Compare commits
127
Commits
master
..
695d26767e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
695d26767e | ||
|
|
b16108c26e | ||
|
|
3c7bd615f8 | ||
|
|
6e7b7709b3 | ||
|
|
dbe4d852b2 | ||
|
|
d746de7e90 | ||
|
|
cb422de218 | ||
|
|
24db9ff5c1 | ||
|
|
1595599a65 | ||
|
|
c0b08a8222 | ||
|
|
ed6b575db3 | ||
|
|
f0e197af3b | ||
|
|
8714266622 | ||
|
|
46b21c01c0 | ||
|
|
075396e17b | ||
|
|
067b697f66 | ||
|
|
f0d06f0070 | ||
|
|
abfe8d1c3d | ||
|
|
d9580bba11 | ||
|
|
26835c2cbb | ||
|
|
b19a5072ba | ||
|
|
ca7ef1ca19 | ||
|
|
dd32e8a04e | ||
|
|
2e46777d12 | ||
|
|
44e04a89d5 | ||
|
|
2e27ae8f72 | ||
|
|
56419a8355 | ||
|
|
c146e03cf1 | ||
|
|
97b1f6bf48 | ||
|
|
cc18bc23f6 | ||
|
|
e30ca52a9a | ||
|
|
1705e9fc2b | ||
|
|
e6113fabdd | ||
|
|
672d8016a8 | ||
|
|
a78ac3442e | ||
|
|
2f97750ae7 | ||
|
|
01780695f0 | ||
|
|
771f6c1dee | ||
|
|
44594b671c | ||
|
|
e036f20944 | ||
|
|
259daa8ad8 | ||
|
|
fefdbada91 | ||
|
|
78fe7cd6b2 | ||
|
|
845c1d3d03 | ||
|
|
c10c8c4f8b | ||
|
|
8f470385b1 | ||
|
|
adac0f59ed | ||
|
|
15eef1f91a | ||
|
|
ee73bbbe4b | ||
|
|
64b9ff2157 | ||
|
|
206b116bf4 | ||
|
|
e0ab051c29 | ||
|
|
6953d43fe3 | ||
|
|
8f61887ba6 | ||
|
|
f472a8ff48 | ||
|
|
18ed5ab966 | ||
|
|
dd926f2035 | ||
|
|
e599b0c4aa | ||
|
|
89bba2e2e1 | ||
|
|
5f55743bd2 | ||
|
|
41e94ab774 | ||
|
|
09b57d87b9 | ||
|
|
f4a8844024 | ||
|
|
bd32fc239d | ||
|
|
5d09f1b64c | ||
|
|
9814f49ec7 | ||
|
|
565d859c98 | ||
|
|
7aa60d8faa | ||
|
|
fec4c3fb82 | ||
|
|
2b40435952 | ||
|
|
439887545f | ||
|
|
1f3029b1a0 | ||
|
|
ba1808fd3f | ||
|
|
250cc5084f | ||
|
|
b5bda4450b | ||
|
|
89fc6844ed | ||
|
|
751adbbedc | ||
|
|
5b6719c018 | ||
|
|
1aa3f08e3a | ||
|
|
c6f5dd9175 | ||
|
|
9aeae36964 | ||
|
|
d84226eac2 | ||
|
|
0788aa4bb4 | ||
|
|
067e47508e | ||
|
|
2e9cfd6915 | ||
|
|
1ab4a1eaa7 | ||
|
|
ad36c84930 | ||
|
|
863ca3058d | ||
|
|
cde69d4d8a | ||
|
|
4b72b7dc65 | ||
|
|
b4e737a6b2 | ||
|
|
435c5c9c36 | ||
|
|
d82b640a79 | ||
|
|
1c4aea7d70 | ||
|
|
71c420f9de | ||
|
|
335210adb9 | ||
|
|
9c36ab1368 | ||
|
|
d8bd8bbf58 | ||
|
|
00b4e81d20 | ||
|
|
d43593c039 | ||
|
|
60fdcabdc9 | ||
|
|
9cc7231e69 | ||
|
|
7e7fd6484b | ||
|
|
b162aa0d25 | ||
|
|
721e9cc677 | ||
|
|
06878062e5 | ||
|
|
6f5a05742d | ||
|
|
e04bd9b347 | ||
|
|
1742ab9cbf | ||
|
|
3817bf5703 | ||
|
|
4bb0a34d49 | ||
|
|
1f97c8b577 | ||
|
|
5799484cf6 | ||
|
|
8a7a0338de | ||
|
|
d0b5bb4a25 | ||
|
|
306a160d6b | ||
|
|
269a7e5234 | ||
|
|
f4df720286 | ||
|
|
17f1d0dc5b | ||
|
|
55ae9ad706 | ||
|
|
1bc5cdf831 | ||
|
|
da7ebf398f | ||
|
|
aae68a6937 | ||
|
|
a3c4355791 | ||
|
|
29930fdef7 | ||
|
|
b9c3aac91f | ||
|
|
79fedb274f |
+153
-2
@@ -1,3 +1,154 @@
|
||||
.venv/
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
test/
|
||||
*.py[co]
|
||||
*$py.class
|
||||
|
||||
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
#lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
pip-wheel-metadata/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
#.env
|
||||
#.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
|
||||
# FlaksFarm
|
||||
config.yaml
|
||||
lib2/
|
||||
.vscode/
|
||||
memo.txt
|
||||
*.zip
|
||||
flaskfarm.sh
|
||||
export.sh
|
||||
run.sh
|
||||
pre_start.sh
|
||||
*.code-workspace
|
||||
false
|
||||
*copy.py
|
||||
*.sh
|
||||
data/
|
||||
tmp/
|
||||
lib/support/site/tving.py
|
||||
lib/support/site/wavve.py
|
||||
lib/support/site/seezn.py
|
||||
lib/support/site/kakaotv.py
|
||||
*.bat
|
||||
output/
|
||||
*.mkv
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
[MESSAGES CONTROL]
|
||||
|
||||
# Disable the message, report, category or checker with the given id(s). You
|
||||
# can either give multiple identifier separated by comma (,) or put this option
|
||||
# multiple time (only on the command line, not in the configuration file where
|
||||
# it should appear only once).
|
||||
disable=missing-module-docstring,missing-class-docstring,missing-function-docstring,broad-except,line-too-long
|
||||
|
||||
ignored-modules=framework
|
||||
Vendored
-5
@@ -1,5 +0,0 @@
|
||||
{
|
||||
"files.associations": {
|
||||
"*.html": "jinja-html"
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,674 @@
|
||||
MIT License
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (c) 2020 joyfuI
|
||||
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.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
Preamble
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
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,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
||||
@@ -1,269 +1,16 @@
|
||||
# youtube-dl_sjva
|
||||
|
||||
[SJVA](https://sjva.me/) 용 [youtube-dl](https://youtube-dl.org/) 플러그인입니다.
|
||||
SJVA에서 유튜브, 네이버TV 등 동영상 사이트 영상을 다운로드할 수 있습니다.
|
||||
|
||||
## 설치
|
||||
|
||||
SJVA에서 "시스템 → 플러그인 → 플러그인 수동 설치" 칸에 저장소 주소를 넣고 설치 버튼을 누르면 됩니다.
|
||||
`https://github.com/joyfuI/youtube-dl`
|
||||
|
||||
## 잡담
|
||||
|
||||
시놀로지 docker 환경에서 테스트했습니다.
|
||||
|
||||
API를 제공합니다. 다른 플러그인에서 동영상 정보나 다운로드를 요청할 수 있습니다.
|
||||
다른 플러그인이 멋대로 다운로드를 중지할 수 없도록 다운로드를 요청할 때 임의의 키를 넘겨받습니다. 중지 요청 시 키가 일치해야 요청이 실행됩니다.
|
||||
|
||||
[youtube-dl](https://github.com/ytdl-org/youtube-dl)의 DMCA 테이크다운 사태 이후, 비슷한 상황을 대비하기 위해 youtube-dl의 포크 프로젝트 [youtube-dlc](https://github.com/blackjack4494/yt-dlc)의 포크 프로젝트(...)인 [yt-dlp](https://github.com/yt-dlp/yt-dlp)를 추가했습니다.
|
||||
설정에서 취향껏 골라서 사용하시면 되며 youtube-dl가 우선 지원됩니다.
|
||||
|
||||
## API
|
||||
|
||||
### 공통사항
|
||||
|
||||
모든 요청은 `POST` 또는 `GET`만 받습니다. 그리고 응답은 `JSON` 형식입니다.
|
||||
모든 요청엔 _플러그인 이름_ 정보가 있어야 합니다. `plugin` 키에 담아서 보내면 됩니다. 만약 _플러그인 이름_ 정보가 없으면 **403 에러**를 반환합니다.
|
||||
요청을 처리하는 과정에서 예외가 발생하면 **500 에러**를 반환합니다. 이건 저한테 로그와 함께 알려주시면 됩니다.
|
||||
모든 응답에는 `errorCode` 키가 있습니다. 코드의 의미는 아래 문단 참고
|
||||
|
||||
#### 에러 코드 (errorCode)
|
||||
|
||||
- `0` - 성공. 문제없음
|
||||
- `1` - 필수 요청 변수가 없음
|
||||
- `2` - 잘못된 동영상 주소
|
||||
- `3` - 인덱스 범위를 벗어남
|
||||
- `4` - 키 값이 일치하지 않음
|
||||
- `5` - 허용되지 않은 값이 있음
|
||||
- `10` - 실패. 요청은 성공하였으나 실행 결과가 실패
|
||||
|
||||
#### Status 타입
|
||||
|
||||
상태를 나타냄
|
||||
|
||||
- `"READY"` - 준비
|
||||
- `"START"` - 분석중
|
||||
- `"DOWNLOADING"` - 다운로드중
|
||||
- `"ERROR"` - 실패
|
||||
- `"FINISHED"` - 변환중
|
||||
- `"STOP"` - 중지
|
||||
- `"COMPLETED"` - 완료
|
||||
|
||||
### /youtube-dl/api/info_dict
|
||||
|
||||
동영상 정보를 반환하는 API
|
||||
|
||||
#### Request
|
||||
|
||||
| 키 | 설명 | 필수 | 타입 |
|
||||
| -------- | ------------- | ---- | ------ |
|
||||
| `plugin` | 플러그인 이름 | O | String |
|
||||
| `url` | 동영상 주소 | O | String |
|
||||
|
||||
#### Response
|
||||
|
||||
| 키 | 설명 | 타입 |
|
||||
| ----------- | ----------- | ------- |
|
||||
| `errorCode` | 에러 코드 | Integer |
|
||||
| `info_dict` | 동영상 정보 | Object |
|
||||
|
||||
동영상 정보(`info_dict` 키)에는 youtube-dl에서 생성한 info_dict 정보가 그대로 들어있습니다. 따라서 이 부분은 직접 주소를 넣어가며 반환되는 정보를 확인해보는 게 좋습니다.
|
||||
간단한 예로 `thumbnail` 키엔 썸네일 주소, `uploader` 키엔 업로더 이름, `title` 키엔 동영상 제목, `duration` 키엔 동영상 길이 등이 들어 있습니다.
|
||||
그리고 만약 주소가 플레이리스트라면 `_type` 키에 `"playlist"`라는 값이 들어 있습니다. 이때는 `entries` 키에 리스트가 들어있어 동영상들의 제목과 ID를 확인할 수 있습니다.
|
||||
|
||||
### /youtube-dl/api/download
|
||||
|
||||
비디오 다운로드 준비를 요청하는 API
|
||||
|
||||
#### Request
|
||||
|
||||
| 키 | 설명 | 필수 | 타입 |
|
||||
| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------- | ---- | ------- |
|
||||
| `plugin` | 플러그인 이름 | O | String |
|
||||
| `key` | 임의의 키. 이후 다운로드를 제어할 때 이 키가 필요함 | O | String |
|
||||
| `url` | 동영상 주소 | O | String |
|
||||
| `filename` | 파일명. 템플릿 규칙은 https://github.com/ytdl-org/youtube-dl/#output-template 참고. 미지정 시 사용자 설정 | X | String |
|
||||
| `save_path` | 저장 폴더 경로. 미지정 시 사용자 설정 | X | String |
|
||||
| `format` | 동영상 포맷. 포맷 지정은 https://github.com/ytdl-org/youtube-dl/#format-selection 참고. 미지정 시 최고 화질 | X | String |
|
||||
| `preferedformat` | 변환할 비디오 포맷. 가능한 포맷은 https://ffmpeg.org/general.html#File-Formats 참고. 미지정 시 변환하지 않음 | X | String |
|
||||
| `preferredcodec` | 추출할 오디오 코덱. 가능한 값은 `"best"`, `"mp3"`, `"aac"`, `"flac"`, `"m4a"`, `"opus"`, `"vorbis"`, `"wav"`. 미지정 시 추출하지 않음 | X | String |
|
||||
| `preferredquality` | 추출한 오디오의 비트레이트. 0 ~ 9 사이의 VBR 퀄리티 값(0에 가까울수록 좋음) 혹은 특정 비트레이트 값. `preferredcodec` 키가 있을 때만 유효. 기본값: `192` | X | Integer |
|
||||
| `dateafter` | 지정한 날짜 이후에 업로드된 동영상만 다운로드. 미지정 시 모두 다운로드 | X | String |
|
||||
| `playlist` | 플레이리스트를 다운로드할 때 범위나 순서 지정. 미지정 시 모두 순서대로 다운로드 | X | String |
|
||||
| `archive` | 다운로드한 동영상의 ID를 기록할 파일 경로. 파일이 이미 있으면 이미 다운로드한 동영상은 다운로드 하지 않음. 미지정 시 기록하지 않음 | X | String |
|
||||
| `start` | 다운로드 준비 후 바로 다운로드를 시작할지 여부. 기본값: `false` | X | Boolean |
|
||||
| `cookiefile` | 다운로드 시 필요한 쿠키 파일 경로 | X | String |
|
||||
| `headers` | 다운로드 시 사용할 HTTP 헤더 정보 | X | String |
|
||||
|
||||
`dateafter` 키에 넣을 수 있는 날짜는 `"YYYYMMDD"` 또는 `"(now|today)[+-][0-9](day|week|month|year)(s)?"` 형식의 문자열입니다.
|
||||
`headers` 키에 넣는 값은 `json` 형식의 문자열입니다.
|
||||
|
||||
`playlist` 키에 넣을 수 있는 값은 `"1-3,7,10-13"` 형식의 범위 또는 `"reverse"`, `"random"`입니다.
|
||||
범위를 넣으면 플레이리스트에서 선택한 것만 다운로드합니다.
|
||||
`"reverse"`를 넣으면 전체 플레이리스트를 역순으로 다운로드합니다.
|
||||
`"random"`을 넣으면 전체 플레이리스트를 랜덤 순서로 다운로드합니다.
|
||||
|
||||
#### Response
|
||||
|
||||
| 키 | 설명 | 타입 |
|
||||
| ----------- | ------------------------------------------------------- | ------- |
|
||||
| `errorCode` | 에러 코드 | Integer |
|
||||
| `index` | 동영상 인덱스. 이후 다운로드를 제어할 때 이 값이 필요함 | Integer |
|
||||
|
||||
### /youtube-dl/api/thumbnail
|
||||
|
||||
썸네일 다운로드 준비를 요청하는 API
|
||||
|
||||
#### Request
|
||||
|
||||
| 키 | 설명 | 필수 | 타입 |
|
||||
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------- | ---- | ------- |
|
||||
| `plugin` | 플러그인 이름 | O | String |
|
||||
| `key` | 임의의 키. 이후 다운로드를 제어할 때 이 키가 필요함 | O | String |
|
||||
| `url` | 동영상 주소 | O | String |
|
||||
| `filename` | 파일명. 템플릿 규칙은 https://github.com/ytdl-org/youtube-dl/#output-template 참고. 미지정 시 사용자 설정 | X | String |
|
||||
| `save_path` | 저장 폴더 경로. 미지정 시 사용자 설정 | X | String |
|
||||
| `all_thumbnails` | 모든 썸네일 다운로드 여부. `false`는 대표 썸네일 하나만 다운로드. 기본값: `false` | X | Boolean |
|
||||
| `dateafter` | 지정한 날짜 이후에 업로드된 동영상만 다운로드. 미지정 시 모두 다운로드 | X | String |
|
||||
| `playlist` | 플레이리스트를 다운로드할 때 범위나 순서 지정. 미지정 시 모두 순서대로 다운로드 | X | String |
|
||||
| `archive` | 다운로드한 동영상의 ID를 기록할 파일 경로. 파일이 이미 있으면 이미 다운로드한 동영상은 다운로드 하지 않음. 미지정 시 기록하지 않음 | X | String |
|
||||
| `start` | 다운로드 준비 후 바로 다운로드를 시작할지 여부. 기본값: `false` | X | Boolean |
|
||||
| `cookiefile` | 다운로드 시 필요한 쿠키 파일 경로 | X | String |
|
||||
| `headers` | 다운로드 시 사용할 HTTP 헤더 정보 | X | String |
|
||||
|
||||
`dateafter` 키에 넣을 수 있는 날짜는 `"YYYYMMDD"` 또는 `"(now|today)[+-][0-9](day|week|month|year)(s)?"` 형식의 문자열입니다.
|
||||
`headers` 키에 넣는 값은 `json` 형식의 문자열입니다.
|
||||
|
||||
`playlist` 키에 넣을 수 있는 값은 `"1-3,7,10-13"` 형식의 범위 또는 `"reverse"`, `"random"`입니다.
|
||||
범위를 넣으면 플레이리스트에서 선택한 것만 다운로드합니다.
|
||||
`"reverse"`를 넣으면 전체 플레이리스트를 역순으로 다운로드합니다.
|
||||
`"random"`을 넣으면 전체 플레이리스트를 랜덤 순서로 다운로드합니다.
|
||||
|
||||
#### Response
|
||||
|
||||
| 키 | 설명 | 타입 |
|
||||
| ----------- | ------------------------------------------------------- | ------- |
|
||||
| `errorCode` | 에러 코드 | Integer |
|
||||
| `index` | 동영상 인덱스. 이후 다운로드를 제어할 때 이 값이 필요함 | Integer |
|
||||
|
||||
### /youtube-dl/api/sub
|
||||
|
||||
자막 다운로드 준비를 요청하는 API
|
||||
|
||||
#### Request
|
||||
|
||||
| 키 | 설명 | 필수 | 타입 |
|
||||
| ------------ | ---------------------------------------------------------------------------------------------------------------------------------- | ---- | ------- |
|
||||
| `plugin` | 플러그인 이름 | O | String |
|
||||
| `key` | 임의의 키. 이후 다운로드를 제어할 때 이 키가 필요함 | O | String |
|
||||
| `url` | 동영상 주소 | O | String |
|
||||
| `filename` | 파일명. 템플릿 규칙은 https://github.com/ytdl-org/youtube-dl/#output-template 참고. 미지정 시 사용자 설정 | X | String |
|
||||
| `save_path` | 저장 폴더 경로. 미지정 시 사용자 설정 | X | String |
|
||||
| `all_subs` | 모든 자막 다운로드 여부. 기본값: `false` | X | Boolean |
|
||||
| `sub_lang` | 자막 언어. 두 자리 국가 코드. 콤마(,)를 구분자로 여러 개 지정 가능. `all_subs` 키가 `false`일 때만 유효. 기본값: `"ko"` | X | String |
|
||||
| `auto_sub` | 자동생성 자막 다운로드 여부. 유튜브 전용. 기본값: `false` | X | Boolean |
|
||||
| `dateafter` | 지정한 날짜 이후에 업로드된 동영상만 다운로드. 미지정 시 모두 다운로드 | X | String |
|
||||
| `playlist` | 플레이리스트를 다운로드할 때 범위나 순서 지정. 미지정 시 모두 순서대로 다운로드 | X | String |
|
||||
| `archive` | 다운로드한 동영상의 ID를 기록할 파일 경로. 파일이 이미 있으면 이미 다운로드한 동영상은 다운로드 하지 않음. 미지정 시 기록하지 않음 | X | String |
|
||||
| `start` | 다운로드 준비 후 바로 다운로드를 시작할지 여부. 기본값: `false` | X | Boolean |
|
||||
| `cookiefile` | 다운로드 시 필요한 쿠키 파일 경로 | X | String |
|
||||
| `headers` | 다운로드 시 사용할 HTTP 헤더 정보 | X | String |
|
||||
|
||||
`dateafter` 키에 넣을 수 있는 날짜는 `"YYYYMMDD"` 또는 `"(now|today)[+-][0-9](day|week|month|year)(s)?"` 형식의 문자열입니다.
|
||||
`headers` 키에 넣는 값은 `json` 형식의 문자열입니다.
|
||||
|
||||
`playlist` 키에 넣을 수 있는 값은 `"1-3,7,10-13"` 형식의 범위 또는 `"reverse"`, `"random"`입니다.
|
||||
범위를 넣으면 플레이리스트에서 선택한 것만 다운로드합니다.
|
||||
`"reverse"`를 넣으면 전체 플레이리스트를 역순으로 다운로드합니다.
|
||||
`"random"`을 넣으면 전체 플레이리스트를 랜덤 순서로 다운로드합니다.
|
||||
|
||||
#### Response
|
||||
|
||||
| 키 | 설명 | 타입 |
|
||||
| ----------- | ------------------------------------------------------- | ------- |
|
||||
| `errorCode` | 에러 코드 | Integer |
|
||||
| `index` | 동영상 인덱스. 이후 다운로드를 제어할 때 이 값이 필요함 | Integer |
|
||||
|
||||
### /youtube-dl/api/start
|
||||
|
||||
다운로드 시작을 요청하는 API
|
||||
|
||||
#### Request
|
||||
|
||||
| 키 | 설명 | 필수 | 타입 |
|
||||
| -------- | ----------------------------------------------------------- | ---- | ------- |
|
||||
| `plugin` | 플러그인 이름 | O | String |
|
||||
| `index` | 제어할 동영상의 인덱스 | O | Integer |
|
||||
| `key` | 제어할 동영상에게 넘겨준 키. 이 값이 일치해야 요청이 실행됨 | O | String |
|
||||
|
||||
#### Response
|
||||
|
||||
| 키 | 설명 | 타입 |
|
||||
| ----------- | ------------------------- | ------- |
|
||||
| `errorCode` | 에러 코드 | Integer |
|
||||
| `status` | 요청을 받았을 당시의 상태 | Status |
|
||||
|
||||
### /youtube-dl/api/stop
|
||||
|
||||
다운로드 중지를 요청하는 API
|
||||
|
||||
#### Request
|
||||
|
||||
| 키 | 설명 | 필수 | 타입 |
|
||||
| -------- | ----------------------------------------------------------- | ---- | ------- |
|
||||
| `plugin` | 플러그인 이름 | O | String |
|
||||
| `index` | 제어할 동영상의 인덱스 | O | Integer |
|
||||
| `key` | 제어할 동영상에게 넘겨준 키. 이 값이 일치해야 요청이 실행됨 | O | String |
|
||||
|
||||
#### Response
|
||||
|
||||
| 키 | 설명 | 타입 |
|
||||
| ----------- | ------------------------- | ------- |
|
||||
| `errorCode` | 에러 코드 | Integer |
|
||||
| `status` | 요청을 받았을 당시의 상태 | Status |
|
||||
|
||||
### /youtube-dl/api/status
|
||||
|
||||
현재 상태를 반환하는 API
|
||||
|
||||
#### Request
|
||||
|
||||
| 키 | 설명 | 필수 | 타입 |
|
||||
| -------- | ----------------------------------------------------------- | ---- | ------- |
|
||||
| `plugin` | 플러그인 이름 | O | String |
|
||||
| `index` | 제어할 동영상의 인덱스 | O | Integer |
|
||||
| `key` | 제어할 동영상에게 넘겨준 키. 이 값이 일치해야 요청이 실행됨 | O | String |
|
||||
|
||||
#### Response
|
||||
|
||||
| 키 | 설명 | 타입 |
|
||||
| ------------ | ----------------------------------------------- | ------- |
|
||||
| `errorCode` | 에러 코드 | Integer |
|
||||
| `status` | 요청을 받았을 당시의 상태 | Status |
|
||||
| `type` | 다운로드 타입. `"video" "thumbnail" "subtitle"` | String |
|
||||
| `start_time` | 다운로드 시작 시간 | String |
|
||||
| `end_time` | 다운로드 종료 시간 | String |
|
||||
| `temp_path` | 임시 폴더 경로 | String |
|
||||
| `save_path` | 저장 폴더 경로 | String |
|
||||
|
||||
`start_time` 키와 `end_time` 키에 들어있는 시간은 `"YYYY-MM-DDThh:mm:ss"` 형식의 문자열입니다.
|
||||
물론 해당 정보가 없으면 null입니다.
|
||||
|
||||
## Changelog
|
||||
|
||||
v0.1.2
|
||||
|
||||
- 유튜브 검색 속도 대폭 개선 (extract_flat 적용)
|
||||
- 검색 결과 캐싱 추가 (5분 유지)
|
||||
- 인피니티 스크롤 안정화 및 최적화
|
||||
- 미니 플레이어 (스크롤 시 오른쪽 하단 고정) 추가
|
||||
- Artplayer 영상 비율 버그 수정 (16:9 aspect-ratio 적용)
|
||||
- UI 개선: 검색 후 초기 메시지 자동 숨김
|
||||
|
||||
v0.1.1
|
||||
|
||||
- 유지보수 업데이트
|
||||
|
||||
v0.1.0
|
||||
|
||||
- 최초 공개
|
||||
### Hi there 👋
|
||||
|
||||
<!--
|
||||
**flaskfarm/flaskfarm** is a ✨ _special_ ✨ repository because its `README.md` (this file) appears on your GitHub profile.
|
||||
|
||||
Here are some ideas to get you started:
|
||||
|
||||
- 🔭 I’m currently working on ...
|
||||
- 🌱 I’m currently learning ...
|
||||
- 👯 I’m looking to collaborate on ...
|
||||
- 🤔 I’m looking for help with ...
|
||||
- 💬 Ask me about ...
|
||||
- 📫 How to reach me: ...
|
||||
- 😄 Pronouns: ...
|
||||
- ⚡ Fun fact: ...
|
||||
-->
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lib'))
|
||||
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
from flask import jsonify
|
||||
|
||||
|
||||
class LogicAbort:
|
||||
@staticmethod
|
||||
def abort(base, code):
|
||||
base["errorCode"] = code
|
||||
return jsonify(base)
|
||||
@@ -0,0 +1,26 @@
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'lib'))
|
||||
|
||||
from support import SupportFile, logger
|
||||
|
||||
|
||||
class ChangeUI:
|
||||
def change(self, target, old, new):
|
||||
if target == 'macro':
|
||||
target_filepath = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'lib', 'framework', 'templates', 'macro.html')
|
||||
text = SupportFile.read_file(target_filepath)
|
||||
SupportFile.write_file(target_filepath, text.replace(old, new))
|
||||
|
||||
def process_args(self):
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--target', default='macro')
|
||||
parser.add_argument('--old', default='btn-outline-primary')
|
||||
parser.add_argument('--new', required=True)
|
||||
args = parser.parse_args()
|
||||
self.change(args.target, args.old, args.new)
|
||||
|
||||
if __name__== "__main__":
|
||||
ChangeUI().process_args()
|
||||
@@ -0,0 +1,48 @@
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'lib'))
|
||||
|
||||
from support import SupportFile, SupportSC, logger
|
||||
|
||||
|
||||
class CodeEncode:
|
||||
def start_folder(self, folderpath):
|
||||
for name in os.listdir(folderpath):
|
||||
filepath = os.path.join(folderpath, name)
|
||||
if os.path.isfile(filepath) and name not in ['setup.py', '__init__.py'] and name.endswith('.py'):
|
||||
self.encode_file(filepath)
|
||||
|
||||
def encode_file(self, filepath):
|
||||
if filepath.endswith(".py") == False:
|
||||
logger.info("is not .py file")
|
||||
return
|
||||
text = SupportFile.read_file(filepath)
|
||||
data = SupportSC.encode(text, 1)
|
||||
SupportFile.write_file(filepath + 'f', data)
|
||||
logger.info(f"Create {os.path.basename(filepath + 'f')}")
|
||||
|
||||
|
||||
def process_args(self):
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--mode', default='encode')
|
||||
parser.add_argument('--source', required=True, help=u'absolute path. folder or file')
|
||||
args = parser.parse_args()
|
||||
if SupportSC.LIBRARY_LOADING == False:
|
||||
logger.error("sc import fail")
|
||||
return
|
||||
if os.path.exists(args.source):
|
||||
if os.path.isdir(args.source):
|
||||
self.start_folder(args.source)
|
||||
elif os.path.isfile(args.source):
|
||||
self.encode_file(args.source)
|
||||
else:
|
||||
logger.error("wrong source path!!")
|
||||
|
||||
|
||||
if __name__== "__main__":
|
||||
CodeEncode().process_args()
|
||||
|
||||
# python C:\work\FlaskFarm\flaskfarm\cli\code_encode.py --source=C:\work\FlaskFarm\data\LOADING\sjva
|
||||
@@ -0,0 +1,69 @@
|
||||
path_data: "."
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
##########################################################################
|
||||
# 데이터 폴더 루트 경로
|
||||
# 윈도우의 경우 폴더 구분 기호 \ 를 두개 사용
|
||||
# 예) data_folder: "C:\\work\\data"
|
||||
# 현재 폴더인 경우 .
|
||||
#path_data: "."
|
||||
|
||||
|
||||
# 개발용 플러그인 경로
|
||||
#path_dev:
|
||||
|
||||
|
||||
# gevent 사용여부
|
||||
# 플러그인 개발이나 termux 환경에서의 실행 같이 특수한 경우에만 false로 사용.
|
||||
# 실행환경에 gevent 관련 패키지가 설치되어 있지 않는다면 값과 상관 없이 false로 동작.
|
||||
#use_gevent: true
|
||||
|
||||
# celery 사용 여부
|
||||
#use_celery: true
|
||||
|
||||
# redis port
|
||||
# celery를 사용하는 경우 사용하는 redis 포트
|
||||
# 환경변수 REDIS_PORT 값이 있는 경우 무시됨.
|
||||
#redis_port: 6379
|
||||
|
||||
# 포트
|
||||
# 생략시 DB 값을 사용.
|
||||
#port: 9999
|
||||
|
||||
# 소스 수정시 재로딩
|
||||
# 두번 로딩되는 것을 감안하여 코딩해야 함.
|
||||
#debug: false
|
||||
|
||||
# 플러그인 업데이트 여부
|
||||
# - true인 경우 로딩시 플러그인을 업데이트 함.
|
||||
# /data/plugins 폴더에 있는 플러그인 만을 대상으로 함.
|
||||
# - debug 값이 true인 경우에는 항상 false
|
||||
#plugin_update: true
|
||||
|
||||
# running_type
|
||||
# termux, entware 인 경우 입력 함.
|
||||
#running_type: "native"
|
||||
|
||||
# 개발용 폴더만 로딩할 경우 사용
|
||||
#plugin_loading_only_devpath: true
|
||||
|
||||
# 로딩할 플러그인 package 명
|
||||
# 타 플러그인과 연동되는 플러그인 개발시 사용.
|
||||
# import 로 런타임에 로딩할 수 있지만 타 패키지 메뉴 등은 표시되지 않음.
|
||||
#plugin_loading_list: ['command', 'flaskcode']
|
||||
|
||||
|
||||
# 로딩 제외할 플러그인 package 명
|
||||
#plugin_except_list: ['terminal', 'membership']
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
# 카테고리
|
||||
# uri 가 plugin인 경우 name 값은 대체
|
||||
|
||||
#- name: "토렌트"
|
||||
# list:
|
||||
# - uri: "rss"
|
||||
|
||||
|
||||
#- name: "기본 기능"
|
||||
# list:
|
||||
# - uri: "terminal"
|
||||
# - uri: "command"
|
||||
# - uri: "flaskfilemanager"
|
||||
# - uri: "flaskcode"
|
||||
# - uri: "number_baseball"
|
||||
|
||||
|
||||
#- name: "링크"
|
||||
# list:
|
||||
# - uri: "https://app.plex.tv"
|
||||
# name: "Plex"
|
||||
# target: "_self"
|
||||
# - uri: "https://www.netflix.com"
|
||||
# name: "Netflix"
|
||||
|
||||
|
||||
- name: "시스템"
|
||||
list:
|
||||
- uri: "system"
|
||||
name: "설정"
|
||||
- uri: "setting"
|
||||
name: "확장 설정"
|
||||
- uri: "system/plugin"
|
||||
name: "플러그인 관리"
|
||||
- uri: "-"
|
||||
- uri: "system/logout"
|
||||
name: "로그아웃"
|
||||
- uri: "system/restart"
|
||||
name: "재시작(업데이트)"
|
||||
- uri: "system/shutdown"
|
||||
#uri: "javascript:shutdown_confirm();"
|
||||
name: "종료"
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# DEFAULT 필수
|
||||
# message id 별로 각각 알림 설정 추가
|
||||
# message id 가 없을 경우 DEFAULT 값 사용
|
||||
# 공통: type, enable_time (시작시간-종료시간. 항상 받을 경우 생략)
|
||||
|
||||
- DEFAULT:
|
||||
- type: 'telegram'
|
||||
token: ''
|
||||
chat_id: ''
|
||||
disable_notification: false
|
||||
enable_time: '09-23'
|
||||
- type: 'discord'
|
||||
webhook: ''
|
||||
enable_time: '09-23'
|
||||
|
||||
|
||||
- system_start:
|
||||
- type: 'telegram'
|
||||
token: ''
|
||||
chat_id: ''
|
||||
disable_notification: false
|
||||
- type: 'discord'
|
||||
webhook: ''
|
||||
@@ -0,0 +1,28 @@
|
||||
#flask
|
||||
Flask
|
||||
Flask-SQLAlchemy
|
||||
Flask-Login
|
||||
Flask-Cors
|
||||
Flask-Markdown
|
||||
Flask-SocketIO
|
||||
python-engineio
|
||||
python-socketio
|
||||
Werkzeug
|
||||
Jinja2
|
||||
|
||||
# common util
|
||||
apscheduler
|
||||
pytz
|
||||
requests
|
||||
discord-webhook
|
||||
pyyaml
|
||||
telepot-mod
|
||||
Flask-Dropzone
|
||||
psutil
|
||||
|
||||
# filemanager
|
||||
pillow
|
||||
|
||||
gevent
|
||||
gevent-websocket
|
||||
pycryptodome
|
||||
@@ -0,0 +1,2 @@
|
||||
celery
|
||||
redis
|
||||
@@ -0,0 +1,2 @@
|
||||
lxml
|
||||
selenium
|
||||
@@ -1,7 +0,0 @@
|
||||
title: "유튜브 다운로더"
|
||||
version: "0.1.2"
|
||||
package_name: "youtube-dl"
|
||||
developer: "flaskfarm"
|
||||
description: "유튜브 다운로드"
|
||||
home: "https://gitea.yommi.duckdns.org/ff_plugins/youtube-dl"
|
||||
more: "https://gitea.yommi.duckdns.org/ff_plugins/youtube-dl/raw/branch/main/README.md"
|
||||
@@ -0,0 +1,25 @@
|
||||
from .init_main import Framework
|
||||
from .version import VERSION
|
||||
|
||||
frame = Framework.get_instance()
|
||||
F = frame
|
||||
logger = frame.logger
|
||||
app = frame.app
|
||||
celery = frame.celery
|
||||
db = frame.db
|
||||
scheduler = frame.scheduler
|
||||
socketio = frame.socketio
|
||||
path_app_root = frame.path_app_root
|
||||
path_data = frame.path_data
|
||||
get_logger = frame.get_logger
|
||||
from flask_login import login_required
|
||||
from support import d
|
||||
|
||||
from .init_declare import User, check_api
|
||||
from .scheduler import Job
|
||||
|
||||
frame.initialize_system()
|
||||
from system.setup import SystemModelSetting
|
||||
|
||||
frame.initialize_plugin()
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import os
|
||||
from functools import wraps
|
||||
|
||||
from flask import abort, request
|
||||
|
||||
|
||||
def check_api(original_function):
|
||||
@wraps(original_function)
|
||||
def wrapper_function(*args, **kwargs): #1
|
||||
from framework import F
|
||||
|
||||
#logger.debug('CHECK API... {} '.format(original_function.__module__))
|
||||
#logger.warning(request.url)
|
||||
#logger.warning(request.form)
|
||||
try:
|
||||
if F.SystemModelSetting.get_bool('auth_use_apikey'):
|
||||
if request.method == 'POST':
|
||||
apikey = request.form['apikey']
|
||||
else:
|
||||
apikey = request.args.get('apikey')
|
||||
#apikey = request.args.get('apikey')
|
||||
if apikey is None or apikey != F.SystemModelSetting.get('auth_apikey'):
|
||||
F.logger.warning('CHECK API : ABORT no match ({})'.format(apikey))
|
||||
F.logger.warning(request.environ.get('HTTP_X_REAL_IP', request.remote_addr))
|
||||
abort(403)
|
||||
return
|
||||
except Exception as e:
|
||||
F.logger.warning('CHECK API : ABORT exception')
|
||||
abort(403)
|
||||
return
|
||||
return original_function(*args, **kwargs) #2
|
||||
return wrapper_function
|
||||
|
||||
# Suuport를 logger 생성전에 쓰지 않기 위해 중복 선언
|
||||
import logging
|
||||
|
||||
|
||||
class CustomFormatter(logging.Formatter):
|
||||
"""Logging Formatter to add colors and count warning / errors"""
|
||||
|
||||
grey = "\x1b[38;21m"
|
||||
yellow = "\x1b[33;21m"
|
||||
red = "\x1b[31;21m"
|
||||
bold_red = "\x1b[31;1m"
|
||||
reset = "\x1b[0m"
|
||||
green = "\x1B[32m"
|
||||
# pathname filename
|
||||
#format = "[%(asctime)s|%(name)s|%(levelname)s - %(message)s (%(filename)s:%(lineno)d)"
|
||||
|
||||
__format = '[{yellow}%(asctime)s{reset}|{color}%(levelname)s{reset}|{green}%(name)s{reset} %(pathname)s:%(lineno)s] {color}%(message)s{reset}' if os.environ.get('LOGGER_PATHNAME', "False") == "True" else '[{yellow}%(asctime)s{reset}|{color}%(levelname)s{reset}|{green}%(name)s{reset} %(filename)s:%(lineno)s] {color}%(message)s{reset}'
|
||||
|
||||
FORMATS = {
|
||||
logging.DEBUG: __format.format(color=grey, reset=reset, yellow=yellow, green=green),
|
||||
logging.INFO: __format.format(color=green, reset=reset, yellow=yellow, green=green),
|
||||
logging.WARNING: __format.format(color=yellow, reset=reset, yellow=yellow, green=green),
|
||||
logging.ERROR: __format.format(color=red, reset=reset, yellow=yellow, green=green),
|
||||
logging.CRITICAL: __format.format(color=bold_red, reset=reset, yellow=yellow, green=green)
|
||||
}
|
||||
|
||||
def format(self, record):
|
||||
log_fmt = self.FORMATS.get(record.levelno)
|
||||
formatter = logging.Formatter(log_fmt)
|
||||
return formatter.format(record)
|
||||
|
||||
|
||||
|
||||
class User:
|
||||
def __init__(self, user_id, email=None, passwd_hash=None, authenticated=False):
|
||||
self.user_id = user_id
|
||||
self.email = email
|
||||
self.passwd_hash = passwd_hash
|
||||
self.authenticated = authenticated
|
||||
|
||||
def __repr__(self):
|
||||
r = {
|
||||
'user_id': self.user_id,
|
||||
'email': self.email,
|
||||
'passwd_hash': self.passwd_hash,
|
||||
'authenticated': self.authenticated,
|
||||
}
|
||||
return str(r)
|
||||
|
||||
def can_login(self, passwd_hash):
|
||||
#from support import SupportAES
|
||||
#tmp = SupportAES.decrypt(self.passwd_hash)
|
||||
import hashlib
|
||||
enc = hashlib.md5()
|
||||
enc.update(passwd_hash.encode())
|
||||
hash = enc.hexdigest()
|
||||
#return True
|
||||
return self.passwd_hash == hash
|
||||
|
||||
def is_active(self):
|
||||
return True
|
||||
|
||||
def get_id(self):
|
||||
return self.user_id
|
||||
|
||||
def is_authenticated(self):
|
||||
return self.authenticated
|
||||
|
||||
def is_anonymous(self):
|
||||
return False
|
||||
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
import yaml
|
||||
from flask import Flask
|
||||
from flask_cors import CORS
|
||||
from flask_login import LoginManager, login_required
|
||||
from flask_socketio import SocketIO
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flaskext.markdown import Markdown
|
||||
from pytz import timezone, utc
|
||||
|
||||
from .init_declare import CustomFormatter, check_api
|
||||
|
||||
|
||||
class Framework:
|
||||
__instance = None
|
||||
|
||||
@classmethod
|
||||
def get_instance(cls):
|
||||
if cls.__instance == None:
|
||||
cls.__instance = Framework()
|
||||
return cls.__instance
|
||||
|
||||
|
||||
def __init__(self):
|
||||
self.logger = None
|
||||
self.app = None
|
||||
self.celery = None
|
||||
self.db = None
|
||||
self.scheduler = None
|
||||
self.socketio = None
|
||||
self.path_app_root = None
|
||||
self.path_data = None
|
||||
self.users = {}
|
||||
|
||||
self.__level_unset_logger_list = []
|
||||
self.__logger_list = []
|
||||
self.__exit_code = -1
|
||||
self.login_manager = None
|
||||
#self.plugin_instance_list = {}
|
||||
#self.plugin_menus = {}
|
||||
|
||||
# 그냥 F. 로 접근 하게....
|
||||
self.SystemModelSetting = None
|
||||
self.Job = None
|
||||
self.login_required = login_required
|
||||
self.check_api = check_api
|
||||
self.__initialize()
|
||||
|
||||
|
||||
def __initialize(self):
|
||||
os.environ["PYTHONUNBUFFERED"] = "1"
|
||||
os.environ['FF'] = "true"
|
||||
self.__config_initialize("first")
|
||||
self.__make_default_dir()
|
||||
|
||||
self.logger = self.get_logger(__package__)
|
||||
import support
|
||||
|
||||
self.__prepare_starting()
|
||||
self.app = Flask(__name__)
|
||||
self.__config_initialize('flask')
|
||||
|
||||
self.__init_db()
|
||||
|
||||
if True or self.config['run_flask']:
|
||||
from .scheduler import Job, Scheduler
|
||||
self.scheduler = Scheduler(self)
|
||||
self.Job = Job
|
||||
|
||||
if self.config['use_gevent']:
|
||||
self.socketio = SocketIO(self.app, cors_allowed_origins="*")
|
||||
else:
|
||||
self.socketio = SocketIO(self.app, cors_allowed_origins="*", async_mode='threading')
|
||||
|
||||
CORS(self.app)
|
||||
Markdown(self.app)
|
||||
|
||||
self.login_manager = LoginManager()
|
||||
self.login_manager.init_app(self.app)
|
||||
self.login_manager.login_view = "/system/login"
|
||||
|
||||
self.celery = self.__init_celery()
|
||||
|
||||
from flask_dropzone import Dropzone
|
||||
self.app.config.update(
|
||||
DROPZONE_MAX_FILE_SIZE = 102400,
|
||||
DROPZONE_TIMEOUT = 5*60*1000,
|
||||
#DROPZONE_ALLOWED_FILE_CUSTOM = True,
|
||||
#DROPZONE_ALLOWED_FILE_TYPE = 'default, image, audio, video, text, app, *.*',
|
||||
)
|
||||
self.dropzone = Dropzone(self.app)
|
||||
|
||||
|
||||
def __init_db(self):
|
||||
# https://flask-sqlalchemy.palletsprojects.com/en/3.0.x/config/#flask_sqlalchemy.config.SQLALCHEMY_BINDS
|
||||
# 어떤 편법도 불가. db를 사용하지 않아도 파일이 생김.
|
||||
db_path = os.path.join(self.config['path_data'], 'db', 'system.db')
|
||||
self.app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{db_path}?check_same_thread=False' # 3.0에서 필수
|
||||
self.app.config['SQLALCHEMY_BINDS'] = {'system':f'sqlite:///{db_path}?check_same_thread=False'}
|
||||
self.app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||
|
||||
_ = os.path.join(self.config['path_data'], 'plugins')
|
||||
plugins = []
|
||||
if os.path.exists(_):
|
||||
plugins = os.listdir(_)
|
||||
|
||||
if self.config['path_dev'] != None:
|
||||
if type(self.config['path_dev']) == type(''):
|
||||
plugin_path_list = [self.config['path_dev']]
|
||||
elif type(self.config['path_dev']) == type([]):
|
||||
plugin_path_list = self.config['path_dev']
|
||||
for __ in plugin_path_list:
|
||||
if os.path.exists(__):
|
||||
plugins += os.listdir(__)
|
||||
|
||||
for package_name in plugins:
|
||||
db_path = os.path.join(self.config['path_data'], 'db', f'{package_name}.db')
|
||||
self.app.config['SQLALCHEMY_BINDS'][package_name] = f'sqlite:///{db_path}?check_same_thread=False'
|
||||
self.db = SQLAlchemy(self.app, session_options={"autoflush": False, "expire_on_commit": False})
|
||||
#with self.app.app_context():
|
||||
# self.db.session.expunge_all()
|
||||
|
||||
|
||||
def __init_celery(self):
|
||||
try:
|
||||
from celery import Celery
|
||||
|
||||
#if frame.config['use_celery'] == False or platform.system() == 'Windows':
|
||||
if self.config['use_celery'] == False:
|
||||
raise Exception('no celery')
|
||||
|
||||
redis_port = os.environ.get('REDIS_PORT', None)
|
||||
if redis_port == None:
|
||||
redis_port = self.config.get('redis_port', None)
|
||||
if redis_port == None:
|
||||
redis_port = '6379'
|
||||
|
||||
|
||||
self.app.config['CELERY_BROKER_URL'] = 'redis://localhost:%s/0' % redis_port
|
||||
self.app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:%s/0' % redis_port
|
||||
celery = Celery(self.app.name, broker=self.app.config['CELERY_BROKER_URL'], backend=self.app.config['CELERY_RESULT_BACKEND'])
|
||||
celery.conf['CELERY_ENABLE_UTC'] = False
|
||||
celery.conf.update(
|
||||
task_serializer='pickle',
|
||||
result_serializer='pickle',
|
||||
accept_content=['pickle'],
|
||||
timezone='Asia/Seoul'
|
||||
)
|
||||
from celery import bootsteps
|
||||
from click import Option
|
||||
celery.user_options['worker'].add(Option(('--config_filepath',), help=''),)
|
||||
celery.user_options['worker'].add(Option(('--running_type',), help=''),)
|
||||
class CustomArgs(bootsteps.Step):
|
||||
def __init__(self, worker, config_filepath=None, running_type=None, **options):
|
||||
from . import F
|
||||
F.logger.info(f"celery config_filepath: {config_filepath}")
|
||||
F.logger.info(f"celery running_type: {running_type}")
|
||||
#F.logger.info(f"celery running_type: {options}")
|
||||
celery.steps['worker'].add(CustomArgs)
|
||||
except Exception as e:
|
||||
if self.config['use_celery']:
|
||||
self.logger.error('CELERY!!!')
|
||||
self.logger.error(f'Exception:{str(e)}')
|
||||
self.logger.error(traceback.format_exc())
|
||||
else:
|
||||
self.logger.info("use_celery = False")
|
||||
|
||||
def dummy_func():
|
||||
pass
|
||||
|
||||
class celery(object):
|
||||
class task(object):
|
||||
def __init__(self, *args, **kwargs):
|
||||
if len(args) > 0:
|
||||
self.f = args[0]
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
if len(args) > 0 and type(args[0]) == type(dummy_func):
|
||||
return args[0]
|
||||
self.f(*args, **kwargs)
|
||||
return celery
|
||||
|
||||
|
||||
def initialize_system(self):
|
||||
from system.setup import P
|
||||
SystemInstance = P
|
||||
try:
|
||||
with self.app.app_context():
|
||||
self.db.create_all()
|
||||
except Exception as e:
|
||||
self.logger.error('CRITICAL db.create_all()!!!')
|
||||
self.logger.error(f'Exception:{str(e)}')
|
||||
self.logger.error(traceback.format_exc())
|
||||
self.SystemModelSetting = SystemInstance.ModelSetting
|
||||
SystemInstance.plugin_load()
|
||||
self.app.register_blueprint(SystemInstance.blueprint)
|
||||
self.config['flag_system_loading'] = True
|
||||
self.__config_initialize('member')
|
||||
self.__config_initialize('system_loading_after')
|
||||
|
||||
|
||||
def initialize_plugin(self):
|
||||
from system.setup import P as SP
|
||||
|
||||
from .init_web import jinja_initialize
|
||||
jinja_initialize(self.app)
|
||||
|
||||
from .init_plugin import PluginManager
|
||||
self.PluginManager = PluginManager
|
||||
PluginManager.plugin_update()
|
||||
PluginManager.plugin_init()
|
||||
PluginManager.plugin_menus['system'] = {'menu':SP.menu, 'match':False}
|
||||
|
||||
from .init_menu import MenuManager
|
||||
MenuManager.init_menu()
|
||||
self.logger.info("메뉴 구성 완료")
|
||||
|
||||
if self.config['run_flask']:
|
||||
if self.config.get('port') == None:
|
||||
self.config['port'] = self.SystemModelSetting.get_int('port')
|
||||
|
||||
from . import init_route, log_viewer
|
||||
|
||||
self.__make_default_logger()
|
||||
self.__config_initialize("last")
|
||||
self.logger.info('### LAST')
|
||||
self.logger.info(f"### PORT: {self.config.get('port')}")
|
||||
self.logger.info('### Now you can access App by webbrowser!!')
|
||||
|
||||
|
||||
def __prepare_starting(self):
|
||||
# 여기서 monkey.patch시 너무 늦다고 문제 발생
|
||||
pass
|
||||
|
||||
|
||||
###################################################
|
||||
# 환경
|
||||
###################################################
|
||||
def __config_initialize(self, mode):
|
||||
if mode == "first":
|
||||
self.config = {}
|
||||
self.config['os'] = platform.system()
|
||||
self.config['flag_system_loading'] = False
|
||||
#self.config['run_flask'] = True if sys.argv[0].endswith('main.py') else False
|
||||
self.config['run_celery'] = True if sys.argv[0].find('celery') != -1 else False
|
||||
self.config['run_flask'] = not self.config['run_celery']
|
||||
self.config['path_app'] = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
if self.config['os'] == 'Windows' and self.config['path_app'][0] != '/':
|
||||
self.config['path_app'] = self.config['path_app'][0].upper() + self.config['path_app'][1:]
|
||||
self.path_app_root = self.config['path_app']
|
||||
self.config['path_working'] = os.getcwd()
|
||||
if os.environ.get('RUNNING_TYPE', None) != None:
|
||||
self.config['running_type'] = os.environ.get('RUNNING_TYPE')
|
||||
self.config['export_filepath'] = os.path.join(self.config['path_app'], 'export.sh')
|
||||
self.config['exist_export'] = os.path.exists(self.config['export_filepath'])
|
||||
self.config['recent_version'] = '--'
|
||||
self.__process_args()
|
||||
self.__load_config()
|
||||
self.__init_define()
|
||||
self.config['menu_yaml_filepath'] = os.path.join(self.config['path_data'], 'db', 'menu.yaml')
|
||||
self.config['notify_yaml_filepath'] = os.path.join(self.config['path_data'], 'db', 'notify.yaml')
|
||||
if 'running_type' not in self.config:
|
||||
self.config['running_type'] = 'native'
|
||||
|
||||
elif mode == "flask":
|
||||
self.app.secret_key = os.urandom(24)
|
||||
self.app.config['TEMPLATES_AUTO_RELOAD'] = True
|
||||
self.app.config['JSON_AS_ASCII'] = False
|
||||
elif mode == 'system_loading_after':
|
||||
pass
|
||||
elif mode == 'last':
|
||||
db_foder = os.path.join(self.config['path_data'], 'db')
|
||||
for name in os.listdir(db_foder):
|
||||
if name.endswith('.db'):
|
||||
db_filepath = os.path.join(db_foder, name)
|
||||
try:
|
||||
if os.stat(db_filepath).st_size == 0:
|
||||
os.remove(db_filepath)
|
||||
self.logger.debug(f"REMOVE {db_filepath}")
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
def __init_define(self):
|
||||
self.config['DEFINE'] = {}
|
||||
# 이건 필요 없음
|
||||
self.config['DEFINE']['GIT_VERSION_URL'] = 'https://raw.githubusercontent.com/flaskfarm/flaskfarm/main/lib/framework/version.py'
|
||||
self.config['DEFINE']['CHANGELOG'] = 'https://flaskfarm.github.io/posts/changelog'
|
||||
|
||||
|
||||
|
||||
def __process_args(self):
|
||||
# celery 에서 args 처리시 문제 발생.
|
||||
if self.config['run_flask']:
|
||||
import argparse
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--config', default='.', help='config filepath. Default: {current folder}/config.yaml')
|
||||
parser.add_argument('--repeat', default=0, type=int, help=u'Do not set. This value is set by automatic')
|
||||
args = parser.parse_args()
|
||||
self.config['arg_repeat'] = args.repeat
|
||||
self.config['arg_config'] = args.config
|
||||
else:
|
||||
# 아주 안좋은 구조..
|
||||
# celery user_options으로 configfilepath를 받은 후 처리해야하나, 로그파일 경로 등에서 데이터 폴더 위치를 미리 사용하는 경우가 많다.
|
||||
# sys.argv에서 데이터 경로를 바로 가져와서 사용.
|
||||
self.config['arg_repeat'] = 0
|
||||
#self.config['arg_config'] = sys.argv[-1].split('=')[-1]
|
||||
#self.config['arg_config'] = sys.argv[-1].split('=')[-1]
|
||||
for tmp in sys.argv:
|
||||
if tmp.startswith('--config_filepath'):
|
||||
self.config['arg_config'] = tmp.split('=')[1]
|
||||
#break
|
||||
elif tmp.startswith('--running_type'):
|
||||
self.config['running_type'] = tmp.split('=')[1]
|
||||
|
||||
#self.config['arg_config'] =
|
||||
|
||||
def __load_config(self):
|
||||
#if self.config['run_flask']:
|
||||
if self.config['arg_config'] == '.':
|
||||
#self.config['config_filepath'] = os.path.join(self.path_app_root, 'config.yaml')
|
||||
self.config['config_filepath'] = os.path.join(self.config['path_working'], 'config.yaml')
|
||||
else:
|
||||
self.config['config_filepath'] = self.config['arg_config']
|
||||
if os.path.exists(self.config['config_filepath']) == False:
|
||||
if self.config.get('running_type', '').startswith('docker'):
|
||||
with open(self.config['config_filepath'], 'w', encoding='utf8') as f:
|
||||
yaml.dump({'path_data':'/data'}, f, default_flow_style=False, allow_unicode=True)
|
||||
else:
|
||||
shutil.copy(
|
||||
os.path.join(self.path_app_root, 'files', 'config.yaml.template'),
|
||||
self.config['config_filepath']
|
||||
)
|
||||
with open(self.config['config_filepath'], encoding='utf8') as file:
|
||||
data = yaml.load(file, Loader=yaml.FullLoader)
|
||||
for key, value in data.items():
|
||||
if key == 'running_type' and value not in ['termux', 'entware']:
|
||||
continue
|
||||
self.config[key] = value
|
||||
|
||||
if self.config['path_data'] == '.':
|
||||
self.config['path_data'] = self.config['path_working']
|
||||
# 예외적으로 현재폴더가 app일 경우 지저분해지는 것을 방지하기 위해 data 로 지정
|
||||
if self.config['path_data'] == self.config['path_working']:
|
||||
self.config['path_data'] = os.path.join(self.config['path_working'], 'data')
|
||||
self.path_data = self.config['path_data']
|
||||
|
||||
if self.config.get('use_gevent') == None:
|
||||
self.config['use_gevent'] = True
|
||||
if self.config.get('use_celery') == None:
|
||||
self.config['use_celery'] = True
|
||||
if self.config.get('debug') == None:
|
||||
self.config['debug'] = False
|
||||
if self.config.get('plugin_update') == None:
|
||||
self.config['plugin_update'] = True
|
||||
if self.config.get('plugin_loading_only_devpath') == None:
|
||||
self.config['plugin_loading_only_devpath'] = False
|
||||
if self.config.get('plugin_loading_list') == None:
|
||||
self.config['plugin_loading_list'] = []
|
||||
if self.config.get('plugin_except_list') == None:
|
||||
self.config['plugin_except_list'] = []
|
||||
if self.config.get('path_dev') == None:
|
||||
self.config['path_dev'] = None
|
||||
|
||||
|
||||
def __make_default_dir(self):
|
||||
os.makedirs(self.config['path_data'], exist_ok=True)
|
||||
tmp = os.path.join(self.config['path_data'], 'tmp')
|
||||
try:
|
||||
import shutil
|
||||
if os.path.exists(tmp):
|
||||
shutil.rmtree(tmp)
|
||||
except:
|
||||
pass
|
||||
sub = ['db', 'log', 'tmp']
|
||||
for item in sub:
|
||||
tmp = os.path.join(self.config['path_data'], item)
|
||||
os.makedirs(tmp, exist_ok=True)
|
||||
|
||||
###################################################
|
||||
|
||||
|
||||
|
||||
|
||||
###################################################
|
||||
# 로그
|
||||
###################################################
|
||||
def get_logger(self, name, from_command=False):
|
||||
logger = logging.getLogger(name)
|
||||
if not logger.handlers:
|
||||
level = logging.DEBUG
|
||||
try:
|
||||
if self.config['flag_system_loading']:
|
||||
try:
|
||||
from system import SystemModelSetting
|
||||
level = SystemModelSetting.get_int('log_level')
|
||||
except:
|
||||
level = logging.DEBUG
|
||||
if self.__level_unset_logger_list is not None:
|
||||
for item in self.__level_unset_logger_list:
|
||||
item.setLevel(level)
|
||||
self.__level_unset_logger_list = None
|
||||
else:
|
||||
self.__level_unset_logger_list.append(logger)
|
||||
if name.startswith('apscheduler'):
|
||||
level = logging.CRITICAL
|
||||
else:
|
||||
self.__logger_list.append(logger)
|
||||
except:
|
||||
pass
|
||||
logger.setLevel(level)
|
||||
def customTime(*args):
|
||||
utc_dt = utc.localize(datetime.utcnow())
|
||||
my_tz = timezone("Asia/Seoul")
|
||||
converted = utc_dt.astimezone(my_tz)
|
||||
return converted.timetuple()
|
||||
|
||||
if from_command == False:
|
||||
file_formatter = logging.Formatter(u'[%(asctime)s|%(levelname)s|%(filename)s:%(lineno)s] %(message)s')
|
||||
else:
|
||||
file_formatter = logging.Formatter(u'[%(asctime)s] %(message)s')
|
||||
|
||||
file_formatter.converter = customTime
|
||||
file_max_bytes = 1 * 1024 * 1024
|
||||
fileHandler = logging.handlers.RotatingFileHandler(filename=os.path.join(self.path_data, 'log', f'{name}.log'), maxBytes=file_max_bytes, backupCount=5, encoding='utf8', delay=True)
|
||||
fileHandler.setFormatter(file_formatter)
|
||||
logger.addHandler(fileHandler)
|
||||
if from_command == False:
|
||||
streamHandler = logging.StreamHandler()
|
||||
streamHandler.setFormatter(CustomFormatter())
|
||||
logger.addHandler(streamHandler)
|
||||
return logger
|
||||
|
||||
|
||||
def __make_default_logger(self):
|
||||
self.get_logger('apscheduler.scheduler')
|
||||
self.get_logger('apscheduler.executors.default')
|
||||
try: logging.getLogger('socketio').setLevel(logging.ERROR)
|
||||
except: pass
|
||||
try: logging.getLogger('engineio').setLevel(logging.ERROR)
|
||||
except: pass
|
||||
try: logging.getLogger('apscheduler.scheduler').setLevel(logging.ERROR)
|
||||
except: pass
|
||||
try: logging.getLogger('apscheduler.executors.default').setLevel(logging.ERROR)
|
||||
except: pass
|
||||
try: logging.getLogger('werkzeug').setLevel(logging.ERROR)
|
||||
except: pass
|
||||
|
||||
def set_level(self, level):
|
||||
try:
|
||||
for l in self.__logger_list:
|
||||
l.setLevel(level)
|
||||
self.__make_default_logger()
|
||||
except:
|
||||
pass
|
||||
###################################################
|
||||
|
||||
|
||||
def start(self):
|
||||
host = '0.0.0.0'
|
||||
for i in range(5):
|
||||
try:
|
||||
#self.logger.debug(d(self.config))
|
||||
# allow_unsafe_werkzeug=True termux nohup 실행시 필요함
|
||||
#if self.config['running_type'] == 'termux':
|
||||
# self.socketio.run(self.app, host=host, port=self.config['port'], debug=self.config['debug'], use_reloader=self.config['debug'], allow_unsafe_werkzeug=True)
|
||||
#else:
|
||||
self.socketio.run(self.app, host=host, port=self.config['port'], debug=self.config['debug'], use_reloader=self.config['debug'])
|
||||
self.logger.warning(f"EXIT CODE : {self.__exit_code}")
|
||||
# 2021-05-18
|
||||
if self.config['running_type'] in ['termux', 'entware']:
|
||||
os._exit(self.__exit_code)
|
||||
else:
|
||||
if self.__exit_code != -1:
|
||||
sys.exit(self.__exit_code)
|
||||
else:
|
||||
self.logger.warning(f"framework.exit_code is -1")
|
||||
break
|
||||
except Exception as exception:
|
||||
self.logger.error(f"Start ERROR : {str(exception)}")
|
||||
host = '127.0.0.1'
|
||||
time.sleep(10*i)
|
||||
continue
|
||||
except KeyboardInterrupt:
|
||||
self.logger.error('KeyboardInterrupt !!')
|
||||
|
||||
|
||||
#except SystemExit:
|
||||
# return
|
||||
#sys.exit(self.__exit_code)
|
||||
|
||||
|
||||
# system 플러그인에서 콜
|
||||
def restart(self):
|
||||
self.__exit_code = 1
|
||||
self.__app_close()
|
||||
|
||||
def shutdown(self):
|
||||
self.__exit_code = 0
|
||||
self.__app_close()
|
||||
|
||||
def __app_close(self):
|
||||
try:
|
||||
from support import SupportSubprocess
|
||||
SupportSubprocess.all_process_close()
|
||||
from .init_plugin import PluginManager
|
||||
PluginManager.plugin_unload()
|
||||
with self.app.test_request_context():
|
||||
self.socketio.stop()
|
||||
except Exception as exception:
|
||||
self.logger.error('Exception:%s', exception)
|
||||
self.logger.error(traceback.format_exc())
|
||||
|
||||
def get_recent_version(self):
|
||||
try:
|
||||
import requests
|
||||
text = requests.get(self.config['DEFINE']['GIT_VERSION_URL']).text
|
||||
self.config['recent_version'] = text.split('=')[1].strip().strip('"')
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.error(f'Exception:{str(e)}')
|
||||
self.logger.error(traceback.format_exc())
|
||||
self.config['recent_version'] = '확인 실패'
|
||||
return False
|
||||
@@ -0,0 +1,93 @@
|
||||
import os
|
||||
import shutil
|
||||
|
||||
from support import SupportYaml, d
|
||||
|
||||
from framework import F
|
||||
|
||||
|
||||
class MenuManager:
|
||||
menu_map = None
|
||||
|
||||
@classmethod
|
||||
def __load_menu_yaml(cls):
|
||||
menu_yaml_filepath = os.path.join(F.config['path_data'], 'db', 'menu.yaml')
|
||||
if os.path.exists(menu_yaml_filepath) == False:
|
||||
shutil.copy(
|
||||
os.path.join(F.config['path_app'], 'files', 'menu.yaml.template'),
|
||||
menu_yaml_filepath
|
||||
)
|
||||
cls.menu_map = SupportYaml.read_yaml(menu_yaml_filepath)
|
||||
|
||||
|
||||
@classmethod
|
||||
def init_menu(cls):
|
||||
cls.__load_menu_yaml()
|
||||
from .init_plugin import PluginManager
|
||||
plugin_menus = PluginManager.plugin_menus
|
||||
copy_map = []
|
||||
|
||||
for category in cls.menu_map:
|
||||
if 'uri' in category:
|
||||
copy_map.append(category)
|
||||
continue
|
||||
cate_count = 0
|
||||
|
||||
tmp_cate_list = []
|
||||
for item in category['list']:
|
||||
if item['uri'] in plugin_menus:
|
||||
plugin_menus[item['uri']]['match'] = True
|
||||
tmp_cate_list.append(plugin_menus[item['uri']]['menu'])
|
||||
cate_count += 1
|
||||
elif item['uri'].startswith('http'):
|
||||
tmp_cate_list.append({
|
||||
'uri': item['uri'],
|
||||
'name': item['name'],
|
||||
'target': item.get('target', '_blank')
|
||||
})
|
||||
cate_count += 1
|
||||
elif (len(item['uri'].split('/')) > 1 and item['uri'].split('/')[0] in plugin_menus) or item['uri'].startswith('javascript') or item['uri'] in ['-']:
|
||||
tmp_cate_list.append({
|
||||
'uri': item['uri'],
|
||||
'name': item.get('name', ''),
|
||||
})
|
||||
cate_count += 1
|
||||
elif item['uri'] == 'setting':
|
||||
if len(PluginManager.setting_menus) > 0:
|
||||
tmp_cate_list.append({
|
||||
'uri': item['uri'],
|
||||
'name': item.get('name', ''),
|
||||
'list': PluginManager.setting_menus
|
||||
})
|
||||
|
||||
if cate_count > 0:
|
||||
copy_map.append({
|
||||
'name': category['name'],
|
||||
'list': tmp_cate_list,
|
||||
'count': cate_count
|
||||
})
|
||||
cls.menu_map = copy_map
|
||||
|
||||
make_dummy_cate = False
|
||||
for name, plugin_menu in plugin_menus.items():
|
||||
#F.logger.info(d(plugin_menu))
|
||||
#if 'uri' not in plugin_menu['menu']:
|
||||
# continue
|
||||
if plugin_menu['match'] == False:
|
||||
if make_dummy_cate == False:
|
||||
make_dummy_cate = True
|
||||
cls.menu_map.insert(len(cls.menu_map)-1, {
|
||||
'name':'미분류', 'count':0, 'list':[]
|
||||
})
|
||||
|
||||
c = cls.menu_map[-2]
|
||||
c['count'] += 1
|
||||
c['list'].append(plugin_menu['menu'])
|
||||
|
||||
#F.logger.warning(d(cls.menu_map))
|
||||
|
||||
|
||||
@classmethod
|
||||
def get_menu_map(cls):
|
||||
#F.logger.warning(d(cls.menu_map))
|
||||
return cls.menu_map
|
||||
@@ -0,0 +1,405 @@
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import sys
|
||||
import threading
|
||||
import traceback
|
||||
import zipfile
|
||||
|
||||
import requests
|
||||
from support import SupportFile, SupportSubprocess, SupportYaml
|
||||
|
||||
from framework import F
|
||||
|
||||
|
||||
class PluginManager:
|
||||
plugin_list = {}
|
||||
plugin_menus = {}
|
||||
setting_menus = []
|
||||
all_package_list = {}
|
||||
|
||||
|
||||
@classmethod
|
||||
def get_plugin_name_list(cls):
|
||||
plugins = []
|
||||
#2019-07-17
|
||||
try:
|
||||
plugin_path = os.path.join(F.config['path_data'], 'plugins')
|
||||
if os.path.exists(plugin_path) == True and os.path.isdir(plugin_path) == True:
|
||||
sys.path.insert(1, plugin_path)
|
||||
tmps = os.listdir(plugin_path)
|
||||
add_plugin_list = []
|
||||
for t in tmps:
|
||||
if not t.startswith('_') and os.path.isdir(os.path.join(plugin_path, t)):
|
||||
add_plugin_list.append(t)
|
||||
cls.all_package_list[t] = {'pos':'normal', 'path':os.path.join(plugin_path, t), 'loading':(F.config.get('plugin_loading_only_devpath', None) != True)}
|
||||
|
||||
plugins = plugins + add_plugin_list
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
|
||||
if F.config.get('plugin_loading_only_devpath', None) == True:
|
||||
plugins = []
|
||||
|
||||
# 2018-09-04
|
||||
try:
|
||||
#plugin_path = F.SystemModelSetting.get('plugin_dev_path')
|
||||
plugin_path = F.config['path_dev']
|
||||
plugin_path_list = []
|
||||
if type(plugin_path) == type(''):
|
||||
plugin_path_list = [plugin_path]
|
||||
elif type(plugin_path) == type([]):
|
||||
plugin_path_list = plugin_path
|
||||
|
||||
for __ in plugin_path_list:
|
||||
if __ != None and __ != '':
|
||||
if os.path.exists(__):
|
||||
sys.path.insert(0, __)
|
||||
tmps = os.listdir(__)
|
||||
add_plugin_list = []
|
||||
for t in tmps:
|
||||
if not t.startswith('_') and os.path.isdir(os.path.join(__, t)):
|
||||
add_plugin_list.append(t)
|
||||
cls.all_package_list[t] = {'pos':'dev', 'path':os.path.join(__, t), 'loading':True}
|
||||
plugins = plugins + add_plugin_list
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
|
||||
# plugin_loading_list
|
||||
try:
|
||||
plugin_loading_list = F.config.get('plugin_loading_list', None)
|
||||
if plugin_loading_list != None and (type(plugin_loading_list) == type([]) and len(plugin_loading_list)) > 0:
|
||||
new_plugins = []
|
||||
for _ in plugins:
|
||||
if _ in plugin_loading_list:
|
||||
new_plugins.append(_)
|
||||
else:
|
||||
cls.all_package_list[_]['loading'] = False
|
||||
cls.all_package_list[_]['status'] = 'not_include_loading_list'
|
||||
plugins = new_plugins
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
|
||||
# plugin_except_list
|
||||
try:
|
||||
plugin_except_list = F.config.get('plugin_except_list', None)
|
||||
if plugin_except_list != None and (type(plugin_except_list) == type([]) and len(plugin_except_list)) > 0:
|
||||
new_plugins = []
|
||||
for _ in plugins:
|
||||
if _ not in plugin_except_list:
|
||||
new_plugins.append(_)
|
||||
else:
|
||||
cls.all_package_list[_]['loading'] = False
|
||||
cls.all_package_list[_]['status'] = 'include_except_list'
|
||||
plugins = new_plugins
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
return plugins
|
||||
|
||||
|
||||
|
||||
# menu, blueprint, plugin_info, plugin_load, plugin_unload
|
||||
@classmethod
|
||||
def plugin_init(cls):
|
||||
try:
|
||||
plugins = cls.get_plugin_name_list()
|
||||
plugins = sorted(plugins)
|
||||
|
||||
F.logger.debug(plugins)
|
||||
for plugin_name in plugins:
|
||||
F.logger.debug(f'[+] PLUGIN LOADING Start.. [{plugin_name}]')
|
||||
entity = cls.all_package_list[plugin_name]
|
||||
entity['version'] = '3'
|
||||
try:
|
||||
mod = __import__('%s' % (plugin_name), fromlist=[])
|
||||
mod_plugin_info = None
|
||||
try:
|
||||
mod_plugin_info = getattr(mod, 'plugin_info')
|
||||
entity['module'] = mod
|
||||
except Exception as exception:
|
||||
F.logger.info(f'[!] PLUGIN_INFO not exist : [{plugin_name}] - is FF')
|
||||
|
||||
if mod_plugin_info == None:
|
||||
try:
|
||||
mod = __import__(f'{plugin_name}.setup', fromlist=['setup'])
|
||||
entity['version'] = '4'
|
||||
except Exception as e:
|
||||
F.logger.error(f'Exception:{str(e)}')
|
||||
F.logger.error(traceback.format_exc())
|
||||
F.logger.warning(f'[!] NOT normal plugin : [{plugin_name}]')
|
||||
|
||||
try:
|
||||
if entity['version'] != '4':
|
||||
mod_blue_print = getattr(mod, 'blueprint')
|
||||
else:
|
||||
entity['setup_mod'] = mod
|
||||
entity['P'] = getattr(mod, 'P')
|
||||
mod_blue_print = getattr(entity['P'], 'blueprint')
|
||||
if mod_blue_print:
|
||||
F.app.register_blueprint(mod_blue_print)
|
||||
except Exception as exception:
|
||||
#logger.error('Exception:%s', exception)
|
||||
#logger.error(traceback.format_exc())
|
||||
F.logger.warning(f'[!] BLUEPRINT not exist : [{plugin_name}]')
|
||||
cls.plugin_list[plugin_name] = entity
|
||||
#system.LogicPlugin.current_loading_plugin_list[plugin_name]['status'] = 'success'
|
||||
#system.LogicPlugin.current_loading_plugin_list[plugin_name]['info'] = mod_plugin_info
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
F.logger.debug('no blueprint')
|
||||
cls.all_package_list[plugin_name]['loading'] = False
|
||||
cls.all_package_list[plugin_name]['status'] = 'import fail'
|
||||
cls.all_package_list[plugin_name]['log'] = traceback.format_exc()
|
||||
|
||||
|
||||
|
||||
if not F.config['run_celery']:
|
||||
try:
|
||||
with F.app.app_context():
|
||||
F.db.create_all()
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
F.logger.debug('db.create_all error')
|
||||
|
||||
if not F.config['run_flask']:
|
||||
return
|
||||
|
||||
for key, entity in cls.plugin_list.items():
|
||||
try:
|
||||
mod_plugin_load = None
|
||||
if entity['version'] == '3':
|
||||
mod_plugin_load = getattr(entity['module'], 'plugin_load')
|
||||
elif entity['version'] == '4':
|
||||
mod_plugin_load = getattr(entity['P'], 'plugin_load')
|
||||
if mod_plugin_load:
|
||||
def func(mod_plugin_load, key):
|
||||
try:
|
||||
F.logger.debug(f'[!] plugin_load threading start : [{key}]')
|
||||
#mod.plugin_load()
|
||||
mod_plugin_load()
|
||||
F.logger.debug(f'[!] plugin_load threading end : [{key}]')
|
||||
except Exception as exception:
|
||||
F.logger.error('### plugin_load exception : %s', key)
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
cls.all_package_list[key]['loading'] = False
|
||||
cls.all_package_list[key]['status'] = 'plugin_load error'
|
||||
cls.all_package_list[key]['log'] = traceback.format_exc()
|
||||
|
||||
if key in cls.plugin_menus:
|
||||
del cls.plugin_menus[key]
|
||||
F.logger.info(f"플러그인 로딩 실패로 메뉴 삭제1 : {key}")
|
||||
from framework.init_menu import MenuManager
|
||||
MenuManager.init_menu()
|
||||
F.logger.info(f"플러그인 로딩 실패로 메뉴 삭제2 : {key}")
|
||||
|
||||
|
||||
# mod는 위에서 로딩
|
||||
if key != 'mod':
|
||||
t = threading.Thread(target=func, args=(mod_plugin_load, key))
|
||||
t.setDaemon(True)
|
||||
t.start()
|
||||
#if key == 'mod':
|
||||
# t.join()
|
||||
except Exception as exception:
|
||||
F.logger.debug(f'[!] PLUGIN_LOAD function not exist : [{key}]')
|
||||
#logger.error('Exception:%s', exception)
|
||||
#logger.error(traceback.format_exc())
|
||||
#logger.debug('no init_scheduler')
|
||||
try:
|
||||
mod_menu = None
|
||||
if entity['version'] == '3':
|
||||
mod_menu = getattr(entity['module'], 'menu')
|
||||
elif entity['version'] == '4':
|
||||
mod_menu = getattr(entity['P'], 'menu')
|
||||
|
||||
if mod_menu and cls.all_package_list[key]['loading'] != False:
|
||||
cls.plugin_menus[key]= {'menu':mod_menu, 'match':False}
|
||||
if entity['version'] == '4':
|
||||
setting_menu = getattr(entity['P'], 'setting_menu')
|
||||
if setting_menu != None and cls.all_package_list[key]['loading'] != False:
|
||||
F.logger.info(f"메뉴 포함 : {key}")
|
||||
cls.setting_menus.append(setting_menu)
|
||||
|
||||
|
||||
except Exception as exception:
|
||||
F.logger.debug('no menu')
|
||||
F.logger.debug('### plugin_load threading all start.. : %s ', len(cls.plugin_list))
|
||||
# 모든 모듈을 로드한 이후에 app 등록, table 생성, start
|
||||
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def plugin_unload(cls):
|
||||
for key, entity in cls.plugin_list.items():
|
||||
try:
|
||||
if entity['version'] == '3':
|
||||
mod_plugin_unload = getattr(entity['module'], 'plugin_unload')
|
||||
elif entity['version'] == '4':
|
||||
mod_plugin_unload = getattr(entity['P'], 'plugin_unload')
|
||||
|
||||
#if plugin_name == 'rss':
|
||||
# continue
|
||||
#mod_plugin_unload = getattr(mod, 'plugin_unload')
|
||||
if mod_plugin_unload:
|
||||
mod_plugin_unload()
|
||||
#mod.plugin_unload()
|
||||
except Exception as e:
|
||||
F.logger.error('module:%s', key)
|
||||
F.logger.error(f'Exception:{str(e)}')
|
||||
F.logger.error(traceback.format_exc())
|
||||
try:
|
||||
from system.setup import P
|
||||
P.plugin_unload()
|
||||
except Exception as e:
|
||||
F.logger.error(f'Exception:{str(e)}')
|
||||
F.logger.error(traceback.format_exc())
|
||||
|
||||
@classmethod
|
||||
def plugin_install(cls, plugin_git, zip_url=None, zip_filename=None):
|
||||
is_git = True if plugin_git != None and plugin_git != '' else False
|
||||
ret = {}
|
||||
try:
|
||||
if is_git:
|
||||
name = plugin_git.split('/')[-1]
|
||||
else:
|
||||
name = zip_filename.split('.')[0]
|
||||
|
||||
plugin_all_path = os.path.join(F.config['path_data'], 'plugins')
|
||||
os.makedirs(plugin_all_path, exist_ok=True)
|
||||
plugin_path = os.path.join(plugin_all_path, name)
|
||||
plugin_info = None
|
||||
if os.path.exists(plugin_path):
|
||||
ret['ret'] = 'danger'
|
||||
ret['msg'] = '이미 설치되어 있습니다.'
|
||||
ret['status'] = 'already_exist'
|
||||
return ret
|
||||
|
||||
if plugin_git and plugin_git.startswith('http'):
|
||||
for tag in ['main', 'master']:
|
||||
try:
|
||||
info_url = plugin_git.replace('github.com', 'raw.githubusercontent.com') + f'/{tag}/info.yaml'
|
||||
plugin_info = requests.get(info_url).json()
|
||||
if plugin_info is not None:
|
||||
break
|
||||
except:
|
||||
pass
|
||||
|
||||
if zip_filename and zip_filename != '':
|
||||
zip_filepath = os.path.join(F.config['path_data'], 'tmp', zip_filename)
|
||||
extract_filepath = os.path.join(F.config['path_data'], 'tmp', name)
|
||||
if SupportFile.download(zip_url, zip_filepath):
|
||||
with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
|
||||
zip_ref.extractall(extract_filepath)
|
||||
plugin_info_filepath = os.path.join(extract_filepath, 'info.yaml')
|
||||
if os.path.exists(plugin_info_filepath):
|
||||
plugin_info = SupportYaml.read_yaml(plugin_info_filepath)
|
||||
|
||||
if plugin_info == None:
|
||||
plugin_info = {}
|
||||
|
||||
flag = True
|
||||
tmp = plugin_info.get('require_os', '')
|
||||
if tmp != '' and type(tmp) == type([]) and platform.system() not in tmp:
|
||||
ret['ret'] = 'danger'
|
||||
ret['msg'] = '설치 가능한 OS가 아닙니다.'
|
||||
ret['status'] = 'not_support_os'
|
||||
flag = False
|
||||
|
||||
tmp = plugin_info.get('require_running_type', '')
|
||||
if tmp != '' and type(tmp) == type([]) and F.config['running_type'] not in tmp:
|
||||
ret['ret'] = 'danger'
|
||||
ret['msg'] = '설치 가능한 실행타입이 아닙니다.'
|
||||
ret['status'] = 'not_support_running_type'
|
||||
flag = False
|
||||
|
||||
|
||||
if flag:
|
||||
if plugin_git and plugin_git.startswith('http'):
|
||||
command = ['git', '-C', plugin_all_path, 'clone', plugin_git + '.git', '--depth', '1']
|
||||
log = SupportSubprocess.execute_command_return(command, log=True)
|
||||
F.logger.debug(log)
|
||||
if os.path.exists(plugin_path):
|
||||
ret['ret'] = 'success'
|
||||
ret['msg'] = '정상적으로 설치하였습니다. 재시작시 적용됩니다.<br>' + '<br>'.join(log['log'].split('\n'))
|
||||
else:
|
||||
ret['ret'] = 'danger'
|
||||
ret['msg'] = '설치 실패.<br>' + '<br>'.join(log['log'].split('\n'))
|
||||
if zip_filename and zip_filename != '':
|
||||
|
||||
if os.path.exists(plugin_path) == False:
|
||||
shutil.move(extract_filepath, plugin_path)
|
||||
else:
|
||||
for tmp in os.listdir(extract_filepath):
|
||||
shutil.move(os.path.join(extract_filepath, tmp), plugin_path)
|
||||
log = ''
|
||||
|
||||
# 2021-12-31
|
||||
tmp = plugin_info.get('require_plugin', '')
|
||||
if tmp != '' and type(tmp) == type([]) and len(tmp) > 0:
|
||||
for need_plugin in plugin_info['require_plugin']:
|
||||
if need_plugin['package_name'] in cls.plugin_init:
|
||||
F.logger.debug(f"Dependency 설치 - 이미 설치됨 : {need_plugin['package_name']}")
|
||||
continue
|
||||
else:
|
||||
F.logger.debug(f"Dependency 설치 : {need_plugin['package_name']}")
|
||||
cls.plugin_install(need_plugin['home'], None, None)
|
||||
|
||||
|
||||
#ret['msg'] = '<br>'.join(log)
|
||||
|
||||
except Exception as e:
|
||||
F.logger.error(f'Exception:{str(e)}')
|
||||
F.logger.error(traceback.format_exc())
|
||||
ret['ret'] = 'danger'
|
||||
ret['msg'] = str(e)
|
||||
return ret
|
||||
|
||||
|
||||
@classmethod
|
||||
def plugin_update(cls):
|
||||
try:
|
||||
if os.environ.get('UPDATE_STOP') == 'true':
|
||||
return
|
||||
if os.environ.get('PLUGIN_UPDATE_FROM_PYTHON') == 'false':
|
||||
return
|
||||
if F.config['plugin_update'] != True:
|
||||
return
|
||||
plugins_path = os.path.join(F.config['path_data'], 'plugins')
|
||||
if os.path.exists(plugins_path) == False:
|
||||
return
|
||||
tmps = os.listdir(plugins_path)
|
||||
for t in tmps:
|
||||
plugin_path = os.path.join(plugins_path, t)
|
||||
if t.startswith('_'):
|
||||
continue
|
||||
if os.path.exists(os.path.join(plugin_path, '.git')):
|
||||
command = ['git', '-C', plugin_path, 'reset', '--hard', 'HEAD']
|
||||
ret = SupportSubprocess.execute_command_return(command)
|
||||
F.logger.debug(ret)
|
||||
command = ['git', '-C', plugin_path, 'pull']
|
||||
ret = SupportSubprocess.execute_command_return(command)
|
||||
F.logger.debug(ret)
|
||||
else:
|
||||
F.logger.debug(f"{plugin_path} not git repo")
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
@classmethod
|
||||
def get_plugin_instance(cls, package_name):
|
||||
try:
|
||||
return cls.all_package_list[package_name]['P']
|
||||
except:
|
||||
pass
|
||||
@@ -0,0 +1,132 @@
|
||||
import os
|
||||
import traceback
|
||||
|
||||
from flask import (jsonify, redirect, render_template, request,
|
||||
send_from_directory)
|
||||
from flask_login import login_required
|
||||
|
||||
from framework import F
|
||||
|
||||
|
||||
@F.app.route('/global/ajax/<sub>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def global_ajax(sub):
|
||||
#logger.debug('/global/ajax/%s', sub)
|
||||
if sub == 'listdir':
|
||||
if 'path' in request.form:
|
||||
#if os.path.isfile(request.form['path']):
|
||||
# return jsonify('')
|
||||
path = request.form['path']
|
||||
if os.path.isfile(path):
|
||||
path = os.path.dirname(path)
|
||||
result_list = os.listdir(path)
|
||||
|
||||
if 'only_dir' in request.form and request.form['only_dir'].lower() == 'true':
|
||||
result_list = [name for name in result_list if os.path.isdir(os.path.join(path, name))]
|
||||
|
||||
result_list.sort()
|
||||
result_list = [f"{x}|{os.path.join(path,x)}" for x in result_list]
|
||||
tmp = os.path.dirname(path)
|
||||
if path != tmp:
|
||||
result_list = [f'..|{tmp}'] + result_list
|
||||
return jsonify(result_list)
|
||||
else:
|
||||
return jsonify(None)
|
||||
elif sub == 'is_available_edit':
|
||||
# globalEditBtn
|
||||
try:
|
||||
if F.PluginManager.all_package_list['flaskcode']['loading']:
|
||||
PP = F.PluginManager.all_package_list['flaskcode']['P']
|
||||
#import flaskcode
|
||||
#from flaskcode.setup import P as PP
|
||||
ret = {'ret':True, 'target':PP.ModelSetting.get('setting_open_target')}
|
||||
return jsonify(ret)
|
||||
else:
|
||||
return jsonify({'ret':False})
|
||||
|
||||
except:
|
||||
return jsonify({'ret':False})
|
||||
elif sub == 'command_modal_hide':
|
||||
from tool import ToolModalCommand
|
||||
ToolModalCommand.modal_close()
|
||||
return jsonify('')
|
||||
elif sub == 'command_modal_input':
|
||||
from tool import ToolModalCommand
|
||||
cmd = request.form['cmd']
|
||||
ToolModalCommand.input_command(cmd)
|
||||
return jsonify('')
|
||||
|
||||
|
||||
|
||||
@F.app.route('/robots.txt')
|
||||
def robot_to_root():
|
||||
return send_from_directory('', 'static/file/robots.txt')
|
||||
|
||||
|
||||
|
||||
|
||||
@F.app.route("/")
|
||||
@F.app.route("/None")
|
||||
@F.app.route("/home")
|
||||
def home():
|
||||
return redirect('/system/home')
|
||||
|
||||
|
||||
@F.app.route("/version")
|
||||
def get_version():
|
||||
from .version import VERSION
|
||||
return VERSION
|
||||
|
||||
@F.app.route("/open/<path:path>")
|
||||
@login_required
|
||||
def open_file(path):
|
||||
return send_from_directory('/', path)
|
||||
|
||||
|
||||
@F.app.route("/file/<path:path>")
|
||||
@F.check_api
|
||||
def file2(path):
|
||||
# 윈도우 drive 필요 없음
|
||||
return send_from_directory('/', path, as_attachment=True)
|
||||
|
||||
|
||||
@F.app.route("/upload", methods=['GET', 'POST'])
|
||||
def upload():
|
||||
try:
|
||||
if request.method == 'POST':
|
||||
f = request.files['file']
|
||||
from werkzeug import secure_filename
|
||||
upload_path = F.SystemModelSetting.get('path_upload')
|
||||
os.makedirs(upload_path, exist_ok=True)
|
||||
f.save(os.path.join(upload_path, secure_filename(f.filename)))
|
||||
return jsonify('success')
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
return jsonify('fail')
|
||||
|
||||
|
||||
@F.app.route("/videojs", methods=['GET', 'POST'])
|
||||
def videojs():
|
||||
data = {}
|
||||
data['play_title'] = request.form['play_title']
|
||||
data['play_source_src'] = request.form['play_source_src']
|
||||
data['play_source_type'] = request.form['play_source_type']
|
||||
if 'play_subtitle_src' in request.form:
|
||||
data['play_subtitle_src'] = request.form['play_subtitle_src']
|
||||
return render_template('videojs.html', data=data)
|
||||
|
||||
|
||||
|
||||
@F.app.route("/headers", methods=['GET', 'POST'])
|
||||
def headers():
|
||||
from support import d
|
||||
F.logger.info(d(request.headers))
|
||||
return jsonify(d(request.headers))
|
||||
|
||||
|
||||
# 3.10에서 이거 필수
|
||||
@F.socketio.on('connect', namespace=f'/framework')
|
||||
def connect():
|
||||
pass
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import re
|
||||
|
||||
from framework import F
|
||||
|
||||
|
||||
def get_menu(full_query):
|
||||
match = re.compile(r'\/(?P<menu>.*?)\/manual\/(?P<sub2>.*?)($|\?)').match(full_query)
|
||||
if match:
|
||||
return match.group('menu'), 'manual', match.group('sub2')
|
||||
|
||||
match = re.compile(r'\/(?P<menu>.*?)\/(?P<sub>.*?)\/(?P<sub2>.*?)($|\/|\?)').match(full_query)
|
||||
if match:
|
||||
return match.group('menu'), match.group('sub'), match.group('sub2')
|
||||
|
||||
match = re.compile(r'\/(?P<menu>.*?)\/(?P<sub>.*?)($|\/|\?)').match(full_query)
|
||||
if match:
|
||||
return match.group('menu'), match.group('sub'), None
|
||||
|
||||
match = re.compile(r'\/(?P<menu>.*?)($|\/|\?)').match(full_query)
|
||||
if match:
|
||||
return match.group('menu'), None , None
|
||||
return 'home', None, None
|
||||
|
||||
|
||||
|
||||
def get_theme():
|
||||
return F.SystemModelSetting.get('theme')
|
||||
|
||||
#def get_login_status():
|
||||
# if current_user is None:
|
||||
# return False
|
||||
# return current_user.is_authenticated
|
||||
|
||||
def get_web_title():
|
||||
try:
|
||||
return F.SystemModelSetting.get('web_title')
|
||||
except:
|
||||
return 'Home'
|
||||
|
||||
|
||||
def is_https():
|
||||
return (F.SystemModelSetting.get('ddns').find('https://') != -1)
|
||||
|
||||
|
||||
def jinja_initialize(app):
|
||||
#from .init_menu import get_menu_map, get_plugin_menu
|
||||
from .init_menu import MenuManager
|
||||
app.jinja_env.globals.update(get_menu=get_menu)
|
||||
app.jinja_env.globals.update(get_theme=get_theme)
|
||||
app.jinja_env.globals.update(get_menu_map=MenuManager.get_menu_map)
|
||||
app.jinja_env.globals.update(get_web_title=get_web_title)
|
||||
app.jinja_env.globals.update(dropzone=F.dropzone)
|
||||
|
||||
app.jinja_env.filters['get_menu'] = get_menu
|
||||
app.jinja_env.filters['get_theme'] = get_theme
|
||||
app.jinja_env.filters['get_menu_map'] = MenuManager.get_menu_map
|
||||
app.jinja_env.filters['get_web_title'] = get_web_title
|
||||
|
||||
app.jinja_env.auto_reload = True
|
||||
app.jinja_env.add_extension('jinja2.ext.loopcontrols')
|
||||
@@ -0,0 +1,137 @@
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from flask import request
|
||||
from support import SingletonClass
|
||||
|
||||
from framework import F
|
||||
|
||||
namespace = 'log'
|
||||
|
||||
@F.socketio.on('connect', namespace='/%s' % namespace)
|
||||
def socket_connect():
|
||||
F.logger.debug('log connect')
|
||||
|
||||
@F.socketio.on('start', namespace='/%s' % namespace)
|
||||
def socket_file(data):
|
||||
try:
|
||||
package = filename = None
|
||||
if 'package' in data:
|
||||
package = data['package']
|
||||
else:
|
||||
filename = data['filename']
|
||||
LogViewer.instance().start(package, filename, request.sid)
|
||||
F.logger.debug('start package:%s filename:%s sid:%s', package, filename, request.sid)
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
|
||||
@F.socketio.on('disconnect', namespace='/%s' % namespace)
|
||||
def disconnect():
|
||||
try:
|
||||
LogViewer.instance().disconnect(request.sid)
|
||||
F.logger.debug('disconnect sid:%s', request.sid)
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
class WatchThread(threading.Thread):
|
||||
|
||||
def __init__(self, package, filename):
|
||||
super(WatchThread, self).__init__()
|
||||
self.stop_flag = False
|
||||
self.package = package
|
||||
self.filename = filename
|
||||
self.daemon = True
|
||||
|
||||
def stop(self):
|
||||
self.stop_flag = True
|
||||
|
||||
def run(self):
|
||||
F.logger.debug('WatchThread.. Start %s', self.package)
|
||||
if self.package is not None:
|
||||
logfile = os.path.join(F.config['path_data'], 'log', f'{self.package}.log')
|
||||
key = 'package'
|
||||
value = self.package
|
||||
else:
|
||||
logfile = os.path.join(F.config['path_data'], 'log', self.filename)
|
||||
key = 'filename'
|
||||
value = self.filename
|
||||
if os.path.exists(logfile):
|
||||
with open(logfile, 'r') as f:
|
||||
f.seek(0, os.SEEK_END)
|
||||
while not self.stop_flag:
|
||||
line = f.readline()
|
||||
if not line:
|
||||
time.sleep(0.1) # Sleep briefly
|
||||
continue
|
||||
F.socketio.emit("add", {key : value, 'data': line}, namespace='/log', broadcast=True)
|
||||
F.logger.debug('WatchThread.. End %s', value)
|
||||
else:
|
||||
F.socketio.emit("add", {key : value, 'data': 'not exist logfile'}, namespace='/log', broadcast=True)
|
||||
|
||||
|
||||
|
||||
class LogViewer(SingletonClass):
|
||||
|
||||
watch_list = {}
|
||||
|
||||
@classmethod
|
||||
def start(cls, package, filename, sid):
|
||||
# 2019-04-02 간만에 봤더니 헷깔려서 적는다
|
||||
# 이 쓰레드는 오픈시 이전 데이타만을 보내는 쓰레드다. 실시간보는거 아님.
|
||||
|
||||
def thread_function():
|
||||
if package is not None:
|
||||
logfile = os.path.join(F.config['path_data'], 'log', f'{package}.log')
|
||||
else:
|
||||
logfile = os.path.join(F.config['path_data'], 'log', filename)
|
||||
if os.path.exists(logfile):
|
||||
ins_file = open(logfile, 'r', encoding='utf8') ## 3)
|
||||
line = ins_file.read()
|
||||
F.socketio.emit("on_start", {'data': line}, namespace='/log')
|
||||
F.logger.debug('on_start end')
|
||||
else:
|
||||
F.socketio.emit("on_start", {'data': 'not exist logfile'}, namespace='/log')
|
||||
|
||||
if package is not None:
|
||||
key = package
|
||||
else:
|
||||
key = filename
|
||||
thread = threading.Thread(target=thread_function, args=())
|
||||
thread.daemon = True
|
||||
thread.start()
|
||||
|
||||
|
||||
if key not in cls.watch_list:
|
||||
cls.watch_list[key] = {}
|
||||
cls.watch_list[key]['sid'] = []
|
||||
cls.watch_list[key]['thread'] = WatchThread(package, filename)
|
||||
cls.watch_list[key]['thread'].start()
|
||||
cls.watch_list[key]['sid'].append(sid)
|
||||
|
||||
@classmethod
|
||||
def disconnect(cls, sid):
|
||||
find = False
|
||||
find_key = None
|
||||
for key, value in cls.watch_list.items():
|
||||
F.logger.debug('key:%s value:%s', key, value)
|
||||
for s in value['sid']:
|
||||
if sid == s:
|
||||
find = True
|
||||
find_key = key
|
||||
value['sid'].remove(s)
|
||||
break
|
||||
if find:
|
||||
break
|
||||
if not find:
|
||||
return
|
||||
if not cls.watch_list[find_key]['sid']:
|
||||
F.logger.debug('thread kill')
|
||||
cls.watch_list[find_key]['thread'].stop()
|
||||
del cls.watch_list[find_key]
|
||||
|
||||
@@ -0,0 +1,257 @@
|
||||
import threading
|
||||
import traceback
|
||||
from datetime import datetime, timedelta
|
||||
from random import randint
|
||||
|
||||
from apscheduler.jobstores.base import JobLookupError
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
from pytz import timezone
|
||||
|
||||
|
||||
class Scheduler(object):
|
||||
job_list = []
|
||||
first_run_check_thread = None
|
||||
def __init__(self, frame):
|
||||
self.frame = frame
|
||||
self.logger = frame.logger
|
||||
try:
|
||||
if frame.config['use_gevent']:
|
||||
from apscheduler.schedulers.gevent import GeventScheduler
|
||||
self.sched = GeventScheduler(timezone='Asia/Seoul')
|
||||
else:
|
||||
raise Exception('')
|
||||
except:
|
||||
from apscheduler.schedulers.background import BackgroundScheduler
|
||||
self.sched = BackgroundScheduler(timezone='Asia/Seoul')
|
||||
self.sched.start()
|
||||
self.logger.info('SCHEDULER start..')
|
||||
|
||||
def first_run_check_thread_function(self):
|
||||
try:
|
||||
#time.sleep(60)
|
||||
#for i in range(5):
|
||||
flag_exit = True
|
||||
for job_instance in self.job_list:
|
||||
if not job_instance.run:
|
||||
continue
|
||||
if job_instance.count == 0 and not job_instance.is_running and job_instance.is_interval:
|
||||
#if job_instance.count == 0 and not job_instance.is_running:
|
||||
job = self.sched.get_job(job_instance.job_id)
|
||||
if job is not None:
|
||||
self.logger.warning('job_instance : %s', job_instance.plugin)
|
||||
self.logger.warning('XX job re-sched:%s', job)
|
||||
flag_exit = False
|
||||
tmp = randint(1, 20)
|
||||
job.modify(next_run_time=datetime.now(timezone('Asia/Seoul')) + timedelta(seconds=tmp))
|
||||
#break
|
||||
else:
|
||||
pass
|
||||
if flag_exit:
|
||||
self.remove_job("scheduler_check")
|
||||
#time.sleep(30)
|
||||
except Exception as exception:
|
||||
self.logger.error('Exception:%s', exception)
|
||||
self.logger.error(traceback.format_exc())
|
||||
|
||||
def shutdown(self):
|
||||
self.sched.shutdown()
|
||||
|
||||
def kill_scheduler(self, job_id):
|
||||
try:
|
||||
self.sched.remove_job(job_id)
|
||||
except JobLookupError as err:
|
||||
self.logger.debug("fail to stop Scheduler: {err}".format(err=err))
|
||||
self.logger.debug(traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
def add_job_instance(self, job_instance, run=True):
|
||||
if self.frame.config['run_flask']:
|
||||
if not self.is_include(job_instance.job_id):
|
||||
job_instance.run = run
|
||||
Scheduler.job_list.append(job_instance)
|
||||
if job_instance.is_interval:
|
||||
self.sched.add_job(job_instance.job_function, 'interval', minutes=job_instance.interval, seconds=job_instance.interval_seconds, id=job_instance.job_id, args=(None))
|
||||
elif job_instance.is_cron:
|
||||
self.sched.add_job(job_instance.job_function, CronTrigger.from_crontab(job_instance.interval), id=job_instance.job_id, args=(None))
|
||||
job = self.sched.get_job(job_instance.job_id)
|
||||
if run and job_instance.is_interval:
|
||||
tmp = randint(5, 20)
|
||||
job.modify(next_run_time=datetime.now(timezone('Asia/Seoul')) + timedelta(seconds=tmp))
|
||||
|
||||
def execute_job(self, job_id):
|
||||
self.logger.debug('execute_job:%s', job_id)
|
||||
job = self.sched.get_job(job_id)
|
||||
tmp = randint(5, 20)
|
||||
job.modify(next_run_time=datetime.now(timezone('Asia/Seoul')) + timedelta(seconds=tmp))
|
||||
|
||||
|
||||
def is_include(self, job_id):
|
||||
job = self.sched.get_job(job_id)
|
||||
return (job is not None)
|
||||
|
||||
def remove_job(self, job_id):
|
||||
try:
|
||||
if self.is_include(job_id):
|
||||
self.sched.remove_job(job_id)
|
||||
job = self.get_job_instance(job_id)
|
||||
if not job.is_running:
|
||||
self.remove_job_instance(job_id)
|
||||
self.logger.debug('remove job_id:%s', job_id)
|
||||
return True
|
||||
except JobLookupError as err:
|
||||
self.logger.debug("fail to remove Scheduler: {err}".format(err=err))
|
||||
self.logger.debug(traceback.format_exc())
|
||||
return False
|
||||
|
||||
|
||||
def get_job_instance(self, job_id):
|
||||
for job in Scheduler.job_list:
|
||||
if job.job_id == job_id:
|
||||
return job
|
||||
|
||||
def is_running(self, job_id):
|
||||
job = self.get_job_instance(job_id)
|
||||
if job is None:
|
||||
return False
|
||||
else:
|
||||
return job.is_running
|
||||
|
||||
# job에서만 호출한다..
|
||||
def remove_job_instance(self, job_id):
|
||||
# function이 실행중일때 제거하면..
|
||||
# 실행중이나 목록에서 빠져버린다..
|
||||
for job in Scheduler.job_list:
|
||||
if job.job_id == job_id:
|
||||
Scheduler.job_list.remove(job)
|
||||
self.logger.debug('remove_job_instance : %s', job_id)
|
||||
break
|
||||
|
||||
|
||||
def get_job_list_info(self):
|
||||
|
||||
ret = []
|
||||
idx = 0
|
||||
job_list = self.sched.get_jobs()
|
||||
#logger.debug('len jobs %s %s', len(jobs), len(Scheduler.job_list))
|
||||
for j in job_list:
|
||||
idx += 1
|
||||
entity = {}
|
||||
entity['no'] = idx
|
||||
entity['id'] = j.id
|
||||
entity['next_run_time'] = j.next_run_time.strftime('%m-%d %H:%M:%S')
|
||||
remain = (j.next_run_time - datetime.now(timezone('Asia/Seoul')))
|
||||
tmp = ''
|
||||
if remain.days > 0:
|
||||
tmp += '%s일 ' % (remain.days)
|
||||
remain = remain.seconds
|
||||
if remain//3600 > 0:
|
||||
tmp += '%s시간 ' % (remain//3600)
|
||||
remain = remain % 3600
|
||||
if remain // 60 > 0:
|
||||
tmp += '%s분 ' % (remain//60)
|
||||
tmp += '%s초' % (remain%60)
|
||||
#entity['remain_time'] = (j.next_run_time - datetime.now(timezone('Asia/Seoul'))).seconds
|
||||
entity['remain_time'] = tmp
|
||||
job = self.get_job_instance(j.id)
|
||||
if job is not None:
|
||||
entity['count'] = job.count
|
||||
entity['plugin'] = job.plugin
|
||||
if job.is_cron:
|
||||
entity['interval'] = job.interval
|
||||
elif job.interval == 9999:
|
||||
entity['interval'] = '항상 실행'
|
||||
entity['remain_time'] = ''
|
||||
else:
|
||||
entity['interval'] = '%s분 %s초' % (job.interval, job.interval_seconds)
|
||||
entity['is_running'] = job.is_running
|
||||
entity['description'] = job.description
|
||||
entity['running_timedelta'] = job.running_timedelta.seconds if job.running_timedelta is not None else '-'
|
||||
if entity['running_timedelta'] != '-':
|
||||
tmp = entity['running_timedelta']
|
||||
_min = entity['running_timedelta'] / 60
|
||||
_sec = entity['running_timedelta'] % 60
|
||||
entity['running_timedelta'] = "%2d분 %2d초" % (_min, _sec)
|
||||
entity['make_time'] = job.make_time.strftime('%m-%d %H:%M:%S')
|
||||
entity['run'] = job.run
|
||||
else:
|
||||
entity['count'] = ''
|
||||
entity['plugin'] = ''
|
||||
entity['interval'] = ''
|
||||
entity['is_running'] = ''
|
||||
entity['description'] = ''
|
||||
entity['running_timedelta'] = ''
|
||||
entity['make_time'] = ''
|
||||
entity['run'] = True
|
||||
|
||||
ret.append(entity)
|
||||
return ret
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class Job(object):
|
||||
def __init__(self, plugin, job_id, interval, target_function, description, args=None):
|
||||
self.plugin = plugin
|
||||
self.job_id = job_id
|
||||
self.interval = '%s' % interval
|
||||
self.interval_seconds = randint(1, 59)
|
||||
self.target_function = target_function
|
||||
self.description = description
|
||||
self.is_running = False
|
||||
self.thread = None
|
||||
self.start_time = None
|
||||
self.end_time = None
|
||||
self.running_timedelta = None
|
||||
self.status = None
|
||||
self.count = 0
|
||||
self.make_time = datetime.now(timezone('Asia/Seoul'))
|
||||
if len(self.interval.strip().split(' ')) == 5:
|
||||
self.is_cron = True
|
||||
self.is_interval = False
|
||||
else:
|
||||
self.is_cron = False
|
||||
self.is_interval = True
|
||||
if self.is_interval:
|
||||
if isinstance(self.interval, str):
|
||||
self.interval = int(self.interval)
|
||||
self.args = args
|
||||
# true이고 interval이면 바로 실행
|
||||
# false이면 스케쥴링시간이 되면 실행
|
||||
# add_job_instance에서 true이면 20초 이내에 실행하려고 함.
|
||||
# false이면 넣을 때는 실행하지 않고 다음 주기때 실행
|
||||
self.run = True
|
||||
|
||||
def job_function(self):
|
||||
try:
|
||||
from framework import F
|
||||
self.is_running = True
|
||||
self.start_time = datetime.now(timezone('Asia/Seoul'))
|
||||
if self.args is None:
|
||||
self.thread = threading.Thread(target=self.target_function, args=())
|
||||
else:
|
||||
self.thread = threading.Thread(target=self.target_function, args=(self.args,))
|
||||
self.thread.daemon = True
|
||||
self.thread.start()
|
||||
F.socketio.emit('notify', {'type':'success', 'msg':f"{self.description}<br>작업을 시작합니다." }, namespace='/framework', broadcast=True)
|
||||
self.thread.join()
|
||||
F.socketio.emit('notify', {'type':'success', 'msg':f"{self.description}<br>작업이 종료되었습니다." }, namespace='/framework', broadcast=True)
|
||||
self.end_time = datetime.now(timezone('Asia/Seoul'))
|
||||
self.running_timedelta = self.end_time - self.start_time
|
||||
self.status = 'success'
|
||||
if not F.scheduler.is_include(self.job_id):
|
||||
F.scheduler.remove_job_instance(self.job_id)
|
||||
self.count += 1
|
||||
except Exception as exception:
|
||||
self.status = 'exception'
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
finally:
|
||||
self.is_running = False
|
||||
|
||||
|
||||
|
||||
|
||||
+11
File diff suppressed because one or more lines are too long
+6
File diff suppressed because one or more lines are too long
@@ -0,0 +1,108 @@
|
||||
body {
|
||||
font-size: .850rem;
|
||||
}
|
||||
|
||||
/* Rounded sliders */
|
||||
.slider.round {
|
||||
border-radius: 34px;
|
||||
}
|
||||
.slider.round:before {
|
||||
border-radius: 50%;
|
||||
}
|
||||
.alert-minimalist {
|
||||
background-color: rgb(241, 242, 240);
|
||||
border-color: rgba(149, 149, 149, 0.3);
|
||||
border-radius: 3px;
|
||||
color: rgb(149, 149, 149);
|
||||
padding: 10px;
|
||||
}
|
||||
.alert-minimalist > [data-notify="icon"] {
|
||||
height: 50px;
|
||||
margin-right: 12px;
|
||||
}
|
||||
.alert-minimalist > [data-notify="title"] {
|
||||
color: rgb(51, 51, 51);
|
||||
display: block;
|
||||
font-weight: bold;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
.alert-minimalist > [data-notify="message"] {
|
||||
font-size: 80%;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
textarea {
|
||||
font-family: Courier
|
||||
}
|
||||
|
||||
|
||||
.loading { position: fixed; left: 45%; top: 50%; background: #00000000; }
|
||||
|
||||
.table > tbody > tr.collapse > td {
|
||||
background-color: #009fff0d !important;
|
||||
}
|
||||
.tableRowHover tbody tr:not(.tableRowHoverOff):hover td {
|
||||
background-color: #ffff0080 !important;
|
||||
}
|
||||
|
||||
.table > tbody > tr > td { vertical-align: middle; }
|
||||
|
||||
.tab-pane {
|
||||
border-left: 1px solid #ddd;
|
||||
border-right: 1px solid #ddd;
|
||||
border-bottom: 1px solid #ddd;
|
||||
border-radius: 0px 0px 5px 5px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.btn-toolbar { text-align: center; }
|
||||
.nav-tabs { margin-bottom: 0; }
|
||||
.navbar-nav li:hover>.dropdown-menu { display: block; }
|
||||
.dropdown-toggle::after { display:none; }
|
||||
.set-left { text-align: left; }
|
||||
|
||||
@media (min-width: 768px) {
|
||||
.set-left { text-align: right; }
|
||||
}
|
||||
|
||||
.badge-sm {
|
||||
min-width: 1.8em;
|
||||
padding: .25em !important;
|
||||
margin-left: .1em;
|
||||
margin-right: .1em;
|
||||
color: white !important;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
|
||||
@media all and (min-width: 992px) {
|
||||
.dropdown-menu li{
|
||||
position: relative;
|
||||
}
|
||||
.dropdown-menu .submenu{
|
||||
display: none;
|
||||
position: absolute;
|
||||
left:100%; top:-7px;
|
||||
}
|
||||
.dropdown-menu .submenu-left{
|
||||
right:100%; left:auto;
|
||||
}
|
||||
.dropdown-menu > li:hover{ background-color: #f1f1f1 }
|
||||
.dropdown-menu > li:hover > .submenu{
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
/* ============ desktop view .end// ============ */
|
||||
|
||||
/* ============ small devices ============ */
|
||||
@media (max-width: 991px) {
|
||||
.dropdown-menu .dropdown-menu{
|
||||
margin-left:0.7rem; margin-right:0.7rem; margin-bottom: .5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.dropdown-menu {
|
||||
margin:-2px;
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,2 @@
|
||||
User-agent: *
|
||||
Disallow: /
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 318 B |
Binary file not shown.
|
After Width: | Height: | Size: 20 KiB |
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
+6
File diff suppressed because one or more lines are too long
@@ -0,0 +1,301 @@
|
||||
var tmp = window.location.pathname.split('/');
|
||||
if (tmp.length == 2) {
|
||||
var PACKAGE_NAME = tmp[1];
|
||||
var MODULE_NAME = "";
|
||||
var PAGE_NAME = "";
|
||||
} else if (tmp.length == 3) {
|
||||
var PACKAGE_NAME = tmp[1];
|
||||
var MODULE_NAME = tmp[2];
|
||||
var PAGE_NAME = "";
|
||||
} else if (tmp.length == 4){
|
||||
var PACKAGE_NAME = tmp[1];
|
||||
var MODULE_NAME = tmp[2];
|
||||
var PAGE_NAME = tmp[3];
|
||||
}
|
||||
var current_data = null;
|
||||
var current_page = null;
|
||||
console.log("NAME: [" + PACKAGE_NAME + '] [' + MODULE_NAME + '] [' + PAGE_NAME + ']');
|
||||
|
||||
$(window).on("load resize", function (event) {
|
||||
var $navbar = $(".navbar");
|
||||
var $body = $("body");
|
||||
$body.css("padding-top", $navbar.outerHeight());
|
||||
});
|
||||
|
||||
$('#command_modal').on('show.bs.modal', function (event) {
|
||||
console.log('111111111')
|
||||
console.log(event);
|
||||
})
|
||||
|
||||
///////////////////////////////////////
|
||||
// 사용 미확인
|
||||
///////////////////////////////////////
|
||||
|
||||
|
||||
// 알림
|
||||
$.notify({
|
||||
// options
|
||||
icon: 'glyphicon glyphicon-ok',
|
||||
title: 'APP',
|
||||
message: '',
|
||||
url: '',
|
||||
target: '_blank'
|
||||
},{
|
||||
// settings
|
||||
element: 'body',
|
||||
position: null,
|
||||
type: "info",
|
||||
allow_dismiss: true,
|
||||
newest_on_top: false,
|
||||
showProgressbar: false,
|
||||
placement: {
|
||||
from: "top",
|
||||
align: "right"
|
||||
},
|
||||
offset: 20,
|
||||
spacing: 10,
|
||||
z_index: 3000,
|
||||
delay: 10000,
|
||||
timer: 1000,
|
||||
url_target: '_blank',
|
||||
mouse_over: null,
|
||||
animate: {
|
||||
enter: 'animated fadeInDown',
|
||||
exit: 'animated fadeOutUp'
|
||||
},
|
||||
onShow: null,
|
||||
onShown: null,
|
||||
onClose: null,
|
||||
onClosed: null,
|
||||
icon_type: 'class',
|
||||
template: '<div data-notify="container" class="col-xs-11 col-sm-3 alert alert-{0}" role="alert">' +
|
||||
'<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
|
||||
'<span data-notify="icon"></span> ' +
|
||||
'<span data-notify="title" style="word-break:break-all;">{1}</span> ' +
|
||||
'<span data-notify="message" style="word-break:break-all;">{2}</span>' +
|
||||
'<div class="progress" data-notify="progressbar">' +
|
||||
'<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
|
||||
'</div>' +
|
||||
'<a href="{3}" target="{4}" data-notify="url"></a>' +
|
||||
'</div>'
|
||||
});
|
||||
|
||||
|
||||
function notify(msg, type) {
|
||||
$.notify('<strong>' + msg + '</strong>', {type: type, z_index: 3000});
|
||||
}
|
||||
|
||||
// 메뉴 제거
|
||||
function hideMenu() {
|
||||
$("#menu_div").html('');
|
||||
hideMenuModule();
|
||||
hideMenuPage();
|
||||
}
|
||||
|
||||
function hideMenuModule() {
|
||||
$("#menu_module_div").html('');
|
||||
}
|
||||
|
||||
function hideMenuPage() {
|
||||
$("#menu_page_div").html('');
|
||||
}
|
||||
|
||||
|
||||
// 넓은 화면
|
||||
function setWide() {
|
||||
$('#main_container').attr('class', 'container-fluid');
|
||||
}
|
||||
|
||||
|
||||
function showModal(data='EMPTY', title='JSON', json=true) {
|
||||
document.getElementById("modal_title").innerHTML = title;
|
||||
if (json) {
|
||||
data = JSON.stringify(data, null, 2);
|
||||
}
|
||||
document.getElementById("modal_body").innerHTML = '<pre style="white-space: pre-wrap;">' +data + '</pre>';
|
||||
|
||||
$("#large_modal").modal();
|
||||
}
|
||||
|
||||
|
||||
function getFormdata(form_id) {
|
||||
// on, off 일수도 있으니 모두 True, False로 통일하고
|
||||
// 밑에서는 False인 경우 값이 추가되지 않으니.. 수동으로 넣어줌
|
||||
var checkboxs = $(form_id + ' input[type=checkbox]');
|
||||
//for (var i in checkboxs) {
|
||||
for (var i =0 ; i < checkboxs.length; i++) {
|
||||
if ( $(checkboxs[i]).is(':checked') ) {
|
||||
$(checkboxs[i]).val('True');
|
||||
} else {
|
||||
$(checkboxs[i]).val('False');
|
||||
}
|
||||
}
|
||||
var formData = $(form_id).serialize();
|
||||
$.each($(form_id + ' input[type=checkbox]')
|
||||
.filter(function(idx) {
|
||||
return $(this).prop('checked') === false
|
||||
}),
|
||||
function(idx, el) {
|
||||
var emptyVal = "False";
|
||||
formData += '&' + $(el).attr('name') + '=' + emptyVal;
|
||||
}
|
||||
);
|
||||
formData = formData.replace("&global_scheduler=True", "")
|
||||
formData = formData.replace("&global_scheduler=False", "")
|
||||
formData = formData.replace("global_scheduler=True&", "")
|
||||
formData = formData.replace("global_scheduler=False&", "")
|
||||
return formData;
|
||||
}
|
||||
|
||||
///////////////////////////////////////
|
||||
// camel
|
||||
|
||||
|
||||
function use_collapse(div, reverse=false) {
|
||||
var ret = $('#' + div).prop('checked');
|
||||
if (reverse) {
|
||||
if (ret) {
|
||||
$('#' + div + '_div').collapse('hide');
|
||||
} else {
|
||||
$('#' + div + '_div').collapse('show');
|
||||
}
|
||||
} else {
|
||||
if (ret) {
|
||||
$('#' + div + '_div').collapse('show');
|
||||
} else {
|
||||
$('#' + div + '_div').collapse('hide');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
///////////////////////////////////////
|
||||
// 유틸리티 - 프로젝트 관련성 없음
|
||||
///////////////////////////////////////
|
||||
|
||||
function humanFileSize(bytes) {
|
||||
var thresh = 1024;
|
||||
if(Math.abs(bytes) < thresh) {
|
||||
return bytes + ' B';
|
||||
}
|
||||
var units = ['KB','MB','GB','TB','PB','EB','ZB','YB']
|
||||
var u = -1;
|
||||
do {
|
||||
bytes /= thresh;
|
||||
++u;
|
||||
} while(Math.abs(bytes) >= thresh && u < units.length - 1);
|
||||
return bytes.toFixed(1)+' '+units[u];
|
||||
}
|
||||
|
||||
function FormatNumberLength(num, length) {
|
||||
var r = "" + num;
|
||||
while (r.length < length) {
|
||||
r = "0" + r;
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
function msToHMS( ms ) {
|
||||
// 1- Convert to seconds:
|
||||
var seconds = ms / 1000;
|
||||
// 2- Extract hours:
|
||||
var hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
|
||||
seconds = seconds % 3600; // seconds remaining after extracting hours
|
||||
// 3- Extract minutes:
|
||||
var minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
|
||||
// 4- Keep only seconds not extracted to minutes:
|
||||
seconds = seconds % 60;
|
||||
return (''+hours).padStart(2, "0")+":"+(''+minutes).padStart(2, "0")+":"+parseInt(seconds);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
///////////////////////////////////////
|
||||
// 사용 미확인
|
||||
///////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
function duration_str(duration) {
|
||||
duration = duration / 100;
|
||||
var minutes = parseInt(duration / 60);
|
||||
var hour = parseInt(minutes / 60);
|
||||
var min = parseInt(minutes % 60);
|
||||
var sec = parseInt((duration/60 - parseInt(duration/60)) * 60);
|
||||
return pad(hour, 2) + ':' + pad(min, 2) + ':' + pad(sec,2);
|
||||
|
||||
}
|
||||
// 자리맞춤
|
||||
function pad(n, width) {
|
||||
n = n + '';
|
||||
return n.length >= width ? n : new Array(width - n.length + 1).join('0') + n;
|
||||
}
|
||||
|
||||
// jquery extend function
|
||||
// post로 요청하면서 리다이렉트
|
||||
// 푹 자동에서 푹 기본 검색할때 사용
|
||||
$.extend(
|
||||
{
|
||||
redirectPost: function(location, args)
|
||||
{
|
||||
var form = '';
|
||||
$.each( args, function( key, value ) {
|
||||
console.log(key);
|
||||
console.log(value);
|
||||
value = value.split('"').join('\"')
|
||||
form += '<input type="hidden" name="'+key+'" value="'+value+'">';
|
||||
});
|
||||
$('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,589 @@
|
||||
// global socketio
|
||||
$(document).ready(function(){
|
||||
ResizeTextArea();
|
||||
});
|
||||
|
||||
$(document).ready(function(){
|
||||
$('.loading').hide();
|
||||
})
|
||||
.ajaxStart(function(){
|
||||
$('.loading').show();
|
||||
})
|
||||
.ajaxStop(function(){
|
||||
$('.loading').hide();
|
||||
});
|
||||
|
||||
var protocol = window.location.protocol;
|
||||
var frameSocket = io.connect(protocol + "//" + document.domain + ":" + location.port + "/framework");
|
||||
console.log(frameSocket);
|
||||
|
||||
frameSocket.on('notify', function(data){
|
||||
$.notify({
|
||||
message : data['msg'],
|
||||
url: data['url'],
|
||||
target: '_self'
|
||||
},{
|
||||
type: data['type'],
|
||||
z_index: 2000,
|
||||
});
|
||||
});
|
||||
|
||||
frameSocket.on('modal', function(data){
|
||||
m_modal(data.data, data.title, false);
|
||||
});
|
||||
|
||||
frameSocket.on('loading_hide', function(data){
|
||||
$('#loading').hide();
|
||||
});
|
||||
|
||||
frameSocket.on('refresh', function(data){
|
||||
console.log('data')
|
||||
window.location.reload();
|
||||
});
|
||||
|
||||
|
||||
$('#command_modal').on('hide.bs.modal', function (e) {
|
||||
//e.preventDefault(); 있으면 동작 안함.
|
||||
console.log("ff global command_modal hide.bs.modal CATCH")
|
||||
$.ajax({
|
||||
url: `/global/ajax/command_modal_hide`,
|
||||
type: 'POST',
|
||||
cache: false,
|
||||
data: {},
|
||||
dataType: 'json'
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
///////////////////////////////////////
|
||||
// Global - 버튼
|
||||
///////////////////////////////////////
|
||||
|
||||
$("body").on('click', '#globalOpenBtn', function(e) {
|
||||
e.preventDefault();
|
||||
url = $(this).data('url')
|
||||
window.open(url, "_blank");
|
||||
});
|
||||
|
||||
$("body").on('click', '#globalLinkBtn', function(e) {
|
||||
e.preventDefault();
|
||||
url = $(this).data('url')
|
||||
window.location.href = url;
|
||||
});
|
||||
|
||||
// global_link_btn 모두 찾아 변경
|
||||
|
||||
$("body").on('click', '#globalSettingSaveBtn', function(e){
|
||||
e.preventDefault();
|
||||
globalSettingSave();
|
||||
});
|
||||
|
||||
function globalSettingSave() {
|
||||
var formData = getFormdata('#setting');
|
||||
$.ajax({
|
||||
url: '/' + PACKAGE_NAME + '/ajax/setting_save',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: formData,
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
if (ret) {
|
||||
$.notify('<strong>설정을 저장하였습니다.</strong>', {
|
||||
type: 'success'
|
||||
});
|
||||
} else {
|
||||
$.notify('<strong>설정 저장에 실패하였습니다.</strong>', {
|
||||
type: 'warning'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$("body").on('click', '#globalEditBtn', function(e) {
|
||||
e.preventDefault();
|
||||
file = $(this).data('file');
|
||||
console.log(file);
|
||||
$.ajax({
|
||||
url: '/global/ajax/is_available_edit',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {},
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
if (ret.ret) {
|
||||
window.open('/flaskcode?open=' + file, ret.target);
|
||||
} else {
|
||||
notify('편집기 플러그인을 설치해야 합니다.', 'warning');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#globalCliboardBtn', function(e) {
|
||||
e.preventDefault();
|
||||
window.navigator.clipboard.writeText($(this).data('text'));
|
||||
notify("클립보드에 복사하였습니다.", "success");
|
||||
});
|
||||
|
||||
|
||||
// 사용 on / off
|
||||
$("body").on('change', '#globalSchedulerSwitchBtn', function(e) {
|
||||
e.preventDefault();
|
||||
var ret = $(this).prop('checked');
|
||||
$.ajax({
|
||||
url: '/'+PACKAGE_NAME+'/ajax/' + MODULE_NAME + '/scheduler',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {scheduler : ret},
|
||||
dataType: "json",
|
||||
success: function () {}
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('change', '#globalSchedulerSwitchPageBtn', function(e) {
|
||||
var ret = $(this).prop('checked');
|
||||
$.ajax({
|
||||
url: '/'+PACKAGE_NAME+'/ajax/' + MODULE_NAME + '/' + PAGE_NAME + '/scheduler',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {scheduler : ret},
|
||||
dataType: "json",
|
||||
success: function () {}
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#globalOneExecuteBtn', function(e) {
|
||||
e.preventDefault();
|
||||
$.ajax({
|
||||
url: '/'+PACKAGE_NAME+'/ajax/' + MODULE_NAME + '/one_execute',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {},
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
if (ret=='scheduler' || ret=='thread') {
|
||||
$.notify('<strong>작업을 시작하였습니다. ('+ret+')</strong>', {
|
||||
type: 'success'
|
||||
});
|
||||
} else if (ret == 'is_running') {
|
||||
$.notify('<strong>작업중입니다.</strong>', {
|
||||
type: 'warning'
|
||||
});
|
||||
} else {
|
||||
$.notify('<strong>작업 시작에 실패하였습니다.</strong>', {
|
||||
type: 'warning'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#globalOneExecutePageBtn', function(e) {
|
||||
e.preventDefault();
|
||||
$.ajax({
|
||||
url: '/'+PACKAGE_NAME+'/ajax/' + MODULE_NAME + '/' + PAGE_NAME + '/one_execute',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {sub:sub},
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
if (ret=='scheduler' || ret=='thread') {
|
||||
$.notify('<strong>작업을 시작하였습니다. ('+ret+')</strong>', {
|
||||
type: 'success'
|
||||
});
|
||||
} else if (ret == 'is_running') {
|
||||
$.notify('<strong>작업중입니다.</strong>', {
|
||||
type: 'warning'
|
||||
});
|
||||
} else {
|
||||
$.notify('<strong>작업 시작에 실패하였습니다.</strong>', {
|
||||
type: 'warning'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#globalImmediatelyExecuteBtn', function(e){
|
||||
e.preventDefault();
|
||||
$.ajax({
|
||||
url: '/'+PACKAGE_NAME+'/ajax/' + MODULE_NAME + '/immediately_execute',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {},
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
if (ret.msg != null) notify(ret.msg, ret.ret);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
$("body").on('click', '#globalImmediatelyExecutePageBtn', function(e){
|
||||
e.preventDefault();
|
||||
$.ajax({
|
||||
url: '/'+PACKAGE_NAME+'/ajax/' + MODULE_NAME + '/' + PAGE_NAME + '/immediately_execute',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {},
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
if (ret.msg != null) notify(ret.msg, ret.ret);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
$("body").on('click', '#globalDbDeleteBtn', function(e){
|
||||
e.preventDefault();
|
||||
document.getElementById("confirm_title").innerHTML = "DB 삭제";
|
||||
document.getElementById("confirm_body").innerHTML = "전체 목록을 삭제 하시겠습니까?";
|
||||
$('#confirm_button').attr('onclick', "globalDbDelete();");
|
||||
$("#confirm_modal").modal();
|
||||
return;
|
||||
});
|
||||
|
||||
function globalDbDelete() {
|
||||
$.ajax({
|
||||
url: '/'+PACKAGE_NAME+'/ajax/' + MODULE_NAME + '/reset_db',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
if (data) {
|
||||
$.notify('<strong>삭제하였습니다.</strong>', {
|
||||
type: 'success'
|
||||
});
|
||||
} else {
|
||||
$.notify('<strong>삭제에 실패하였습니다.</strong>',{
|
||||
type: 'warning'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$("body").on('click', '#globalDbDeletePageBtn', function(e){
|
||||
e.preventDefault();
|
||||
document.getElementById("confirm_title").innerHTML = "DB 삭제";
|
||||
document.getElementById("confirm_body").innerHTML = "전체 목록을 삭제 하시겠습니까?";
|
||||
$('#confirm_button').attr('onclick', "globalDbDeletePage();");
|
||||
$("#confirm_modal").modal();
|
||||
return;
|
||||
});
|
||||
|
||||
function globalDbDeletePage() {
|
||||
$.ajax({
|
||||
url: '/'+PACKAGE_NAME+'/ajax/' + MODULE_NAME + '/' + PAGE_NAME + '/reset_db',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {sub:sub},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
if (data) {
|
||||
$.notify('<strong>삭제하였습니다.</strong>', {
|
||||
type: 'success'
|
||||
});
|
||||
} else {
|
||||
$.notify('<strong>삭제에 실패하였습니다.</strong>',{
|
||||
type: 'warning'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
///////////////////////////////////////
|
||||
// Global - 함수
|
||||
///////////////////////////////////////
|
||||
|
||||
function globalSendCommand(command, arg1, arg2, arg3, modal_title, callback) {
|
||||
console.log("globalSendCommand [" + command + '] [' + arg1 + '] [' + arg2 + '] [' + arg3 + '] [' + modal_title + '] [' + callback + ']');
|
||||
console.log('/' + PACKAGE_NAME + '/ajax/' + MODULE_NAME + '/command');
|
||||
|
||||
$.ajax({
|
||||
url: '/' + PACKAGE_NAME + '/ajax/' + MODULE_NAME + '/command',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data:{command:command, arg1:arg1, arg2:arg2, arg3},
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
if (ret.msg != null) notify(ret.msg, ret.ret);
|
||||
if (ret.modal != null) showModal(ret.modal, modal_title, false);
|
||||
if (ret.json != null) showModal(ret.json, modal_title, true);
|
||||
if (callback != null) callback(ret);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function globalSendCommandPage(command, arg1, arg2, arg3, modal_title, callback) {
|
||||
console.log("globalSendCommandPage [" + command + '] [' + arg1 + '] [' + arg2 + '] [' + arg3 + '] [' + modal_title + '] [' + callback + ']');
|
||||
console.log('/' + PACKAGE_NAME + '/ajax/' + MODULE_NAME + '/command');
|
||||
|
||||
$.ajax({
|
||||
url: '/' + PACKAGE_NAME + '/ajax/' + MODULE_NAME + '/' + PAGE_NAME + '/command',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data:{command:command, arg1:arg1, arg2:arg2, arg3},
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
if (ret.msg != null) notify(ret.msg, ret.ret);
|
||||
if (ret.modal != null) m_modal(ret.modal, modal_title, false);
|
||||
if (ret.json != null) m_modal(ret.json, modal_title, true);
|
||||
if (callback != null) callback(ret);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function shutdown_confirm() {
|
||||
$("#confirm_title").html("종료 확인");
|
||||
$("#confirm_body").html("종료 하시겠습니까?");
|
||||
$('#confirm_button').attr('onclick', 'window.location.href = "/system/shutdown";');
|
||||
$("#confirm_modal").modal();
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
///////////////////////////////////////
|
||||
// 리스트 화면 기본
|
||||
///////////////////////////////////////
|
||||
|
||||
|
||||
function globalRequestSearch(page, move_top=true) {
|
||||
var formData = getFormdata('#form_search')
|
||||
formData += '&page=' + page;
|
||||
$.ajax({
|
||||
url: '/' + PACKAGE_NAME + '/ajax/' + MODULE_NAME + '/web_list',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: formData,
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
current_data = data;
|
||||
if (move_top)
|
||||
window.scrollTo(0,0);
|
||||
make_list(data.list)
|
||||
make_page_html(data.paging)
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
function make_page_html(data) {
|
||||
str = ' \
|
||||
<div class="d-inline-block"></div> \
|
||||
<div class="row mb-3"> \
|
||||
<div class="col-sm-12"> \
|
||||
<div class="btn-toolbar" style="justify-content: center;" role="toolbar" aria-label="Toolbar with button groups" > \
|
||||
<div class="btn-group btn-group-sm mr-2" role="group" aria-label="First group">'
|
||||
if (data.prev_page) {
|
||||
str += '<button id="gloablSearchPageBtn" data-page="' + (data.start_page-1) + '" type="button" class="btn btn-secondary">«</button>'
|
||||
}
|
||||
|
||||
for (var i = data.start_page ; i <= data.last_page ; i++) {
|
||||
str += '<button id="gloablSearchPageBtn" data-page="' + i +'" type="button" class="btn btn-secondary" ';
|
||||
if (i == data.current_page) {
|
||||
current_page = i
|
||||
str += 'disabled';
|
||||
}
|
||||
str += '>'+i+'</button>';
|
||||
}
|
||||
if (data.next_page) {
|
||||
str += '<button id="gloablSearchPageBtn" data-page="' + (data.last_page+1) + '" type="button" class="btn btn-secondary">»</button>'
|
||||
}
|
||||
|
||||
str += '</div> \
|
||||
</div> \
|
||||
</div> \
|
||||
</div> \
|
||||
'
|
||||
document.getElementById("page1").innerHTML = str;
|
||||
document.getElementById("page2").innerHTML = str;
|
||||
}
|
||||
|
||||
|
||||
|
||||
$("body").on('click', '#gloablSearchPageBtn', function(e){
|
||||
e.preventDefault();
|
||||
globalRequestSearch($(this).data('page'), false);
|
||||
});
|
||||
|
||||
$("body").on('click', '#globalSearchSearchBtn', function(e){
|
||||
e.preventDefault();
|
||||
globalRequestSearch(1, false);
|
||||
});
|
||||
|
||||
$("body").on('click', '#globalSearchResetBtn', function(e){
|
||||
e.preventDefault();
|
||||
$("#order").val('desc');
|
||||
$("#option1").val('all');
|
||||
$("#option2").val('all');
|
||||
$("#keyword").val('');
|
||||
globalRequestSearch(1, false);
|
||||
});
|
||||
|
||||
|
||||
|
||||
///////////////////////////////////////
|
||||
// 파일 선택 모달
|
||||
///////////////////////////////////////
|
||||
|
||||
var select_local_file_modal_callback = null;
|
||||
|
||||
function globalSelectLocalFile(title, init_path, func) {
|
||||
_selectLocalFileModal(title, init_path, false, func);
|
||||
}
|
||||
|
||||
function globalSelectLocalFolder(title, init_path, func) {
|
||||
_selectLocalFileModal(title, init_path, true, func);
|
||||
}
|
||||
|
||||
function _selectLocalFileModal(title, init_path, only_dir, func) {
|
||||
if (init_path == '' || init_path == null)
|
||||
init_path = '/';
|
||||
document.getElementById("select_local_file_modal_title").innerHTML = title;
|
||||
document.getElementById("select_local_file_modal_path").value = init_path;
|
||||
document.getElementById("select_local_file_modal_only_dir").value = only_dir;
|
||||
select_local_file_modal_callback = func;
|
||||
$("#select_local_file_modal").modal();
|
||||
listdir(init_path, only_dir);
|
||||
}
|
||||
|
||||
$("body").on('click', '#global_select_local_file_load_btn', function(e) {
|
||||
e.preventDefault();
|
||||
let current_path = $('#select_local_file_modal_path').val().trim();
|
||||
only_dir = $('#select_local_file_modal_only_dir').val().trim();
|
||||
listdir(current_path, only_dir);
|
||||
});
|
||||
|
||||
$("body").on('click', '#select_local_file_modal_confirm_btn', function(e) {
|
||||
e.preventDefault();
|
||||
if (select_local_file_modal_callback != null)
|
||||
select_local_file_modal_callback($('#select_local_file_modal_path').val().trim());
|
||||
$("#select_local_file_modal").modal('toggle');
|
||||
});
|
||||
|
||||
|
||||
let listdir = (path = '/', only_dir = true) => {
|
||||
$.ajax({
|
||||
url: `/global/ajax/listdir`,
|
||||
type: 'POST',
|
||||
cache: false,
|
||||
data: {
|
||||
path: path,
|
||||
only_dir : only_dir
|
||||
},
|
||||
dataType: 'json'
|
||||
}).done((datas) => {
|
||||
console.log(datas)
|
||||
if (datas.length == 0) {
|
||||
return false;
|
||||
}
|
||||
let new_obj = ``;
|
||||
const path_spliter = (path.indexOf('/')>=0)?'/':'\\';
|
||||
$('#select_local_file_modal_list_group').empty();
|
||||
for (let dt of datas) {
|
||||
tmp = dt.split('|');
|
||||
new_obj += `<a href='#' class="list-group-item list-group-item-action item_path" data-value="${tmp[1]}">${tmp[0]}</a>`;
|
||||
}
|
||||
$('#select_local_file_modal_list_group').append(new_obj);
|
||||
$('.item_path').off('click').click((evt) => {
|
||||
|
||||
let new_path = '';
|
||||
/*
|
||||
if ($(evt.currentTarget).text() === '..'){
|
||||
let split_path = '';
|
||||
split_path = path.split(path_spliter);
|
||||
split_path.pop();
|
||||
new_path = split_path.join(path_spliter);
|
||||
if (new_path.length === 0){
|
||||
new_path = path_spliter
|
||||
}
|
||||
} else {
|
||||
//new_path = (path !== path_spliter) ? path + path_spliter + $(evt.currentTarget).text() : path + $(evt.currentTarget).text();
|
||||
new_path = $(evt.currentTarget).data('value');
|
||||
console.log(new_path)
|
||||
console.log(evt)
|
||||
|
||||
}
|
||||
*/
|
||||
new_path = $(evt.currentTarget).data('value');
|
||||
$('#select_local_file_modal_path').val(new_path);
|
||||
listdir(new_path, only_dir);
|
||||
|
||||
});
|
||||
}).fail((datas) => {
|
||||
$.notify('<strong>경로 읽기 실패</strong><br/>${add_path}', {type: 'danger'});
|
||||
});
|
||||
return false;
|
||||
}
|
||||
// 파일 선택 모달 End
|
||||
///////////////////////////////////////
|
||||
|
||||
|
||||
///////////////////////////////////////
|
||||
// Command MODAL
|
||||
///////////////////////////////////////
|
||||
|
||||
frameSocket.on('command_modal_add_text', function(data){
|
||||
document.getElementById("command_modal_textarea").innerHTML += data ;
|
||||
document.getElementById("command_modal_textarea").scrollTop = document.getElementById("command_modal_textarea").scrollHeight;
|
||||
});
|
||||
|
||||
frameSocket.on('command_modal_input_disable', function(data){
|
||||
$('#command_modal_input').attr('disabled', true);
|
||||
});
|
||||
|
||||
frameSocket.on('command_modal_show', function(data){
|
||||
command_modal_show(data)
|
||||
});
|
||||
|
||||
frameSocket.on('command_modal_clear', function(data){
|
||||
document.getElementById("command_modal_textarea").innerHTML = ""
|
||||
});
|
||||
|
||||
function command_modal_show(title) {
|
||||
ClientHeight = window.innerHeight
|
||||
document.getElementById("command_modal_title").innerHTML = title
|
||||
$("#command_modal").height(ClientHeight+50);
|
||||
$("#command_modal_textarea").height(ClientHeight-380);
|
||||
$("#command_modal").modal({backdrop: 'static', keyboard: false}, 'show');
|
||||
$('#command_modal_input').attr('disabled', false);
|
||||
}
|
||||
|
||||
$("body").on('click', '#command_modal_input_btn', function(e) {
|
||||
e.preventDefault();
|
||||
$.ajax({
|
||||
url: '/global/ajax/command_modal_input',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {cmd:$('#command_modal_input').val()},
|
||||
dataType: "json",
|
||||
success: function (ret) {
|
||||
$('#command_modal_input').val('');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
$(window).resize(function() {
|
||||
ResizeTextArea();
|
||||
});
|
||||
|
||||
|
||||
function ResizeTextArea() {
|
||||
ClientHeight = window.innerHeight
|
||||
$("#command_modal").height(ClientHeight-100);
|
||||
$("#command_modal_textarea").height(ClientHeight-380);
|
||||
}
|
||||
|
||||
///////////////////////////////////////
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
/*
|
||||
<div class="d-inline-block"></div>
|
||||
|
||||
*/
|
||||
function j_button_group(h) {
|
||||
var str = '<div class="btn-group btn-group-sm flex-wrap mr-2" role="group">';
|
||||
str += h
|
||||
str += '</div>';
|
||||
return str;
|
||||
}
|
||||
|
||||
// primary, secondary, success, danger, warning, info, light, dark, white
|
||||
function j_button(id, text, data={}, color='primary', outline=true, small=false) {
|
||||
var str = '<button id="'+id+'" name="'+id+'" class="btn btn-sm btn';
|
||||
if (outline) {
|
||||
str += '-outline';
|
||||
}
|
||||
str += '-' + color+'';
|
||||
if (small) {
|
||||
str += ' py-0" style="font-size: 0.8em;"';
|
||||
} else {
|
||||
str += '" ';
|
||||
}
|
||||
for ( var key in data) {
|
||||
str += ' data-' + key + '="' + data[key]+ '" '
|
||||
}
|
||||
str += '>' + text + '</button>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function j_button_small(id, text, data={}, color='primary', outline=true) {
|
||||
return j_button(id, text, data, color, outline, true);
|
||||
}
|
||||
|
||||
|
||||
|
||||
function j_row_start(padding='10', align='center') {
|
||||
var str = '<div class="row" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+';">';
|
||||
return str;
|
||||
}
|
||||
function j_col(w, h, align='left') {
|
||||
var str = '<div class="col-sm-' + w + ' " style="text-align: '+align+'; word-break:break-all;">';
|
||||
str += h;
|
||||
str += '</div>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function j_col_wide(w, h, align='left') {
|
||||
var str = '<div class="col-sm-' + w + ' " style="padding:0px; margin:0px; text-align: '+align+'; word-break:break-all;">';
|
||||
str += h;
|
||||
str += '</div>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function j_row_end() {
|
||||
var str = '</div>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function j_hr(margin='5') {
|
||||
var str = '<hr style="width: 100%; margin:'+margin+'px;" />';
|
||||
return str;
|
||||
}
|
||||
|
||||
function j_hr_black() {
|
||||
var str = '<hr style="width: 100%; color: black; height: 2px; background-color:black;" />';
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 한줄 왼쪽
|
||||
function j_row_info(left, right, l=2, r=8) {
|
||||
var str =' \
|
||||
<div class="row"> \
|
||||
<div class="col-sm-'+1+'" style="text-align:right;"></div> \
|
||||
<div class="col-sm-'+l+'" style="text-align:right;"> \
|
||||
<strong>'+ left +'</strong> \
|
||||
</div> \
|
||||
<div class="col-sm-'+r+'" style="word-break:break-all;"> \
|
||||
<span class="text-left" style="padding-left:10px; padding-top:3px;">'+right +'</span> \
|
||||
</div> \
|
||||
</div>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function j_progress(id, width, label) {
|
||||
var str = '';
|
||||
str += '<div class="progress" style="height: 25px;">'
|
||||
str += '<div id="'+id+'" class="progress-bar" style="background-color:yellow;width:'+width+'%"></div>';
|
||||
str += '<div id="'+id+'_label" class="justify-content-center d-flex w-100 " style="margin-top:2px">'+label+'</div>';
|
||||
str += '</div>'
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function make_log(key, value, left=2, right=10) {
|
||||
row = m_col(left, key, aligh='right');
|
||||
row += m_col(right, value, aligh='left');
|
||||
return row;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// javascript에서 화면 생성
|
||||
function text_color(text, color='red') {
|
||||
return '<span style="color:'+color+'; font-weight:bold">' + text + '</span>';
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
///////////////////////////////////////
|
||||
// UI - 확장설정 - dropdown
|
||||
///////////////////////////////////////
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function(){
|
||||
/////// Prevent closing from click inside dropdown
|
||||
document.querySelectorAll('.dropdown-menu').forEach(function(element){
|
||||
element.addEventListener('click', function (e) {
|
||||
e.stopPropagation();
|
||||
});
|
||||
})
|
||||
|
||||
// make it as accordion for smaller screens
|
||||
if (window.innerWidth < 992) {
|
||||
// close all inner dropdowns when parent is closed
|
||||
document.querySelectorAll('.navbar .dropdown').forEach(function(everydropdown){
|
||||
everydropdown.addEventListener('hidden.bs.dropdown', function () {
|
||||
// after dropdown is hidden, then find all submenus
|
||||
this.querySelectorAll('.submenu').forEach(function(everysubmenu){
|
||||
// hide every submenu as well
|
||||
everysubmenu.style.display = 'none';
|
||||
});
|
||||
})
|
||||
});
|
||||
|
||||
document.querySelectorAll('.dropdown-menu a').forEach(function(element){
|
||||
element.addEventListener('click', function (e) {
|
||||
|
||||
let nextEl = this.nextElementSibling;
|
||||
if(nextEl && nextEl.classList.contains('submenu')) {
|
||||
// prevent opening link if link needs to open dropdown
|
||||
e.preventDefault();
|
||||
console.log(nextEl);
|
||||
if(nextEl.style.display == 'block'){
|
||||
nextEl.style.display = 'none';
|
||||
} else {
|
||||
nextEl.style.display = 'block';
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
// end if innerWidth
|
||||
});
|
||||
// DOMContentLoaded end
|
||||
///////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function m_row_start_hover(padding='10', align='center') {
|
||||
var str = '<div class="row my_hover" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+';">';
|
||||
return str;
|
||||
}
|
||||
function m_row_start_top(padding='10') {
|
||||
return m_row_start(padding, 'top');
|
||||
}
|
||||
function m_row_start_color(padding='10', align='center', color='') {
|
||||
var str = '<div class="row" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+'; background-color:'+color+'">';
|
||||
return str;
|
||||
}
|
||||
function m_row_start_color2(padding='10', align='center') {
|
||||
var str = '<div class="row bg-dark text-white" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+';">';
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
|
||||
//border
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
// 체크박스는 자바로 하면 on/off 스크립트가 안먹힘.
|
||||
|
||||
|
||||
|
||||
|
||||
function m_tab_head(name, active) {
|
||||
if (active) {
|
||||
var str = '<a class="nav-item nav-link active" id="id_'+name+'" data-toggle="tab" href="#'+name+'" role="tab">'+name+'</a>';
|
||||
} else {
|
||||
var str = '<a class="nav-item nav-link" id="id_'+name+'" data-toggle="tab" href="#'+name+'" role="tab">'+name+'</a>';
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
function m_tab_content(name, content, active) {
|
||||
if (active) {
|
||||
var str = '<div class="tab-pane fade show active" id="'+name+'" role="tabpanel" >';
|
||||
} else {
|
||||
var str = '<div class="tab-pane fade show" id="'+name+'" role="tabpanel" >';
|
||||
}
|
||||
str += content;
|
||||
str += '</div>'
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
function m_progress2(id, width, label) {
|
||||
var str = '';
|
||||
str += '<div class="progress" style="height: 25px;">'
|
||||
str += '<div id="'+id+'" class="progress-bar" style="background-color:yellow;width:'+width+'%"></div>';
|
||||
str += '<div id="'+id+'_label" class="justify-content-center d-flex w-100 position-absolute" style="margin:0px; margin-top:2px">'+label+'</div>';
|
||||
str += '</div>'
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+5
File diff suppressed because one or more lines are too long
@@ -0,0 +1,361 @@
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// 공용 버튼
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
// global_cache_confirm_btn => global_offcloud_cache_confirm_btn
|
||||
$("body").on('click', '#global_offcloud_cache_confirm_btn', function(e){
|
||||
e.preventDefault();
|
||||
hash = $(this).data('hash');
|
||||
$.ajax({
|
||||
url: '/offcloud2/ajax/hash',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data:{hash:hash},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
if (data == 'true') {
|
||||
$.notify('<strong>캐쉬 되어 있습니다.</strong>', {
|
||||
type: 'success'
|
||||
});
|
||||
} else if (data == 'false') {
|
||||
$.notify('<strong>캐쉬 되어 있지 않습니다.</strong>', {
|
||||
type: 'warning'
|
||||
});
|
||||
} else if (data == 'fail') {
|
||||
$.notify('<strong>캐쉬 확인 실패</strong>', {
|
||||
type: 'warning'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
//$(location).attr('href', '/offcloud/cache?magnet=' + hash)
|
||||
});
|
||||
|
||||
//global_add_remote_btn -> global_offcloud_add_btn
|
||||
$("body").on('click', '#global_offcloud_add_btn', function(e) {
|
||||
e.preventDefault();
|
||||
hash = $(this).data('hash');
|
||||
$.ajax({
|
||||
url: '/offcloud2/ajax/add_remote',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {hash:hash},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
m_modal(data)
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
$("body").on('click', '#global_downloader_add_btn', function(e){
|
||||
e.preventDefault();
|
||||
download_url = $(this).data('hash');
|
||||
$.ajax({
|
||||
url: '/downloader/ajax/add_download',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {download_url:download_url},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
show_result_add_download(data);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
// 토렌트 프로그램에 다운로드 추가할 결과를 보여주는
|
||||
function show_result_add_download(data) {
|
||||
try {
|
||||
sub = ''
|
||||
program = '토렌트'
|
||||
if (data.default_torrent_program == '0') {
|
||||
program = '트랜스미션에 토렌트'
|
||||
sub = 'transmission'
|
||||
} else if (data.default_torrent_program == '1') {
|
||||
program = '다운로드스테이션에 토렌트'
|
||||
sub = 'downloadstation'
|
||||
} else if (data.default_torrent_program == '2') {
|
||||
program = '큐빗토렌트다에 토렌트'
|
||||
sub = 'qbittorrent'
|
||||
} else if (data.default_torrent_program == '3') {
|
||||
program = 'aria2에 토렌트'
|
||||
sub = 'aria2'
|
||||
} else if (data.default_torrent_program == '4') {
|
||||
program = 'PikPak에 토렌트'
|
||||
sub = 'pikpak'
|
||||
}
|
||||
}
|
||||
catch {
|
||||
}
|
||||
if (data.ret == 'success') {
|
||||
$.notify({message:'<strong>'+ program +'를 추가하였습니다.</strong><br>클릭시 다운로드 상태창으로 이동', url:'/downloader/'+sub+'/status',
|
||||
target: '_self'}, {
|
||||
type: 'success',
|
||||
});
|
||||
} else if (data.ret == 'success2') {
|
||||
$.notify('<strong>일반 파일 다운로드를 시작하였습니다.</strong>', {
|
||||
type: 'success'
|
||||
});
|
||||
} else if (data.ret == 'fail') {
|
||||
$.notify('<strong>'+ program +' 추가에 실패하였습니다.</strong>', {
|
||||
type: 'warning'
|
||||
});
|
||||
} else {
|
||||
$.notify('<strong>'+ program +' 추가 에러<br>'+data.error+'</strong>', {
|
||||
type: 'warning'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
$("body").on('click', '#global_torrent_info_btn', function(e) {
|
||||
e.preventDefault();
|
||||
hash = $(this).data('hash');
|
||||
$.ajax({
|
||||
url: '/torrent_info/ajax/torrent_info',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {hash:hash},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
m_modal(data, "토렌트 정보")
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
function get_torrent_program_name(p) {
|
||||
if (p == '0') return '트랜스미션'
|
||||
else if (p == '1') return '다운로드스테이션'
|
||||
else if (p == '2') return '큐빗토렌트'
|
||||
else if (p == '3') return 'aria2'
|
||||
else if (p == '4') return 'PikPak'
|
||||
}
|
||||
|
||||
|
||||
function global_relay_test(remote) {
|
||||
$.ajax({
|
||||
url: '/' + 'gd_share_client' + '/ajax/'+'base'+'/relay_test',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {remote:remote},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
if (data.ret == 'success') {
|
||||
$.notify('<strong>릴레이 공유가 가능합니다.<strong>', {type: 'success'});
|
||||
}else {
|
||||
$.notify('<strong>설정이 잘못 되어 있습니다.</strong>', {type: 'warning'});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$("#video_modal").on('hidden.bs.modal', function () {
|
||||
document.getElementById("video_modal_video").pause();
|
||||
//streaming_kill();
|
||||
});
|
||||
|
||||
$("#video_modal").on('click', '#trailer_close_btn', function(e){
|
||||
e.preventDefault();
|
||||
document.getElementById("video_modal_video").pause();
|
||||
//streaming_kill();
|
||||
});
|
||||
|
||||
function streaming_kill(command, data={}) {
|
||||
$.ajax({
|
||||
url: '/' + 'ffmpeg' + '/ajax/streaming_kill',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data:{},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Global.. JS 파일로 뺄것
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
$("body").on('click', '#global_json_btn', function(e){
|
||||
e.preventDefault();
|
||||
var id = $(this).data('id');
|
||||
for (i in current_data.list) {
|
||||
if (current_data.list[i].id == id) {
|
||||
m_modal(current_data.list[i])
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
$("body").on('click', '#global_reset_btn', function(e){
|
||||
e.preventDefault();
|
||||
document.getElementById("order").value = 'desc';
|
||||
document.getElementById("option").value = 'all';
|
||||
document.getElementById("search_word").value = '';
|
||||
global_sub_request_search('1')
|
||||
});
|
||||
|
||||
$("body").on('click', '#global_remove_btn', function(e) {
|
||||
e.preventDefault();
|
||||
id = $(this).data('id');
|
||||
$.ajax({
|
||||
url: '/'+package_name+'/ajax/'+sub+ '/db_remove',
|
||||
type: "POST",
|
||||
cache: false,
|
||||
data: {id:id},
|
||||
dataType: "json",
|
||||
success: function (data) {
|
||||
if (data) {
|
||||
$.notify('<strong>삭제되었습니다.</strong>', {
|
||||
type: 'success'
|
||||
});
|
||||
global_sub_request_search(current_data.paging.current_page, false)
|
||||
} else {
|
||||
$.notify('<strong>삭제 실패</strong>', {
|
||||
type: 'warning'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
|
||||
|
||||
function m_row_start(padding='10', align='center') {
|
||||
var str = '<div class="row" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+';">';
|
||||
return str;
|
||||
}
|
||||
function m_row_start_hover(padding='10', align='center') {
|
||||
var str = '<div class="row my_hover" style="padding-top: '+padding+'px; padding-bottom:'+padding+'px; align-items:'+align+';">';
|
||||
return str;
|
||||
}
|
||||
function m_row_start_top(padding='10') {
|
||||
return m_row_start(padding, 'top');
|
||||
}
|
||||
|
||||
|
||||
function m_row_end() {
|
||||
var str = '</div>';
|
||||
return str;
|
||||
}
|
||||
|
||||
//border
|
||||
function m_col(w, h, align='left') {
|
||||
var str = '<div class="col-sm-' + w + ' " style="text-align: '+align+'; word-break:break-all;">';
|
||||
str += h
|
||||
str += '</div>';
|
||||
return str
|
||||
}
|
||||
|
||||
function m_col2(w, h, align='left') {
|
||||
var str = '<div class="col-sm-' + w + ' " style="padding:5px; margin:0px; text-align: '+align+'; word-break:break-all;">';
|
||||
str += h
|
||||
str += '</div>';
|
||||
return str
|
||||
}
|
||||
|
||||
|
||||
function m_button_group(h) {
|
||||
var str = '<div class="btn-group btn-group-sm flex-wrap mr-2" role="group">';
|
||||
str += h
|
||||
str += '</div>';
|
||||
return str;
|
||||
}
|
||||
|
||||
function m_button(id, text, data) {
|
||||
var str = '<button id="'+id+'" name="'+id+'" class="btn btn-sm btn-outline-success" '
|
||||
for ( var i in data) {
|
||||
str += ' data-' + data[i].key + '="' + data[i].value+ '" '
|
||||
}
|
||||
str += '>' + text + '</button>';
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
function m_hr(margin='5') {
|
||||
var str = '<hr style="width: 100%; margin:'+margin+'px;" />';
|
||||
return str;
|
||||
}
|
||||
|
||||
|
||||
function m_hr_black() {
|
||||
var str = '<hr style="width: 100%; color: black; height: 2px; background-color:black;" />';
|
||||
return str;
|
||||
}
|
||||
// 체크박스는 자바로 하면 on/off 스크립트가 안먹힘.
|
||||
|
||||
|
||||
function m_modal(data='EMPTY', title='JSON', json=true) {
|
||||
document.getElementById("modal_title").innerHTML = title;
|
||||
if (json) {
|
||||
data = JSON.stringify(data, null, 2);
|
||||
}
|
||||
document.getElementById("modal_body").innerHTML = "<pre>"+ data + "</pre>";;
|
||||
$("#large_modal").modal();
|
||||
}
|
||||
|
||||
function m_tab_head(name, active) {
|
||||
if (active) {
|
||||
var str = '<a class="nav-item nav-link active" id="id_'+name+'" data-toggle="tab" href="#'+name+'" role="tab">'+name+'</a>';
|
||||
} else {
|
||||
var str = '<a class="nav-item nav-link" id="id_'+name+'" data-toggle="tab" href="#'+name+'" role="tab">'+name+'</a>';
|
||||
}
|
||||
return str;
|
||||
}
|
||||
|
||||
function m_tab_content(name, content, active) {
|
||||
if (active) {
|
||||
var str = '<div class="tab-pane fade show active" id="'+name+'" role="tabpanel" >';
|
||||
} else {
|
||||
var str = '<div class="tab-pane fade show" id="'+name+'" role="tabpanel" >';
|
||||
}
|
||||
str += content;
|
||||
str += '</div>'
|
||||
return str;
|
||||
}
|
||||
|
||||
Vendored
+25
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,61 @@
|
||||
{% from "macro_menu.html" import menu, menu_module, menu_page with context %}
|
||||
{% from "macro_include.html" import apply_theme, modals with context %}
|
||||
{% import "macro.html" as macros %}
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head lang="ko">
|
||||
{% block head %}
|
||||
<title>{{get_web_title()}}</title>
|
||||
{% endblock %}
|
||||
<meta name="google" value="notranslate">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
|
||||
<link rel="shortcut icon" href="{{ url_for('static', filename='img/favicon.ico') }}">
|
||||
<link href="{{ url_for('static', filename='css/bootstrap.min.css') }}" rel="stylesheet">
|
||||
{% set theme = get_theme() %}
|
||||
<link href="{{ url_for('static', filename='css/theme/'+theme+'_bootstrap.min.css') }}" rel="stylesheet">
|
||||
<link href="{{ url_for('static', filename='css/animate.min.css') }}" rel="stylesheet">
|
||||
<link href="{{ url_for('static', filename='css/custom.css') }}" rel="stylesheet">
|
||||
<link href="https://unpkg.com/balloon-css/balloon.min.css" rel="stylesheet">
|
||||
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
|
||||
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
|
||||
<!--<script src="{{ url_for('static', filename='js/popper.min.js') }}"></script>-->
|
||||
|
||||
<script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/bootstrap-notify.min.js') }}"></script>
|
||||
|
||||
<script src="{{ url_for('static', filename='js/ff_common1.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/ff_ui1.js') }}"></script>
|
||||
|
||||
|
||||
<!--<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.6/socket.io.js"></script>-->
|
||||
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.5.0/socket.io.js"></script>
|
||||
<!-- 토글 -->
|
||||
<link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.4.0/css/bootstrap4-toggle.min.css" rel="stylesheet">
|
||||
<script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.4.0/js/bootstrap4-toggle.min.js"></script>
|
||||
<!-- end 토글 -->
|
||||
|
||||
</head>
|
||||
|
||||
<body class="body ">
|
||||
{{ menu() }}
|
||||
{{ menu_module() }}
|
||||
|
||||
<!--</nav>-->
|
||||
<main id="main_container" role="main" class="container">
|
||||
<div class="d-inline-block"></div>
|
||||
{{ menu_page() }}
|
||||
<div>
|
||||
{% block content %}{% endblock %}
|
||||
</div>
|
||||
</main>
|
||||
<div class="loading" id="loading">
|
||||
<img src="/static/img/loading.gif" />
|
||||
</div>
|
||||
{{ modals() }}
|
||||
</body>
|
||||
</html>
|
||||
|
||||
<!-- 글로벌 버튼이 모두 나오고 처리-->
|
||||
<script src="{{ url_for('static', filename='js/sjva_global1.js') }}"></script>
|
||||
<script src="{{ url_for('static', filename='js/ff_global1.js') }}"></script>
|
||||
@@ -0,0 +1,81 @@
|
||||
{% extends "base.html" %}
|
||||
{% block content %}
|
||||
<div>
|
||||
<nav>
|
||||
{{ macros.m_tab_head_start() }}
|
||||
{{ macros.m_tab_head('old', '이전', true) }}
|
||||
{{ macros.m_tab_head('new', '실시간', false) }}
|
||||
{{ macros.m_tab_head_end() }}
|
||||
</nav>
|
||||
<div class="tab-content" id="nav-tabContent">
|
||||
{{ macros.m_tab_content_start('이전', true) }}
|
||||
<div>
|
||||
<textarea id="log" class="col-md-12" rows="30" charswidth="23" disabled style="background-color:#ffffff;visibility:hidden"></textarea>
|
||||
</div>
|
||||
{{ macros.m_tab_content_end() }}
|
||||
|
||||
{{ macros.m_tab_content_start('실시간', false) }}
|
||||
<div>
|
||||
<textarea id="add" class="col-md-12" rows="30" charswidth="23" disabled style="background-color:#ffffff;visibility:visible"></textarea>
|
||||
</div>
|
||||
|
||||
<div class="form-inline">
|
||||
<label class="form-check-label" for="auto_scroll">자동 스크롤</label>
|
||||
<input id="auto_scroll" name="auto_scroll" class="form-control form-control-sm" type="checkbox" data-toggle="toggle" checked>
|
||||
<span class='text-left' style="padding-left:25px; padding-top:0px">
|
||||
<button id="clear" class="btn btn-sm btn-outline-success">리셋</button>
|
||||
</span>
|
||||
</div>
|
||||
{{ macros.m_tab_content_end() }}
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<script type="text/javascript">
|
||||
$(document).ready(function() {
|
||||
setWide();
|
||||
$('#loading').show();
|
||||
ResizeTextAreaLog()
|
||||
})
|
||||
|
||||
function ResizeTextAreaLog() {
|
||||
ClientHeight = window.innerHeight
|
||||
$("#log").height(ClientHeight-240);
|
||||
$("#add").height(ClientHeight-260);
|
||||
}
|
||||
|
||||
$(window).resize(function() {
|
||||
ResizeTextAreaLog();
|
||||
});
|
||||
|
||||
|
||||
var protocol = window.location.protocol;
|
||||
var socket = io.connect(protocol + "//" + document.domain + ":" + location.port + "/log");
|
||||
socket.emit("start", {'package':'{{package}}'} );
|
||||
socket.on('on_start', function(data){
|
||||
document.getElementById("log").innerHTML += data.data;
|
||||
document.getElementById("log").scrollTop = document.getElementById("log").scrollHeight;
|
||||
document.getElementById("log").style.visibility = 'visible';
|
||||
$('#loading').hide();
|
||||
});
|
||||
|
||||
socket.on('add', function(data){
|
||||
if (data.package == "{{package}}") {
|
||||
var chk = $('#auto_scroll').is(":checked");
|
||||
document.getElementById("add").innerHTML += data.data;
|
||||
if (chk) document.getElementById("add").scrollTop = document.getElementById("add").scrollHeight;
|
||||
}
|
||||
});
|
||||
|
||||
$("#clear").click(function(e) {
|
||||
e.preventDefault();
|
||||
document.getElementById("add").innerHTML = '';
|
||||
});
|
||||
|
||||
$("#auto_scroll").click(function(){
|
||||
var chk = $(this).is(":checked");//.attr('checked');
|
||||
});
|
||||
|
||||
</script>
|
||||
{% endblock %}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,95 @@
|
||||
{% import "macro.html" as macros %}
|
||||
|
||||
|
||||
|
||||
{% macro modals() %}
|
||||
<!-- Modal -->
|
||||
<div class="modal fade" id="large_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h4 class="modal-title" id="modal_title"></h4>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
|
||||
</div>
|
||||
<div class="modal-body" id="modal_body" style="word-break:break-all;">
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-default" data-dismiss="modal">닫기</button>
|
||||
<!--<button type="button" class="btn btn-primary">Save changes</button>-->
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="confirm_modal" class="modal" tabindex="-1" role="dialog">
|
||||
<div class="modal-dialog" role="document">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h5 id="confirm_title" class="modal-title">Modal title</h5>
|
||||
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
<div id="confirm_body" class="modal-body">
|
||||
<p>Modal body text goes here.</p>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button id="confirm_button" type="button" class="btn btn-primary" data-dismiss="modal">확인</button>
|
||||
<button id="confirm_cancel_button" type="button" class="btn btn-secondary" data-dismiss="modal">취소</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 경로 선택 모달 -->
|
||||
<div class="modal fade" id="select_local_file_modal" tabindex="-1" role="dialog" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg">
|
||||
<div class="modal-content">
|
||||
<div class="modal-header">
|
||||
<h4 class="modal-title" id="select_local_file_modal_title">경로 선택</h4>
|
||||
</div>
|
||||
<div class="modal-body" id="modal_body" style="word-break: break-all;">
|
||||
<div class="row" style="padding-top: 10px; padding-bottom:10px; align-items: center;">
|
||||
<div class="col-sm-1 set-left"><strong>Path</strong></div>
|
||||
<div class="col-sm-11">
|
||||
<div class="input-group col-sm-12">
|
||||
<input id="select_local_file_modal_path" name="select_local_file_modal_path" type="text" class="form-control form-control-sm" value="/">
|
||||
<div class="btn-group btn-group-sm flex-wrap mr-2" role="group" style="padding-left:5px; padding-top:0px">
|
||||
<button id="global_select_local_file_load_btn" class="btn btn-sm btn-outline-success">Load</button>
|
||||
<button type="button" id='select_local_file_modal_confirm_btn' class="btn btn-success" data-dismiss="modal">선택
|
||||
</div>
|
||||
</div>
|
||||
<div style="padding-left:20px; padding-top:5px;"><em>입력한 경로를 불러옵니다.</em></div>
|
||||
</div>
|
||||
</div>
|
||||
<input type="hidden" id="select_local_file_modal_only_dir" value="true" />
|
||||
<input type="hidden" id="select_local_file_modal_callback" value="" />
|
||||
<div class="list-group" id="select_local_file_modal_list_group">
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" id='select_local_file_modal_confirm_btn' class="btn btn-success" data-dismiss="modal">선택
|
||||
</button>
|
||||
<button type="button" id='select_local_file_modal_cancel_btn' class="btn btn-default" data-dismiss="modal">닫기
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!--command modal-->
|
||||
{{ macros.m_modal_start('command_modal', '', 'modal-lg') }}
|
||||
<div>
|
||||
<textarea id="command_modal_textarea" class="col-md-12" rows="30" disabled style="background-color:#ffffff;visibility:visible"></textarea>
|
||||
</div>
|
||||
<form id='command_modal_form' name='command_form'>
|
||||
<div class="form-inline input-group">
|
||||
<input id="command_modal_input" name="command_modal_input" type="text" class="form-control form-control-sm" placeholder="">
|
||||
<button id="command_modal_input_btn" class="btn btn-sm btn-outline-success">입력</button>
|
||||
</div>
|
||||
</form>
|
||||
{{ macros.m_modal_end() }}
|
||||
<!--command modal end-->
|
||||
<!-- Modal end -->
|
||||
{% endmacro %}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
{% macro menu() %}
|
||||
<div id="menu_div">
|
||||
<nav class="navbar navbar-expand-md navbar-dark fixed-top bg-dark flex-md-nowrap shadow" role="navigation">
|
||||
<a class="navbar-brand" href="/">{{get_web_title()}}</a>
|
||||
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExample01" aria-controls="navbarsExample01" aria-expanded="false" aria-label="Toggle navigation">
|
||||
<span class="navbar-toggler-icon"></span>
|
||||
</button>
|
||||
{% for i in range(1) %}
|
||||
<div class="collapse navbar-collapse w-100" id="navbarsExample01">
|
||||
{% if i == 0 %}
|
||||
<ul class="nav navbar-nav mr-auto">
|
||||
{% else %}
|
||||
<ul class="nav navbar-nav ml-auto">
|
||||
{% endif %}
|
||||
|
||||
{% set menu = request.full_path | get_menu %}
|
||||
{% set menu_map = get_menu_map() %}
|
||||
{% for category in menu_map %}
|
||||
{% if 'uri' in category and category['uri'].startswith('http') %}
|
||||
<li class="nav-item"> <a class="nav-link" href="{{ category['uri']}}" target="_blank">{{category['name']}}</a></li>
|
||||
{% elif 'uri' in category and category['uri'].startswith('http') == False %}
|
||||
<li class="nav-item"> <a class="nav-link" href="{{ category['uri']}}">{{category['name']}}</a></li>
|
||||
{% else %}
|
||||
<!--{{ category }}-->
|
||||
<li class="nav-item dropdown">
|
||||
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">{{category['name']}}</a>
|
||||
<ul class="dropdown-menu">
|
||||
{% for category_child in category['list'] %}
|
||||
{% if category_child['uri'] == 'setting' %}
|
||||
<li><a class="dropdown-item" href="#" style="font-size: .850rem; font-weight:bold">{{category_child['name']}}</a>
|
||||
<ul class="submenu dropdown-menu">
|
||||
{% for item in category_child['list'] %}
|
||||
<li><a class="dropdown-item" href="/{{item['uri']}}" style="font-size: .850rem; font-weight:bold">{{item['name']}}</a></li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</li>
|
||||
{% elif category_child['uri'] == '-' %}
|
||||
<div class="dropdown-divider"></div>
|
||||
{% elif 'uri' in category_child and category_child['uri'].startswith('http') %}
|
||||
{% if 'target' not in category_child or category_child['target'] == '_blank' %}
|
||||
<a class="dropdown-item" href="{{ category_child['uri'] }}" target="_blank" style="font-size: .850rem; font-weight:bold">{{ category_child['name'] }}</a>
|
||||
{% else %}
|
||||
<a class="dropdown-item" href="{{ category_child['uri'] }}" style="font-size: .850rem; font-weight:bold">{{ category_child['name'] }}</a>
|
||||
{% endif %}
|
||||
{% elif 'uri' in category_child and category_child['uri'].startswith('javascript') %}
|
||||
<a class="dropdown-item" href="{{ category_child['uri'] }}" style="font-size: .850rem; font-weight:bold">{{ category_child['name'] }}</a>
|
||||
{% else %}
|
||||
{% if category_child['uri'] == menu[0] %}
|
||||
<a class="dropdown-item active" href="/{{ category_child['uri'] }}" style="font-size: .850rem; font-weight:bold">{{ category_child['name'] }}</a>
|
||||
{% else %}
|
||||
{% if 'target' in category_child %}
|
||||
<a class="dropdown-item" href="/{{ category_child['uri'] }}" style="font-size: .850rem; font-weight:bold" target="{{category_child['target']}}">{{ category_child['name'] }}</a>
|
||||
{% else %}
|
||||
<a class="dropdown-item" href="/{{ category_child['uri'] }}" style="font-size: .850rem; font-weight:bold">{{ category_child['name'] }}</a>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</ul>
|
||||
</li>
|
||||
{% endif %}
|
||||
{% endfor %}<!---->
|
||||
</ul>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</nav>
|
||||
</div>
|
||||
{% endmacro %}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
{% macro menu_module() %}
|
||||
<div id='menu_module_div'>
|
||||
{% set current_menu = request.full_path | get_menu %}
|
||||
<!--{{ current_menu }}-->
|
||||
{% set menu_map = get_menu_map() %}
|
||||
{% for category in menu_map %}
|
||||
{% for category_child in category['list'] %}
|
||||
{% if current_menu[0] == category_child['uri'] %}
|
||||
<ul class="nav nav-pills bg-light shadow text-dark" >
|
||||
<li class="nav-item"><span class="nav-link">{{category['name']}} ➤ {{category_child['name']}}</span></li>
|
||||
{% for module in category_child['list'] %}
|
||||
<!--{{ module }}-->
|
||||
{% if current_menu[0] == 'setting' %}
|
||||
{% if current_menu[1] == module['uri'] or (current_menu[2] is not none and current_menu[1] + "/" + current_menu[2] == module['uri']) %}
|
||||
<li class="nav-item"><a class="nav-link active" href="/{{module['uri']}}">{{module['name']}}</a></li>
|
||||
{% else %}
|
||||
<li class="nav-item"><a class="nav-link" href="/{{module['uri']}}">{{module['name']}}</a></li>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
{% if current_menu[1] == module['uri'] or (current_menu[2] is not none and current_menu[1] + "/" + current_menu[2] == module['uri']) %}
|
||||
{% if 'target' in module and module['target'] == '_blank' %}
|
||||
<li class="nav-item"><a class="nav-link active" href="/{{current_menu[0]}}/{{module['uri']}}" target="_blank">{{module['name']}}</a></li>
|
||||
{% else %}
|
||||
<li class="nav-item"><a class="nav-link active" href="/{{current_menu[0]}}/{{module['uri']}}">{{module['name']}}</a></li>
|
||||
{% endif %}
|
||||
{% else %}
|
||||
{% if 'target' in module and module['target'] == '_blank' %}
|
||||
<li class="nav-item"><a class="nav-link" href="/{{current_menu[0]}}/{{module['uri']}}" target="_blank">{{module['name']}}</a></li>
|
||||
{% else %}
|
||||
<li class="nav-item"><a class="nav-link" href="/{{current_menu[0]}}/{{module['uri']}}">{{module['name']}}</a></li>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% break %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endmacro %}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
{% macro menu_page() %}
|
||||
<div id='menu_page_div'>
|
||||
{% set current_menu = request.full_path | get_menu %}
|
||||
{% set menu_map = get_menu_map() %}
|
||||
{% for category in menu_map %}
|
||||
{% for plugin in category['list'] %}
|
||||
{% if current_menu[0] == plugin['uri'] and 'list' in plugin %}
|
||||
{% for module in plugin['list'] %}
|
||||
{% if module['uri'] == current_menu[1] and 'list' in module%}
|
||||
<!--{{ module }}-->
|
||||
<ul class="nav nav-pills bg-light shadow text-dark">
|
||||
{% for page in module['list'] %}
|
||||
{% if current_menu[2] == page['uri'] %}
|
||||
<li class="nav-item"><a class="nav-link active" href="/{{ current_menu[0] }}/{{ current_menu[1] }}/{{ page['uri'] }}">{{page['name']}}</a></li>
|
||||
{% else %}
|
||||
<li class="nav-item"><a class="nav-link" href="/{{ current_menu[0] }}/{{ current_menu[1] }}/{{ page['uri'] }}">{{page['name']}}</a></li>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
</ul>
|
||||
<div class="d-inline-block"></div>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endmacro %}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
{% extends "base.html" %}
|
||||
{% block content %}
|
||||
|
||||
{% filter markdown %}
|
||||
{{ data }}
|
||||
{% endfilter %}
|
||||
|
||||
|
||||
<style type="text/css">
|
||||
img{
|
||||
|
||||
display: block;
|
||||
max-width: 100%;
|
||||
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
</style>
|
||||
|
||||
<div id="md_div" data-url="{{ arg }}"></div>
|
||||
<div id="content_div" data-url="{{ arg }}"></div>
|
||||
|
||||
|
||||
<script type="text/javascript">
|
||||
$(document).ready(function(){
|
||||
//$('#main_container').attr('class', 'container-fluid');
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{% extends "base.html" %}
|
||||
{% block content %}
|
||||
<div class="">
|
||||
<h3>{{title}}</h3>
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,65 @@
|
||||
<title>{{data['play_title']}}</title>
|
||||
<script src="https://vjs.zencdn.net/7.11.4/video.min.js"></script>
|
||||
<link href="https://vjs.zencdn.net/7.11.4/video-js.css" rel="stylesheet" />
|
||||
|
||||
<body bgcolor='black'>
|
||||
<video id=player width=960 height=540 class="video-js vjs-default-skin vjs-16-9" autoplay controls>
|
||||
<source
|
||||
src="{{data['play_source_src']}}"
|
||||
type="{{data['play_source_type']}}" />
|
||||
</video>
|
||||
</body>
|
||||
|
||||
<script>
|
||||
var subtitle_src = "{{data['play_subtitle_src']}}";
|
||||
let options = {
|
||||
html5: {
|
||||
nativeTextTracks: false
|
||||
},
|
||||
playbackRates: [.5, .75, 1, 1.5, 2],
|
||||
controls: true,
|
||||
preload: "auto",
|
||||
controlBar: {
|
||||
playToggle: false,
|
||||
pictureInPictureToggle: false,
|
||||
remainingTimeDisplay: true,
|
||||
qualitySelector: true,
|
||||
}
|
||||
};
|
||||
let player = videojs('player', options);
|
||||
|
||||
player.ready(function(){
|
||||
// set subtitle track
|
||||
console.log(subtitle_src);
|
||||
if (subtitle_src != "") {
|
||||
var suburl = subtitle_src.replace(/&/g, '&');
|
||||
console.log(suburl);
|
||||
let captionOption = {
|
||||
kind: 'captions',
|
||||
srclang: 'ko',
|
||||
label: 'Korean',
|
||||
src: suburl,
|
||||
mode: 'showing'
|
||||
};
|
||||
player.addRemoteTextTrack(captionOption);
|
||||
|
||||
var settings = this.textTrackSettings;
|
||||
settings.setValues({
|
||||
"backgroundColor": "#000",
|
||||
"backgroundOpacity": "0",
|
||||
"edgeStyle": "uniform",
|
||||
});
|
||||
settings.updateDisplay();
|
||||
}
|
||||
else {
|
||||
var tracks = player.textTracks();
|
||||
console.log(tracks.length);
|
||||
for (var i = 0; i < tracks.length; i++) {
|
||||
var track = tracks[i];
|
||||
console.log(track);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
player.play();
|
||||
</script>
|
||||
@@ -0,0 +1,104 @@
|
||||
|
||||
import os
|
||||
import traceback
|
||||
|
||||
from framework import F
|
||||
|
||||
|
||||
class Util(object):
|
||||
|
||||
@staticmethod
|
||||
def db_to_dict(db_list):
|
||||
ret = []
|
||||
for item in db_list:
|
||||
ret.append(item.as_dict())
|
||||
return ret
|
||||
|
||||
@staticmethod
|
||||
def get_paging_info(count, current_page, page_size):
|
||||
try:
|
||||
paging = {}
|
||||
paging['prev_page'] = True
|
||||
paging['next_page'] = True
|
||||
if current_page <= 10:
|
||||
paging['prev_page'] = False
|
||||
|
||||
paging['total_page'] = int(count / page_size) + 1
|
||||
if count % page_size == 0:
|
||||
paging['total_page'] -= 1
|
||||
paging['start_page'] = int((current_page-1)/10) * 10 + 1
|
||||
paging['last_page'] = paging['total_page'] if paging['start_page'] + 9 > paging['total_page'] else paging['start_page'] + 9
|
||||
if paging['last_page'] == paging['total_page']:
|
||||
paging['next_page'] = False
|
||||
paging['current_page'] = current_page
|
||||
paging['count'] = count
|
||||
F.logger.debug('paging : c:%s %s %s %s %s %s', count, paging['total_page'], paging['prev_page'], paging['next_page'] , paging['start_page'], paging['last_page'])
|
||||
return paging
|
||||
except Exception as exception:
|
||||
F.logger.debug('Exception:%s', exception)
|
||||
F.logger.debug(traceback.format_exc())
|
||||
|
||||
|
||||
# 토렌트 인포에서 최대 크기 파일과 폴더명을 리턴한다
|
||||
@staticmethod
|
||||
def get_max_size_fileinfo(torrent_info):
|
||||
try:
|
||||
ret = {}
|
||||
max_size = -1
|
||||
max_filename = None
|
||||
for t in torrent_info['files']:
|
||||
if t['size'] > max_size:
|
||||
max_size = t['size']
|
||||
max_filename = str(t['path'])
|
||||
t = max_filename.split('/')
|
||||
ret['filename'] = t[-1]
|
||||
if len(t) == 1:
|
||||
ret['dirname'] = ''
|
||||
elif len(t) == 2:
|
||||
ret['dirname'] = t[0]
|
||||
else:
|
||||
ret['dirname'] = max_filename.replace('/%s' % ret['filename'], '')
|
||||
ret['max_size'] = max_size
|
||||
return ret
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
# 압축할 폴더 경로를 인자로 받음. 폴더명.zip 생성
|
||||
@staticmethod
|
||||
def makezip(zip_path, zip_extension='zip'):
|
||||
import zipfile
|
||||
try:
|
||||
if os.path.isdir(zip_path):
|
||||
zipfilename = os.path.join(os.path.dirname(zip_path), '%s.%s' % (os.path.basename(zip_path), zip_extension))
|
||||
fantasy_zip = zipfile.ZipFile(zipfilename, 'w')
|
||||
for f in os.listdir(zip_path):
|
||||
#if f.endswith('.jpg') or f.endswith('.png'):
|
||||
src = os.path.join(zip_path, f)
|
||||
fantasy_zip.write(src, os.path.basename(src), compress_type = zipfile.ZIP_DEFLATED)
|
||||
fantasy_zip.close()
|
||||
import shutil
|
||||
shutil.rmtree(zip_path)
|
||||
return True
|
||||
except Exception as exception:
|
||||
F.logger.error('Exception:%s', exception)
|
||||
F.logger.error(traceback.format_exc())
|
||||
return False
|
||||
|
||||
|
||||
|
||||
@staticmethod
|
||||
def make_apikey(url):
|
||||
from framework import SystemModelSetting
|
||||
url = url.format(ddns=SystemModelSetting.get('ddns'))
|
||||
if SystemModelSetting.get_bool('auth_use_apikey'):
|
||||
if url.find('?') == -1:
|
||||
url += '?'
|
||||
else:
|
||||
url += '&'
|
||||
url += 'apikey=%s' % SystemModelSetting.get('auth_apikey')
|
||||
return url
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
VERSION="4.0.47"
|
||||
@@ -0,0 +1,17 @@
|
||||
# 순서 바꾸지 말 것
|
||||
import os, sys, traceback, re, threading, time, queue
|
||||
from datetime import datetime, timedelta
|
||||
from flask import Blueprint, render_template, jsonify, redirect, request
|
||||
from sqlalchemy import desc, or_
|
||||
|
||||
from framework import logger
|
||||
from .model_setting import get_model_setting
|
||||
from .logic import Logic
|
||||
from .route import default_route, default_route_socketio_module, default_route_socketio_page, default_route_single_module
|
||||
from .logic_module_base import PluginModuleBase, PluginPageBase
|
||||
#from .ffmpeg_queue import FfmpegQueueEntity, FfmpegQueue
|
||||
from .model_base import ModelBase
|
||||
from .create_plugin import create_plugin_instance
|
||||
|
||||
from framework import *
|
||||
from tool import *
|
||||
@@ -0,0 +1,292 @@
|
||||
import abc
|
||||
import os
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class FfmpegQueueEntity(abc.ABCMeta('ABC', (object,), {'__slots__': ()})):
|
||||
|
||||
def __init__(self, P, module_logic, info):
|
||||
self.P = P
|
||||
self.module_logic = module_logic
|
||||
self.entity_id = -1 #FfmpegQueueEntity.static_index
|
||||
self.info = info
|
||||
self.url = None
|
||||
self.ffmpeg_status = -1
|
||||
self.ffmpeg_status_kor = u'대기중'
|
||||
self.ffmpeg_percent = 0
|
||||
self.ffmpeg_arg = None
|
||||
self.cancel = False
|
||||
self.created_time = datetime.now().strftime('%m-%d %H:%M:%S')
|
||||
self.savepath = None
|
||||
self.filename = None
|
||||
self.filepath = None
|
||||
self.quality = None
|
||||
self.headers = None
|
||||
#FfmpegQueueEntity.static_index += 1
|
||||
#FfmpegQueueEntity.entity_list.append(self)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def get_video_url(self):
|
||||
return self.url
|
||||
|
||||
def get_video_filepath(self):
|
||||
return self.filepath
|
||||
|
||||
@abc.abstractmethod
|
||||
def refresh_status(self):
|
||||
pass
|
||||
|
||||
@abc.abstractmethod
|
||||
def info_dict(self, tmp):
|
||||
pass
|
||||
|
||||
def donwload_completed(self):
|
||||
pass
|
||||
|
||||
def as_dict(self):
|
||||
tmp = {}
|
||||
tmp['entity_id'] = self.entity_id
|
||||
tmp['url'] = self.url
|
||||
tmp['ffmpeg_status'] = self.ffmpeg_status
|
||||
tmp['ffmpeg_status_kor'] = self.ffmpeg_status_kor
|
||||
tmp['ffmpeg_percent'] = self.ffmpeg_percent
|
||||
tmp['ffmpeg_arg'] = self.ffmpeg_arg
|
||||
tmp['cancel'] = self.cancel
|
||||
tmp['created_time'] = self.created_time#.strftime('%m-%d %H:%M:%S')
|
||||
tmp['savepath'] = self.savepath
|
||||
tmp['filename'] = self.filename
|
||||
tmp['filepath'] = self.filepath
|
||||
tmp['quality'] = self.quality
|
||||
#tmp['current_speed'] = self.ffmpeg_arg['current_speed'] if self.ffmpeg_arg is not None else ''
|
||||
tmp = self.info_dict(tmp)
|
||||
return tmp
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class FfmpegQueue(object):
|
||||
|
||||
def __init__(self, P, max_ffmpeg_count):
|
||||
self.P = P
|
||||
self.static_index = 1
|
||||
self.entity_list = []
|
||||
self.current_ffmpeg_count = 0
|
||||
self.download_queue = None
|
||||
self.download_thread = None
|
||||
self.max_ffmpeg_count = max_ffmpeg_count
|
||||
if self.max_ffmpeg_count is None or self.max_ffmpeg_count == '':
|
||||
self.max_ffmpeg_count = 1
|
||||
|
||||
def queue_start(self):
|
||||
try:
|
||||
if self.download_queue is None:
|
||||
self.download_queue = queue.Queue()
|
||||
if self.download_thread is None:
|
||||
self.download_thread = threading.Thread(target=self.download_thread_function, args=())
|
||||
self.download_thread.daemon = True
|
||||
self.download_thread.start()
|
||||
except Exception as exception:
|
||||
self.P.logger.error('Exception:%s', exception)
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def download_thread_function(self):
|
||||
while True:
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
if self.current_ffmpeg_count < self.max_ffmpeg_count:
|
||||
break
|
||||
time.sleep(5)
|
||||
except Exception as exception:
|
||||
self.P.logger.error('Exception:%s', exception)
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
self.P.logger.error('current_ffmpeg_count : %s', self.current_ffmpeg_count)
|
||||
self.P.logger.error('max_ffmpeg_count : %s', self.max_ffmpeg_count)
|
||||
break
|
||||
entity = self.download_queue.get()
|
||||
if entity.cancel:
|
||||
continue
|
||||
|
||||
#from .logic_ani24 import LogicAni24
|
||||
#entity.url = LogicAni24.get_video_url(entity.info['code'])
|
||||
video_url = entity.get_video_url()
|
||||
if video_url is None:
|
||||
entity.ffmpeg_status_kor = 'URL실패'
|
||||
entity.refresh_status()
|
||||
#plugin.socketio_list_refresh()
|
||||
continue
|
||||
|
||||
import ffmpeg
|
||||
|
||||
#max_pf_count = 0
|
||||
#save_path = ModelSetting.get('download_path')
|
||||
#if ModelSetting.get('auto_make_folder') == 'True':
|
||||
# program_path = os.path.join(save_path, entity.info['filename'].split('.')[0])
|
||||
# save_path = program_path
|
||||
#try:
|
||||
# if not os.path.exists(save_path):
|
||||
# os.makedirs(save_path)
|
||||
#except:
|
||||
# logger.debug('program path make fail!!')
|
||||
# 파일 존재여부 체크
|
||||
filepath = entity.get_video_filepath()
|
||||
if os.path.exists(filepath):
|
||||
entity.ffmpeg_status_kor = '파일 있음'
|
||||
entity.ffmpeg_percent = 100
|
||||
entity.refresh_status()
|
||||
#plugin.socketio_list_refresh()
|
||||
continue
|
||||
dirname = os.path.dirname(filepath)
|
||||
if not os.path.exists(dirname):
|
||||
os.makedirs(dirname)
|
||||
f = ffmpeg.Ffmpeg(video_url, os.path.basename(filepath), plugin_id=entity.entity_id, listener=self.ffmpeg_listener, call_plugin=self.P.package_name, save_path=dirname, headers=entity.headers)
|
||||
f.start()
|
||||
self.current_ffmpeg_count += 1
|
||||
self.download_queue.task_done()
|
||||
except Exception as exception:
|
||||
self.P.logger.error('Exception:%s', exception)
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
def ffmpeg_listener(self, **arg):
|
||||
import ffmpeg
|
||||
entity = self.get_entity_by_entity_id(arg['plugin_id'])
|
||||
if entity is None:
|
||||
return
|
||||
if arg['type'] == 'status_change':
|
||||
if arg['status'] == ffmpeg.Status.DOWNLOADING:
|
||||
pass
|
||||
elif arg['status'] == ffmpeg.Status.COMPLETED:
|
||||
entity.donwload_completed()
|
||||
elif arg['status'] == ffmpeg.Status.READY:
|
||||
pass
|
||||
elif arg['type'] == 'last':
|
||||
self.current_ffmpeg_count += -1
|
||||
elif arg['type'] == 'log':
|
||||
pass
|
||||
elif arg['type'] == 'normal':
|
||||
pass
|
||||
|
||||
entity.ffmpeg_arg = arg
|
||||
entity.ffmpeg_status = int(arg['status'])
|
||||
entity.ffmpeg_status_kor = str(arg['status'])
|
||||
entity.ffmpeg_percent = arg['data']['percent']
|
||||
entity.ffmpeg_arg['status'] = str(arg['status'])
|
||||
#self.P.logger.debug(arg)
|
||||
#import plugin
|
||||
#arg['status'] = str(arg['status'])
|
||||
#plugin.socketio_callback('status', arg)
|
||||
entity.refresh_status()
|
||||
|
||||
|
||||
#FfmpegQueueEntity.static_index += 1
|
||||
#FfmpegQueueEntity.entity_list.append(self)
|
||||
|
||||
|
||||
def add_queue(self, entity):
|
||||
try:
|
||||
#entity = QueueEntity.create(info)
|
||||
#if entity is not None:
|
||||
# LogicQueue.download_queue.put(entity)
|
||||
# return True
|
||||
entity.entity_id = self.static_index
|
||||
self.static_index += 1
|
||||
self.entity_list.append(entity)
|
||||
self.download_queue.put(entity)
|
||||
return True
|
||||
except Exception as exception:
|
||||
self.P.logger.error('Exception:%s', exception)
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
return False
|
||||
|
||||
|
||||
def set_max_ffmpeg_count(self, max_ffmpeg_count):
|
||||
self.max_ffmpeg_count = max_ffmpeg_count
|
||||
|
||||
def get_max_ffmpeg_count(self):
|
||||
return self.max_ffmpeg_count
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def command(self, cmd, entity_id):
|
||||
self.P.logger.debug('command :%s %s', cmd, entity_id)
|
||||
ret = {}
|
||||
try:
|
||||
if cmd == 'cancel':
|
||||
self.P.logger.debug('command :%s %s', cmd, entity_id)
|
||||
entity = self.get_entity_by_entity_id(entity_id)
|
||||
if entity is not None:
|
||||
if entity.ffmpeg_status == -1:
|
||||
entity.cancel = True
|
||||
entity.ffmpeg_status_kor = "취소"
|
||||
#entity.refresh_status()
|
||||
ret['ret'] = 'refresh'
|
||||
elif entity.ffmpeg_status != 5:
|
||||
ret['ret'] = 'notify'
|
||||
ret['log'] = '다운로드중 상태가 아닙니다.'
|
||||
else:
|
||||
idx = entity.ffmpeg_arg['data']['idx']
|
||||
import ffmpeg
|
||||
ffmpeg.Ffmpeg.stop_by_idx(idx)
|
||||
entity.refresh_status()
|
||||
ret['ret'] = 'refresh'
|
||||
elif cmd == 'reset':
|
||||
if self.download_queue is not None:
|
||||
with self.download_queue.mutex:
|
||||
self.download_queue.queue.clear()
|
||||
for _ in self.entity_list:
|
||||
if _.ffmpeg_status == 5:
|
||||
import ffmpeg
|
||||
idx = _.ffmpeg_arg['data']['idx']
|
||||
ffmpeg.Ffmpeg.stop_by_idx(idx)
|
||||
self.entity_list = []
|
||||
ret['ret'] = 'refresh'
|
||||
elif cmd == 'delete_completed':
|
||||
new_list = []
|
||||
for _ in self.entity_list:
|
||||
if _.ffmpeg_status_kor in [u'파일 있음', u'취소', u'사용자중지']:
|
||||
continue
|
||||
if _.ffmpeg_status != 7:
|
||||
new_list.append(_)
|
||||
self.entity_list = new_list
|
||||
ret['ret'] = 'refresh'
|
||||
elif cmd == 'remove':
|
||||
new_list = []
|
||||
for _ in self.entity_list:
|
||||
if _.entity_id == entity_id:
|
||||
continue
|
||||
new_list.append(_)
|
||||
self.entity_list = new_list
|
||||
ret['ret'] = 'refresh'
|
||||
return ret
|
||||
except Exception as exception:
|
||||
self.P.logger.error('Exception:%s', exception)
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def get_entity_by_entity_id(self, entity_id):
|
||||
for _ in self.entity_list:
|
||||
if _.entity_id == entity_id:
|
||||
return _
|
||||
return None
|
||||
|
||||
|
||||
def get_entity_list(self):
|
||||
ret = []
|
||||
for x in self.entity_list:
|
||||
tmp = x.as_dict()
|
||||
ret.append(tmp)
|
||||
return ret
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
import os, sys, traceback, re, threading, time
|
||||
from datetime import datetime, timedelta
|
||||
from flask import Blueprint, render_template, jsonify, redirect, request
|
||||
from framework import frame, F, login_required, check_api, Job, SystemModelSetting
|
||||
from plugin import PluginModuleBase, get_model_setting, Logic, default_route, create_plugin_instance
|
||||
"""
|
||||
@@ -0,0 +1,93 @@
|
||||
import os
|
||||
import traceback
|
||||
|
||||
from flask import Blueprint
|
||||
from framework import F
|
||||
from support import SupportYaml
|
||||
|
||||
from . import (Logic, default_route, default_route_single_module,
|
||||
get_model_setting)
|
||||
|
||||
|
||||
class PluginBase(object):
|
||||
package_name = None
|
||||
logger = None
|
||||
blueprint = None
|
||||
menu = None
|
||||
plugin_info = None
|
||||
ModelSetting = None
|
||||
logic = None
|
||||
module_list = None
|
||||
home_module = None
|
||||
vars = []
|
||||
|
||||
def __init__(self, setting):
|
||||
try:
|
||||
is_system = ('system' == os.path.basename(os.path.dirname(setting['filepath'])))
|
||||
self.status = ""
|
||||
self.setting = setting
|
||||
|
||||
info_filepath = os.path.join(os.path.dirname(setting['filepath']), 'info.yaml')
|
||||
if os.path.exists(info_filepath) == False and is_system == False:
|
||||
return
|
||||
if is_system:
|
||||
self.package_name = 'system'
|
||||
else:
|
||||
self.plugin_info = SupportYaml.read_yaml(info_filepath)
|
||||
self.package_name = self.plugin_info['package_name']
|
||||
|
||||
self.logger = F.get_logger(self.package_name)
|
||||
self.blueprint = Blueprint(self.package_name, self.package_name, url_prefix=f'/{self.package_name}', template_folder=os.path.join(os.path.dirname(setting['filepath']), 'templates'), static_folder=os.path.join(os.path.dirname(setting['filepath']), 'static'))
|
||||
self.menu = setting['menu']
|
||||
self.setting_menu = setting.get('setting_menu', None)
|
||||
|
||||
self.ModelSetting = None
|
||||
if setting.get('use_db', True):
|
||||
db_path = os.path.join(F.config['path_data'], 'db', f'{self.package_name}.db')
|
||||
F.app.config['SQLALCHEMY_BINDS'][self.package_name] = f"sqlite:///{db_path}?check_same_thread=False"
|
||||
if setting.get('use_default_setting', True):
|
||||
self.ModelSetting = get_model_setting(self.package_name, self.logger)
|
||||
|
||||
self.module_list = []
|
||||
self.home_module = setting.get('home_module')
|
||||
self.status = "init_success"
|
||||
self.config = {}
|
||||
except Exception as e:
|
||||
self.logger.error(f'Exception:{str(e)}')
|
||||
self.logger.error(traceback.format_exc())
|
||||
self.status = 'init_fail'
|
||||
|
||||
def set_module_list(self, mod_list):
|
||||
try:
|
||||
for mod in mod_list:
|
||||
mod_ins = mod(self)
|
||||
self.module_list.append(mod_ins)
|
||||
|
||||
except Exception as e:
|
||||
F.logger.error(f'[{self.package_name}] Exception:{str(e)}')
|
||||
F.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
self.logic = Logic(self)
|
||||
route_mode = self.setting.get('default_route', 'normal')
|
||||
if route_mode == 'normal':
|
||||
default_route(self)
|
||||
elif route_mode == 'single':
|
||||
default_route_single_module(self)
|
||||
|
||||
|
||||
def plugin_load(self):
|
||||
self.logic.plugin_load()
|
||||
|
||||
def plugin_unload(self):
|
||||
self.logic.plugin_unload()
|
||||
|
||||
def get_first_manual_path(self):
|
||||
for __ in self.menu['list']:
|
||||
if __['uri'] == 'manual' and len(__['list']) > 0:
|
||||
return __['list'][0]['uri']
|
||||
|
||||
|
||||
def create_plugin_instance(config):
|
||||
ins = PluginBase(config)
|
||||
return ins
|
||||
@@ -0,0 +1,314 @@
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from framework import F, Job
|
||||
|
||||
#########################################################
|
||||
|
||||
|
||||
class Logic(object):
|
||||
db_default = {
|
||||
'recent_menu_plugin' : '',
|
||||
}
|
||||
|
||||
def __init__(self, P):
|
||||
self.P = P
|
||||
|
||||
def plugin_load(self):
|
||||
self.P.logger.debug('%s plugin_load', self.P.package_name)
|
||||
self.db_init()
|
||||
for module in self.P.module_list:
|
||||
module.migration()
|
||||
if module.page_list is not None:
|
||||
for page_instance in module.page_list:
|
||||
page_instance.migration()
|
||||
|
||||
for module in self.P.module_list:
|
||||
module.plugin_load()
|
||||
if module.page_list is not None:
|
||||
for page_instance in module.page_list:
|
||||
page_instance.plugin_load()
|
||||
if self.P.ModelSetting is not None:
|
||||
for module in self.P.module_list:
|
||||
key = f'{module.name}_auto_start'
|
||||
if self.P.ModelSetting.has_key(key) and self.P.ModelSetting.get_bool(key):
|
||||
self.scheduler_start(module.name)
|
||||
if module.page_list is not None:
|
||||
for page_instance in module.page_list:
|
||||
key = f'{module.name}_{page_instance.name}_auto_start'
|
||||
if self.P.ModelSetting.has_key(key) and self.P.ModelSetting.get_bool(key):
|
||||
self.scheduler_start_sub(module.name, page_instance.name)
|
||||
|
||||
|
||||
def db_init(self):
|
||||
try:
|
||||
if self.P.ModelSetting is None:
|
||||
return
|
||||
|
||||
for key, value in Logic.db_default.items():
|
||||
if self.P.ModelSetting.get(key) == None:
|
||||
self.P.ModelSetting.set(key, value)
|
||||
|
||||
for module in self.P.module_list:
|
||||
if module.page_list is not None:
|
||||
for page_instance in module.page_list:
|
||||
if page_instance.db_default is not None:
|
||||
for key, value in page_instance.db_default.items():
|
||||
if self.P.ModelSetting.get(key) == None:
|
||||
self.P.ModelSetting.set(key, value)
|
||||
if module.db_default is not None:
|
||||
for key, value in module.db_default.items():
|
||||
if self.P.ModelSetting.get(key) == None:
|
||||
self.P.ModelSetting.set(key, value)
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def plugin_unload(self):
|
||||
try:
|
||||
self.P.logger.debug('%s plugin_unload', self.P.package_name)
|
||||
for module in self.P.module_list:
|
||||
try:
|
||||
module.plugin_unload()
|
||||
if module.page_list is not None:
|
||||
for page_instance in module.page_list:
|
||||
page_instance.plugin_unload()
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
self.P.logger.debug(f'[{self.P.package_name}] plugin_unload end')
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def scheduler_start(self, module_name):
|
||||
try:
|
||||
job_id = '%s_%s' % (self.P.package_name, module_name)
|
||||
module = self.get_module(module_name)
|
||||
job = Job(self.P.package_name, job_id, module.get_scheduler_interval(), self.scheduler_function, module.get_scheduler_desc(), args=module_name)
|
||||
F.scheduler.add_job_instance(job)
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def scheduler_stop(self, module_name):
|
||||
try:
|
||||
job_id = '%s_%s' % (self.P.package_name, module_name)
|
||||
F.scheduler.remove_job(job_id)
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def scheduler_function(self, module_name):
|
||||
try:
|
||||
module = self.get_module(module_name)
|
||||
module.scheduler_function()
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
def reset_db(self, module_name):
|
||||
try:
|
||||
module = self.get_module(module_name)
|
||||
return module.reset_db()
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def one_execute(self, module_name):
|
||||
self.P.logger.debug('one_execute :%s', module_name)
|
||||
try:
|
||||
job_id = '%s_%s' % (self.P.package_name, module_name)
|
||||
if F.scheduler.is_include(job_id):
|
||||
if F.scheduler.is_running(job_id):
|
||||
ret = 'is_running'
|
||||
else:
|
||||
F.scheduler.execute_job(job_id)
|
||||
ret = 'scheduler'
|
||||
else:
|
||||
def func():
|
||||
time.sleep(2)
|
||||
self.scheduler_function(module_name)
|
||||
threading.Thread(target=func, args=()).start()
|
||||
ret = 'thread'
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
ret = 'fail'
|
||||
return ret
|
||||
|
||||
def immediately_execute(self, module_name):
|
||||
self.P.logger.debug('immediately_execute :%s', module_name)
|
||||
try:
|
||||
def func():
|
||||
time.sleep(1)
|
||||
self.scheduler_function(module_name)
|
||||
threading.Thread(target=func, args=()).start()
|
||||
ret = {'ret':'success', 'msg':'실행합니다.'}
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
ret = {'ret' : 'danger', 'msg':str(e)}
|
||||
return ret
|
||||
|
||||
def get_module(self, sub):
|
||||
try:
|
||||
for module in self.P.module_list:
|
||||
if module.name == sub:
|
||||
return module
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
def process_telegram_data(self, data, target=None):
|
||||
try:
|
||||
for module in self.P.module_list:
|
||||
if target is None or target.startswith(module.name):
|
||||
module.process_telegram_data(data, target=target)
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
#######################################################
|
||||
# 플러그인 - 모듈 - 페이지 구조하에서 서브 관련 함수
|
||||
|
||||
def scheduler_start_sub(self, module_name, page_name):
|
||||
try:
|
||||
#self.P.logger.warning('scheduler_start_sub')
|
||||
job_id = f'{self.P.package_name}_{module_name}_{page_name}'
|
||||
ins_module = self.get_module(module_name)
|
||||
ins_page = ins_module.get_page(page_name)
|
||||
job = Job(self.P.package_name, job_id, ins_page.get_scheduler_interval(), ins_page.scheduler_function, ins_page.get_scheduler_desc(), args=None)
|
||||
F.scheduler.add_job_instance(job)
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
def scheduler_stop_sub(self, module_name, page_name):
|
||||
try:
|
||||
job_id = f'{self.P.package_name}_{module_name}_{page_name}'
|
||||
F.scheduler.remove_job(job_id)
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
def scheduler_function_sub(self, module_name, page_name):
|
||||
try:
|
||||
ins_module = self.get_module(module_name)
|
||||
ins_sub = ins_module.get_page(page_name)
|
||||
ins_sub.scheduler_function()
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
def one_execute_sub(self, module_name, page_name):
|
||||
try:
|
||||
job_id = f'{self.P.package_name}_{module_name}_{page_name}'
|
||||
if F.scheduler.is_include(job_id):
|
||||
if F.scheduler.is_running(job_id):
|
||||
ret = 'is_running'
|
||||
else:
|
||||
F.scheduler.execute_job(job_id)
|
||||
ret = 'scheduler'
|
||||
else:
|
||||
def func():
|
||||
time.sleep(2)
|
||||
self.scheduler_function_sub(module_name, page_name)
|
||||
threading.Thread(target=func, args=()).start()
|
||||
ret = 'thread'
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
ret = 'fail'
|
||||
return ret
|
||||
|
||||
def immediately_execute_sub(self, module_name, page_name):
|
||||
self.P.logger.debug(f'immediately_execute : {module_name} {page_name}')
|
||||
try:
|
||||
def func():
|
||||
time.sleep(1)
|
||||
self.scheduler_function_sub(module_name, page_name)
|
||||
threading.Thread(target=func, args=()).start()
|
||||
ret = {'ret':'success', 'msg':'실행합니다.'}
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
ret = {'ret' : 'danger', 'msg':str(e)}
|
||||
return ret
|
||||
|
||||
|
||||
def arg_to_dict(self, arg):
|
||||
import urllib.parse
|
||||
|
||||
tmp = urllib.parse.unquote(arg)
|
||||
tmps = tmp.split('&')
|
||||
ret = {}
|
||||
for tmp in tmps:
|
||||
_ = tmp.split('=')
|
||||
ret[_[0]] = _[1]
|
||||
return ret
|
||||
@@ -0,0 +1,209 @@
|
||||
import traceback
|
||||
|
||||
from flask import render_template
|
||||
|
||||
|
||||
class PluginModuleBase(object):
|
||||
db_default = None
|
||||
|
||||
def __init__(self, P, first_menu=None, name=None, scheduler_desc=None):
|
||||
self.P = P
|
||||
self.scheduler_desc = scheduler_desc
|
||||
self.first_menu = first_menu
|
||||
self.name = name
|
||||
self.socketio_list = None
|
||||
self.page_list = None
|
||||
self.web_list_model = None
|
||||
|
||||
def get_module(self, module_name):
|
||||
try:
|
||||
for module in self.P.module_list:
|
||||
if module.name == module_name:
|
||||
return module
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
# set_module_list 대응
|
||||
def set_page_list(self, page_list):
|
||||
try:
|
||||
self.page_list = []
|
||||
for mod in page_list:
|
||||
mod_ins = mod(self.P, self)
|
||||
self.page_list.append(mod_ins)
|
||||
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
def get_page(self, page_name):
|
||||
try:
|
||||
for page in self.page_list:
|
||||
if page_name == page.name:
|
||||
return page
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def process_menu(self, page, req):
|
||||
if self.page_list is not None:
|
||||
page_ins = self.get_page(page)
|
||||
if page_ins != None:
|
||||
return page_ins.process_menu(req)
|
||||
return render_template('sample.html', title=f"PluginModuleBase-process_menu{self.P.package_name}/{self.name}/{page}")
|
||||
|
||||
def process_ajax(self, sub, req):
|
||||
pass
|
||||
|
||||
def process_command(self, command, arg1, arg2, arg3, req):
|
||||
pass
|
||||
|
||||
def process_api(self, sub, req):
|
||||
pass
|
||||
|
||||
def process_normal(self, sub, req):
|
||||
pass
|
||||
|
||||
def scheduler_function(self):
|
||||
pass
|
||||
|
||||
def reset_db(self):
|
||||
pass
|
||||
|
||||
def plugin_load(self):
|
||||
pass
|
||||
|
||||
def plugin_unload(self):
|
||||
pass
|
||||
|
||||
def setting_save_after(self, change_list):
|
||||
pass
|
||||
|
||||
def process_telegram_data(self, data, target=None):
|
||||
pass
|
||||
|
||||
def migration(self):
|
||||
pass
|
||||
|
||||
#################################################################
|
||||
def get_scheduler_desc(self):
|
||||
return self.scheduler_desc
|
||||
|
||||
def get_scheduler_interval(self):
|
||||
if self.P is not None and self.P.ModelSetting is not None and self.name is not None:
|
||||
return self.P.ModelSetting.get('{module_name}_interval'.format(module_name=self.name))
|
||||
|
||||
def get_first_menu(self):
|
||||
return self.first_menu
|
||||
|
||||
def get_scheduler_id(self):
|
||||
return '%s_%s' % (self.P.package_name, self.name)
|
||||
|
||||
def dump(self, data):
|
||||
if type(data) in [type({}), type([])]:
|
||||
import json
|
||||
return '\n' + json.dumps(data, indent=4, ensure_ascii=False)
|
||||
else:
|
||||
return str(data)
|
||||
|
||||
def socketio_connect(self):
|
||||
pass
|
||||
|
||||
def socketio_disconnect(self):
|
||||
pass
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class PluginPageBase(object):
|
||||
db_default = None
|
||||
|
||||
def __init__(self, P, parent, name=None, scheduler_desc=None):
|
||||
self.P = P
|
||||
self.parent = parent
|
||||
self.name = name
|
||||
self.scheduler_desc = scheduler_desc
|
||||
self.socketio_list = None
|
||||
self.web_list_model = None
|
||||
|
||||
def process_menu(self, req):
|
||||
try:
|
||||
arg = {}
|
||||
if self.P.ModelSetting != None:
|
||||
arg = self.P.ModelSetting.to_dict()
|
||||
return render_template(f'{self.P.package_name}_{self.parent.name}_{self.name}.html', arg=arg)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
return render_template('sample.html', title=f"PluginPageBase-process_menu --- {self.P.package_name}/{self.parent.name}/{self.name}")
|
||||
|
||||
|
||||
def process_ajax(self, sub, req):
|
||||
pass
|
||||
|
||||
def process_api(self, sub, req):
|
||||
pass
|
||||
|
||||
def process_normal(self, sub, req):
|
||||
pass
|
||||
|
||||
def process_command(self, command, arg1, arg2, arg3, req):
|
||||
pass
|
||||
|
||||
|
||||
|
||||
# logic
|
||||
def plugin_load(self):
|
||||
pass
|
||||
|
||||
# logic
|
||||
def plugin_unload(self):
|
||||
pass
|
||||
|
||||
def scheduler_function(self):
|
||||
pass
|
||||
|
||||
def get_scheduler_desc(self):
|
||||
return self.scheduler_desc
|
||||
|
||||
def get_scheduler_interval(self):
|
||||
if self.P is not None and self.P.ModelSetting is not None and self.parent.name is not None and self.name is not None:
|
||||
return self.P.ModelSetting.get(f'{self.parent.name}_{self.name}_interval')
|
||||
|
||||
def get_scheduler_name(self):
|
||||
return f'{self.P.package_name}_{self.parent.name}_{self.name}'
|
||||
|
||||
|
||||
# logic
|
||||
def migration(self):
|
||||
pass
|
||||
|
||||
|
||||
# route
|
||||
def setting_save_after(self, change_list):
|
||||
pass
|
||||
|
||||
def process_telegram_data(self, data, target=None):
|
||||
pass
|
||||
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import traceback
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from framework import F
|
||||
from sqlalchemy import desc, or_
|
||||
|
||||
|
||||
class ModelBase(F.db.Model):
|
||||
__abstract__ = True
|
||||
__table_args__ = {'mysql_collate': 'utf8_general_ci'}
|
||||
P = None
|
||||
|
||||
def __repr__(self):
|
||||
return repr(self.as_dict())
|
||||
|
||||
def as_dict(self):
|
||||
return {x.name: getattr(self, x.name).strftime('%m-%d %H:%M:%S') if isinstance(getattr(self, x.name), datetime) else getattr(self, x.name) for x in self.__table__.columns}
|
||||
|
||||
|
||||
def save(self):
|
||||
try:
|
||||
with F.app.app_context():
|
||||
F.db.session.add(self)
|
||||
F.db.session.commit()
|
||||
return self
|
||||
except Exception as e:
|
||||
self.P.logger.error(f'Exception:{str(e)}')
|
||||
self.P.logger.error(traceback.format_exc())
|
||||
|
||||
@classmethod
|
||||
def get_paging_info(cls, count, current_page, page_size):
|
||||
try:
|
||||
paging = {}
|
||||
paging['prev_page'] = True
|
||||
paging['next_page'] = True
|
||||
if current_page <= 10:
|
||||
paging['prev_page'] = False
|
||||
|
||||
paging['total_page'] = int(count / page_size) + 1
|
||||
if count % page_size == 0:
|
||||
paging['total_page'] -= 1
|
||||
paging['start_page'] = int((current_page-1)/10) * 10 + 1
|
||||
paging['last_page'] = paging['total_page'] if paging['start_page'] + 9 > paging['total_page'] else paging['start_page'] + 9
|
||||
if paging['last_page'] == paging['total_page']:
|
||||
paging['next_page'] = False
|
||||
paging['current_page'] = current_page
|
||||
paging['count'] = count
|
||||
F.logger.debug('paging : c:%s %s %s %s %s %s', count, paging['total_page'], paging['prev_page'], paging['next_page'] , paging['start_page'], paging['last_page'])
|
||||
return paging
|
||||
except Exception as e:
|
||||
cls.P.logger.error(f'Exception:{str(e)}')
|
||||
cls.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
@classmethod
|
||||
def get_by_id(cls, id):
|
||||
try:
|
||||
with F.app.app_context():
|
||||
return F.db.session.query(cls).filter_by(id=int(id)).first()
|
||||
except Exception as e:
|
||||
cls.P.logger.error(f'Exception:{str(e)}')
|
||||
cls.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
@classmethod
|
||||
def get_list(cls, by_dict=False):
|
||||
try:
|
||||
with F.app.app_context():
|
||||
tmp = F.db.session.query(cls).all()
|
||||
if by_dict:
|
||||
tmp = [x.as_dict() for x in tmp]
|
||||
return tmp
|
||||
except Exception as e:
|
||||
cls.P.logger.error(f'Exception:{str(e)}')
|
||||
cls.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def delete_by_id(cls, id):
|
||||
try:
|
||||
with F.app.app_context():
|
||||
F.db.session.query(cls).filter_by(id=int(id)).delete()
|
||||
F.db.session.commit()
|
||||
return True
|
||||
except Exception as e:
|
||||
cls.P.logger.error(f'Exception:{str(e)}')
|
||||
cls.P.logger.error(traceback.format_exc())
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def delete_all(cls, days=None):
|
||||
try:
|
||||
with F.app.app_context():
|
||||
if days == None:
|
||||
F.db.session.query(cls).delete()
|
||||
F.db.session.commit()
|
||||
else:
|
||||
now = datetime.now()
|
||||
ago = now - timedelta(days=int(days))
|
||||
#ago.hour = 0
|
||||
#ago.minute = 0
|
||||
count = F.db.session.query(cls).filter(cls.created_time > ago).delete()
|
||||
cls.P.logger.info(f"delete_all {days=} {count=}")
|
||||
return True
|
||||
except Exception as e:
|
||||
cls.P.logger.error(f'Exception:{str(e)}')
|
||||
cls.P.logger.error(traceback.format_exc())
|
||||
return False
|
||||
|
||||
|
||||
@classmethod
|
||||
def web_list(cls, req):
|
||||
try:
|
||||
ret = {}
|
||||
page = 1
|
||||
page_size = 30
|
||||
search = ''
|
||||
if 'page' in req.form:
|
||||
page = int(req.form['page'])
|
||||
if 'keyword' in req.form:
|
||||
search = req.form['keyword'].strip()
|
||||
option1 = req.form.get('option1', 'all')
|
||||
option2 = req.form.get('option2', 'all')
|
||||
order = req.form['order'] if 'order' in req.form else 'desc'
|
||||
|
||||
query = cls.make_query(req, order=order, search=search, option1=option1, option2=option2)
|
||||
count = query.count()
|
||||
query = query.limit(page_size).offset((page-1)*page_size)
|
||||
#F.logger.debug('cls count:%s', count)
|
||||
lists = query.all()
|
||||
ret['list'] = [item.as_dict() for item in lists]
|
||||
ret['paging'] = cls.get_paging_info(count, page, page_size)
|
||||
try:
|
||||
if cls.P.ModelSetting is not None and cls.__tablename__ is not None:
|
||||
cls.P.ModelSetting.set(f'{cls.__tablename__}_last_list_option', f'{order}|{page}|{search}|{option1}|{option2}')
|
||||
except Exception as e:
|
||||
F.logger.error('Exception:%s', e)
|
||||
F.logger.error(traceback.format_exc())
|
||||
F.logger.error(f'{cls.__tablename__}_last_list_option ERROR!' )
|
||||
return ret
|
||||
except Exception as e:
|
||||
cls.P.logger.error('Exception:%s', e)
|
||||
cls.P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
# 오버라이딩
|
||||
@classmethod
|
||||
def make_query(cls, req, order='desc', search='', option1='all', option2='all'):
|
||||
with F.app.app_context():
|
||||
query = F.db.session.query(cls)
|
||||
return query
|
||||
|
||||
|
||||
@classmethod
|
||||
def make_query_search(cls, query, search, field):
|
||||
if search is not None and search != '':
|
||||
if search.find('|') != -1:
|
||||
tmp = search.split('|')
|
||||
conditions = []
|
||||
for tt in tmp:
|
||||
if tt != '':
|
||||
conditions.append(field.like('%'+tt.strip()+'%') )
|
||||
query = query.filter(or_(*conditions))
|
||||
elif search.find(',') != -1:
|
||||
tmp = search.split(',')
|
||||
for tt in tmp:
|
||||
if tt != '':
|
||||
query = query.filter(field.like('%'+tt.strip()+'%'))
|
||||
else:
|
||||
query = query.filter(field.like('%'+search+'%'))
|
||||
#query = query1.union(query2)
|
||||
return query
|
||||
@@ -0,0 +1,152 @@
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
|
||||
from framework import F
|
||||
|
||||
|
||||
def get_model_setting(package_name, logger, table_name=None):
|
||||
|
||||
class ModelSetting(F.db.Model):
|
||||
__tablename__ = '%s_setting' % package_name if table_name is None else table_name
|
||||
__table_args__ = {'mysql_collate': 'utf8_general_ci'}
|
||||
__bind_key__ = package_name
|
||||
|
||||
id = F.db.Column(F.db.Integer, primary_key=True)
|
||||
key = F.db.Column(F.db.String, unique=True, nullable=False)
|
||||
value = F.db.Column(F.db.String, nullable=False)
|
||||
|
||||
def __init__(self, key, value):
|
||||
self.key = key
|
||||
self.value = value
|
||||
|
||||
def __repr__(self):
|
||||
return repr(self.as_dict())
|
||||
|
||||
def as_dict(self):
|
||||
return {x.name: getattr(self, x.name) for x in self.__table__.columns}
|
||||
|
||||
@staticmethod
|
||||
def get(key):
|
||||
try:
|
||||
with F.app.app_context():
|
||||
ret = F.db.session.query(ModelSetting).filter_by(key=key).first()
|
||||
if ret is not None:
|
||||
return ret.value.strip()
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Exception:{str(e)} [{key}]")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
@staticmethod
|
||||
def has_key(key):
|
||||
with F.app.app_context():
|
||||
return (F.db.session.query(ModelSetting).filter_by(key=key).first() is not None)
|
||||
|
||||
@staticmethod
|
||||
def get_int(key):
|
||||
try:
|
||||
return int(ModelSetting.get(key))
|
||||
except Exception as e:
|
||||
logger.error(f"Exception:{str(e)} [{key}]")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
@staticmethod
|
||||
def get_bool(key):
|
||||
try:
|
||||
return (ModelSetting.get(key) == 'True')
|
||||
except Exception as e:
|
||||
logger.error(f"Exception:{str(e)} [{key}]")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
@staticmethod
|
||||
def get_datetime(key):
|
||||
try:
|
||||
tmp = ModelSetting.get(key)
|
||||
if tmp != None and tmp != '':
|
||||
return datetime.strptime(tmp, '%Y-%m-%d %H:%M:%S.%f')
|
||||
except Exception as e:
|
||||
logger.error(f"Exception:{str(e)} [{key}]")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
@staticmethod
|
||||
def set(key, value):
|
||||
try:
|
||||
with F.app.app_context():
|
||||
item = F.db.session.query(ModelSetting).filter_by(key=key).with_for_update().first()
|
||||
if item is not None:
|
||||
item.value = value.strip() if value is not None else value
|
||||
F.db.session.commit()
|
||||
else:
|
||||
F.db.session.add(ModelSetting(key, value.strip()))
|
||||
F.db.session.commit()
|
||||
except Exception as e:
|
||||
logger.error(f"Exception:{str(e)} [{key}]")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
@staticmethod
|
||||
def to_dict():
|
||||
try:
|
||||
ret = ModelSetting.db_list_to_dict(F.db.session.query(ModelSetting).all())
|
||||
ret['package_name'] = package_name
|
||||
return ret
|
||||
except Exception as e:
|
||||
logger.error(f"Exception:{str(e)}")
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
@staticmethod
|
||||
def setting_save(req):
|
||||
try:
|
||||
change_list = []
|
||||
for key, value in req.form.items():
|
||||
if key in ['scheduler', 'is_running']:
|
||||
continue
|
||||
if key.startswith('global') or key.startswith('tmp_') or key.startswith('_'):
|
||||
continue
|
||||
#logger.debug('Key:%s Value:%s', key, value)
|
||||
if ModelSetting.get(key) != value:
|
||||
change_list.append(key)
|
||||
entity = F.db.session.query(ModelSetting).filter_by(key=key).with_for_update().first()
|
||||
entity.value = value
|
||||
F.db.session.commit()
|
||||
return True, change_list
|
||||
except Exception as e:
|
||||
logger.error(f"Exception:{str(e)}")
|
||||
logger.error(traceback.format_exc())
|
||||
logger.debug('Error Key:%s Value:%s', key, value)
|
||||
return False, []
|
||||
|
||||
@staticmethod
|
||||
def get_list(key, delimeter='\n', comment=' #'):
|
||||
try:
|
||||
value = ModelSetting.get(key).replace('\n', delimeter)
|
||||
if comment is None:
|
||||
values = [x.strip() for x in value.split(delimeter)]
|
||||
else:
|
||||
values = [x.split(comment)[0].strip() for x in value.split(delimeter)]
|
||||
values = ModelSetting.get_list_except_empty(values)
|
||||
return values
|
||||
except Exception as e:
|
||||
logger.error(f"Exception:{str(e)}")
|
||||
logger.error(traceback.format_exc())
|
||||
logger.error('Error Key:%s Value:%s', key, value)
|
||||
|
||||
|
||||
@staticmethod
|
||||
def get_list_except_empty(source):
|
||||
tmp = []
|
||||
for _ in source:
|
||||
if _.strip().startswith('#'):
|
||||
continue
|
||||
if _.strip() != '':
|
||||
tmp.append(_.strip())
|
||||
return tmp
|
||||
|
||||
@staticmethod
|
||||
def db_list_to_dict(db_list):
|
||||
ret = {}
|
||||
for item in db_list:
|
||||
ret[item.key] = item.value
|
||||
return ret
|
||||
|
||||
return ModelSetting
|
||||
@@ -0,0 +1,422 @@
|
||||
import json
|
||||
import os
|
||||
import traceback
|
||||
|
||||
from flask import jsonify, redirect, render_template, request
|
||||
from flask_login import login_required
|
||||
from framework import F
|
||||
from support import AlchemyEncoder
|
||||
|
||||
|
||||
def default_route(P):
|
||||
@P.blueprint.route('/')
|
||||
def home():
|
||||
if P.ModelSetting is not None:
|
||||
tmp = P.ModelSetting.get('recent_menu_plugin')
|
||||
if tmp is not None and tmp != '':
|
||||
tmps = tmp.split('|')
|
||||
if len(tmps) == 2:
|
||||
return redirect('/{package_name}/{sub}/{sub2}'.format(package_name=P.package_name, sub=tmps[0], sub2=tmps[1]))
|
||||
elif len(tmps) == 1 and not (P.package_name =='system' and tmps[0] == 'logout'):
|
||||
return redirect('/{package_name}/{sub}'.format(package_name=P.package_name, sub=tmps[0]))
|
||||
|
||||
return redirect('/{package_name}/{home_module}'.format(package_name=P.package_name, home_module=P.home_module))
|
||||
|
||||
@P.blueprint.route('/<sub>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def first_menu(sub):
|
||||
try:
|
||||
if P.ModelSetting is not None and (P.package_name == 'system' and sub != 'home'):
|
||||
P.ModelSetting.set('recent_menu_plugin', '{}'.format(sub))
|
||||
for module in P.module_list:
|
||||
if sub == module.name:
|
||||
first_menu = module.get_first_menu()
|
||||
if first_menu:
|
||||
return redirect('/{package_name}/{sub}/{first_menu}'.format(package_name=P.package_name, sub=sub, first_menu=module.get_first_menu()))
|
||||
else:
|
||||
return module.process_menu(None, request)
|
||||
if sub == 'log':
|
||||
return render_template('log.html', package=P.package_name)
|
||||
elif sub == 'manual':
|
||||
#return redirect(f"/{P.package_name}/manual/{P.menu['second']['manual'][0][0]}")
|
||||
try:
|
||||
return redirect(f"/{P.package_name}/manual/{P.menu['sub2']['manual'][0][0]}")
|
||||
except:
|
||||
return redirect(f"/{P.package_name}/manual/{P.get_first_manual_path()}")
|
||||
|
||||
return render_template('sample.html', title='%s - %s' % (P.package_name, sub))
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
@P.blueprint.route('/manual/<path:path>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def manual(path):
|
||||
try:
|
||||
plugin_root = os.path.dirname(P.blueprint.template_folder)
|
||||
filepath = os.path.join(plugin_root, *path.split('/'))
|
||||
from support import SupportFile
|
||||
data = SupportFile.read_file(filepath)
|
||||
return render_template('manual.html', data=data)
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
@P.blueprint.route('/<sub>/<sub2>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def second_menu(sub, sub2):
|
||||
if P.ModelSetting is not None:
|
||||
P.ModelSetting.set('recent_menu_plugin', '{}|{}'.format(sub, sub2))
|
||||
try:
|
||||
for module in P.module_list:
|
||||
if sub == module.name:
|
||||
return module.process_menu(sub2, request)
|
||||
if sub == 'log':
|
||||
return render_template('log.html', package=P.package_name)
|
||||
return render_template('sample.html', title='%s - %s' % (P.package_name, sub))
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
#########################################################
|
||||
# For UI
|
||||
#########################################################
|
||||
@P.blueprint.route('/ajax/<sub>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def ajax(sub):
|
||||
P.logger.debug('AJAX %s %s', P.package_name, sub)
|
||||
try:
|
||||
# global
|
||||
if sub == 'setting_save':
|
||||
ret, change_list = P.ModelSetting.setting_save(request)
|
||||
for module in P.module_list:
|
||||
module.setting_save_after(change_list)
|
||||
return jsonify(ret)
|
||||
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
@P.blueprint.route('/ajax/<module_name>/<cmd>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def second_ajax(module_name, cmd):
|
||||
try:
|
||||
for module in P.module_list:
|
||||
if cmd == 'scheduler':
|
||||
go = request.form['scheduler']
|
||||
if go == 'true':
|
||||
P.logic.scheduler_start(module_name)
|
||||
else:
|
||||
P.logic.scheduler_stop(module_name)
|
||||
return jsonify(go)
|
||||
elif cmd == 'reset_db':
|
||||
ret = P.logic.reset_db(module_name)
|
||||
return jsonify(ret)
|
||||
elif cmd == 'one_execute':
|
||||
ret = P.logic.one_execute(module_name)
|
||||
return jsonify(ret)
|
||||
elif cmd == 'immediately_execute':
|
||||
ret = P.logic.immediately_execute(module_name)
|
||||
return jsonify(ret)
|
||||
elif cmd == 'web_list':
|
||||
model = P.logic.get_module(module_name).web_list_model
|
||||
if model != None:
|
||||
return jsonify(model.web_list(request))
|
||||
|
||||
if module_name == module.name:
|
||||
if cmd == 'command':
|
||||
return module.process_command(request.form['command'], request.form.get('arg1'), request.form.get('arg2'), request.form.get('arg3'), request)
|
||||
else:
|
||||
return module.process_ajax(cmd, request)
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
@P.blueprint.route('/ajax/<module_name>/<page_name>/<command>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def sub_ajax(module_name, page_name, command):
|
||||
try:
|
||||
ins_module = P.logic.get_module(module_name)
|
||||
ins_page = ins_module.get_page(page_name)
|
||||
if ins_page != None:
|
||||
if command == 'scheduler':
|
||||
#sub = page_name
|
||||
go = request.form['scheduler']
|
||||
P.logger.debug('scheduler :%s', go)
|
||||
if go == 'true':
|
||||
P.logic.scheduler_start_sub(module_name, page_name)
|
||||
else:
|
||||
P.logic.scheduler_stop_sub(module_name, page_name)
|
||||
return jsonify(go)
|
||||
#elif command == 'reset_db':
|
||||
# sub = request.form['sub']
|
||||
# ret = P.logic.reset_db(sub)
|
||||
# return jsonify(ret)
|
||||
elif command == 'one_execute':
|
||||
ret = P.logic.one_execute_sub(module_name, page_name)
|
||||
return jsonify(ret)
|
||||
elif command == 'immediately_execute':
|
||||
ret = P.logic.immediately_execute_sub(module_name, page_name)
|
||||
return jsonify(ret)
|
||||
elif command == 'command':
|
||||
return ins_page.process_command(request.form['command'], request.form.get('arg1'), request.form.get('arg2'), request.form.get('arg3'), request)
|
||||
else:
|
||||
return ins_page.process_ajax(command, request)
|
||||
P.logger.error(f"not process ajax : {P.package_name} {module_name} {page_name} {command}")
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
#########################################################
|
||||
# API - 외부
|
||||
#########################################################
|
||||
# 단일 모듈인 경우 모듈이름을 붙이기 불편하여 추가.
|
||||
@P.blueprint.route('/api/<sub2>', methods=['GET', 'POST'])
|
||||
@F.check_api
|
||||
def api_first(sub2):
|
||||
try:
|
||||
for module in P.module_list:
|
||||
return module.process_api(sub2, request)
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
@P.blueprint.route('/api/<sub>/<sub2>', methods=['GET', 'POST'])
|
||||
@F.check_api
|
||||
def api(sub, sub2):
|
||||
try:
|
||||
for module in P.module_list:
|
||||
if sub == module.name:
|
||||
return module.process_api(sub2, request)
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
@P.blueprint.route('/normal/<sub>/<sub2>', methods=['GET', 'POST'])
|
||||
def normal(sub, sub2):
|
||||
try:
|
||||
for module in P.module_list:
|
||||
if sub == module.name:
|
||||
return module.process_normal(sub2, request)
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def default_route_single_module(P):
|
||||
@P.blueprint.route('/')
|
||||
def home():
|
||||
return redirect('/{package_name}/{home_module}'.format(package_name=P.package_name, home_module=P.home_module))
|
||||
|
||||
@P.blueprint.route('/<sub>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def first_menu(sub):
|
||||
if sub == 'log':
|
||||
return render_template('log.html', package=P.package_name)
|
||||
return P.module_list[0].process_menu(sub, request)
|
||||
|
||||
@P.blueprint.route('/ajax/<sub>', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def ajax(sub):
|
||||
P.logger.debug('AJAX %s %s', P.package_name, sub)
|
||||
try:
|
||||
# global
|
||||
if sub == 'setting_save':
|
||||
ret, change_list = P.ModelSetting.setting_save(request)
|
||||
if ret:
|
||||
P.module_list[0].setting_save_after(change_list)
|
||||
if P.module_list[0].page_list is not None:
|
||||
for page_ins in P.module_list[0].page_list:
|
||||
page_ins.setting_save_after(change_list)
|
||||
return jsonify(ret)
|
||||
elif sub == 'scheduler':
|
||||
sub = request.form['sub']
|
||||
go = request.form['scheduler']
|
||||
P.logger.debug('scheduler :%s', go)
|
||||
if go == 'true':
|
||||
P.logic.scheduler_start(sub)
|
||||
else:
|
||||
P.logic.scheduler_stop(sub)
|
||||
return jsonify(go)
|
||||
elif sub == 'reset_db':
|
||||
sub = request.form['sub']
|
||||
ret = P.logic.reset_db(sub)
|
||||
return jsonify(ret)
|
||||
elif sub == 'one_execute':
|
||||
sub = request.form['sub']
|
||||
ret = P.logic.one_execute(sub)
|
||||
return jsonify(ret)
|
||||
else:
|
||||
return P.module_list[0].process_ajax(sub, request)
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
@P.blueprint.route('/api/<sub>', methods=['GET', 'POST'])
|
||||
@F.check_api
|
||||
def api(sub):
|
||||
try:
|
||||
return P.module_list[0].process_api(sub, request)
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
@P.blueprint.route('/normal/<sub>', methods=['GET', 'POST'])
|
||||
def normal(sub):
|
||||
try:
|
||||
return P.module_list[0].process_normal(sub, request)
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# 웹은 페이지
|
||||
# 파이썬은 모듈 단위일 떄 attach 사용
|
||||
# var socket11 = io.connect(window.location.href);
|
||||
def default_route_socketio_module(module, attach=''):
|
||||
P = module.P
|
||||
if module.socketio_list is None:
|
||||
module.socketio_list = []
|
||||
|
||||
@F.socketio.on('connect', namespace=f'/{P.package_name}/{module.name}{attach}')
|
||||
def connect():
|
||||
try:
|
||||
P.logger.debug(f'socket_connect : {P.package_name} - {module.name}{attach}')
|
||||
module.socketio_list.append(request.sid)
|
||||
socketio_callback('start', '')
|
||||
module.socketio_connect()
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
@F.socketio.on('disconnect', namespace=f'/{P.package_name}/{module.name}{attach}')
|
||||
def disconnect():
|
||||
try:
|
||||
P.logger.debug(f'socket_disconnect : {P.package_name} - {module.name}{attach}')
|
||||
module.socketio_list.remove(request.sid)
|
||||
module.socketio_disconnect()
|
||||
except Exception as exception:
|
||||
P.logger.error('Exception:%s', exception)
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def socketio_callback(cmd, data, encoding=True):
|
||||
if module.socketio_list:
|
||||
if encoding:
|
||||
data = json.dumps(data, cls=AlchemyEncoder)
|
||||
data = json.loads(data)
|
||||
F.socketio.emit(cmd, data, namespace=f'/{P.package_name}/{module.name}{attach}', broadcast=True)
|
||||
|
||||
module.socketio_callback = socketio_callback
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def default_route_socketio_page(page):
|
||||
|
||||
module = page.parent
|
||||
P = page.P
|
||||
if page.socketio_list is None:
|
||||
page.socketio_list = []
|
||||
|
||||
@F.socketio.on('connect', namespace=f'/{P.package_name}/{module.name}/{page.name}')
|
||||
def page_socketio_connect():
|
||||
try:
|
||||
P.logger.debug(f'socket_connect : {P.package_name}/{module.name}/{page.name}')
|
||||
page.socketio_list.append(request.sid)
|
||||
page_socketio_socketio_callback('start', '')
|
||||
except Exception as e:
|
||||
P.logger.error(f'Exception:{str(e)}')
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
@F.socketio.on('disconnect', namespace=f'/{P.package_name}/{module.name}/{page.name}')
|
||||
def page_socketio_disconnect():
|
||||
try:
|
||||
P.logger.debug(f'socket_disconnect : {P.package_name}/{module.name}/{page.name}')
|
||||
page.socketio_list.remove(request.sid)
|
||||
except Exception as e:
|
||||
P.logger.error(f'Exception:{str(e)}')
|
||||
P.logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def page_socketio_socketio_callback(cmd, data, encoding=True):
|
||||
if page.socketio_list:
|
||||
if encoding:
|
||||
data = json.dumps(data, cls=AlchemyEncoder)
|
||||
data = json.loads(data)
|
||||
F.socketio.emit(cmd, data, namespace=f'/{P.package_name}/{module.name}/{page.name}', broadcast=True)
|
||||
|
||||
page.socketio_callback = page_socketio_socketio_callback
|
||||
@@ -0,0 +1,24 @@
|
||||
def d(data):
|
||||
if type(data) in [type({}), type([])]:
|
||||
import json
|
||||
try:
|
||||
return '\n' + json.dumps(data, indent=4, ensure_ascii=False)
|
||||
except:
|
||||
return data
|
||||
else:
|
||||
return str(data)
|
||||
|
||||
from .logger import get_logger
|
||||
|
||||
logger = get_logger()
|
||||
|
||||
from .base.aes import SupportAES
|
||||
from .base.discord import SupportDiscord
|
||||
from .base.file import SupportFile
|
||||
from .base.string import SupportString
|
||||
from .base.sub_process import SupportSubprocess
|
||||
from .base.support_sc import SupportSC
|
||||
from .base.telegram import SupportTelegram
|
||||
from .base.util import (AlchemyEncoder, SingletonClass, SupportUtil,
|
||||
default_headers, pt)
|
||||
from .base.yaml import SupportYaml
|
||||
@@ -0,0 +1,47 @@
|
||||
import os, sys, traceback, subprocess, json, platform, time
|
||||
import shutil
|
||||
from . import logger
|
||||
|
||||
|
||||
class SupportFfmpeg(object):
|
||||
|
||||
@classmethod
|
||||
def download_m3u8(cls, config):
|
||||
try:
|
||||
|
||||
if config.get('proxy') == None:
|
||||
if config.get('headers') == None:
|
||||
command = [config.get('ffmpeg_path'), '-y', '-correct_ts_overflow', '0', '-i', config['url'], '-c', 'copy', '-bsf:a', 'aac_adtstoasc']
|
||||
else:
|
||||
headers_command = []
|
||||
for key, value in config.get('headers').items():
|
||||
if key.lower() == 'user-agent':
|
||||
headers_command.append('-user_agent')
|
||||
headers_command.append(value)
|
||||
pass
|
||||
else:
|
||||
headers_command.append('-headers')
|
||||
headers_command.append('\'%s:%s\''%(key,value))
|
||||
command = [config.get('ffmpeg_path'), '-y', '-correct_ts_overflow', '0'] + headers_command + ['-i', config['url'], '-c', 'copy', '-bsf:a', 'aac_adtstoasc']
|
||||
else:
|
||||
command = [config.get('ffmpeg_path'), '-y', '-correct_ts_overflow', '0', '-http_proxy', config.get('proxy'), '-i', config['url'], '-c', 'copy', '-bsf:a', 'aac_adtstoasc']
|
||||
|
||||
filename = str(int(time.time())) + '.mp4'
|
||||
tmp = config.get('tmp_dir')
|
||||
if tmp == None:
|
||||
tmp = os.getcwd()
|
||||
tmp_filepath = os.path.join(tmp, filename)
|
||||
command.append(tmp_filepath)
|
||||
logger.debug(' '.join(command))
|
||||
from . import SupportSubprocess
|
||||
ret = SupportSubprocess.execute(command, timeout=10)
|
||||
logger.error(ret)
|
||||
if os.path.exists(tmp_filepath):
|
||||
shutil.move(tmp_filepath, config.get('output_filepath'))
|
||||
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f'Exception:{str(e)}', )
|
||||
logger.error(traceback.format_exc())
|
||||
logger.error('command : %s', command)
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
from support import d, logger
|
||||
|
||||
import support
|
||||
logger = support.logger
|
||||
@@ -0,0 +1,100 @@
|
||||
import base64
|
||||
import os
|
||||
import traceback
|
||||
|
||||
from Crypto import Random
|
||||
from Crypto.Cipher import AES
|
||||
|
||||
from . import logger
|
||||
|
||||
BS = 16
|
||||
pad = lambda s: s + (BS - len(s.encode('utf-8')) % BS) * chr(BS - len(s.encode('utf-8')) % BS)
|
||||
#unpad = lambda s : s[0:-s[-1]]
|
||||
unpad = lambda s : s[:-ord(s[len(s)-1:])]
|
||||
key = b'140b41b22a29beb4061bda66b6747e14'
|
||||
|
||||
class SupportAES(object):
|
||||
@classmethod
|
||||
def encrypt(cls, raw, mykey=None):
|
||||
try:
|
||||
Random.atfork()
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
raw = pad(raw)
|
||||
if type(raw) == type(''):
|
||||
raw = raw.encode()
|
||||
if mykey is not None and type(mykey) == type(''):
|
||||
mykey = mykey.encode()
|
||||
iv = Random.new().read( AES.block_size )
|
||||
cipher = AES.new(key if mykey is None else mykey, AES.MODE_CBC, iv )
|
||||
try:
|
||||
tmp = cipher.encrypt( raw )
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
tmp = cipher.encrypt( raw.encode() )
|
||||
ret = base64.b64encode( iv + tmp )
|
||||
ret = ret.decode()
|
||||
return ret
|
||||
|
||||
@classmethod
|
||||
def decrypt(cls, enc, mykey=None):
|
||||
enc = base64.b64decode(enc)
|
||||
iv = enc[:16]
|
||||
if len(iv) != 16:
|
||||
iv = os.urandom(16)
|
||||
if mykey is not None and type(mykey) == type(''):
|
||||
mykey = mykey.encode()
|
||||
cipher = AES.new(key if mykey is None else mykey, AES.MODE_CBC, iv )
|
||||
return unpad(cipher.decrypt( enc[16:] )).decode()
|
||||
|
||||
@classmethod
|
||||
def md5(cls, text):
|
||||
import hashlib
|
||||
enc = hashlib.md5()
|
||||
enc.update(text.encode())
|
||||
return enc.hexdigest()
|
||||
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def encrypt_(cls, raw, mykey=None, iv=None):
|
||||
try:
|
||||
Random.atfork()
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
raw = pad(raw)
|
||||
if type(raw) == type(''):
|
||||
raw = raw.encode()
|
||||
if mykey is not None and type(mykey) == type(''):
|
||||
mykey = mykey.encode()
|
||||
if iv == None:
|
||||
iv = Random.new().read( AES.block_size )
|
||||
elif iv is not None and type(iv) == type(''):
|
||||
iv = iv.encode()
|
||||
cipher = AES.new(key if mykey is None else mykey, AES.MODE_CBC, iv )
|
||||
try:
|
||||
tmp = cipher.encrypt( raw )
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
tmp = cipher.encrypt( raw.encode() )
|
||||
ret = base64.b64encode( tmp )
|
||||
ret = ret.decode()
|
||||
return ret
|
||||
|
||||
@classmethod
|
||||
def decrypt_(cls, enc, mykey=None, iv=None):
|
||||
enc = base64.b64decode(enc)
|
||||
if iv == None:
|
||||
iv = os.urandom(16)
|
||||
elif iv is not None and type(iv) == type(''):
|
||||
iv = iv.encode()
|
||||
if mykey is not None and type(mykey) == type(''):
|
||||
mykey = mykey.encode()
|
||||
cipher = AES.new(key if mykey is None else mykey, AES.MODE_CBC, iv )
|
||||
return unpad(cipher.decrypt( enc )).decode()
|
||||
@@ -0,0 +1,219 @@
|
||||
import io
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
import traceback
|
||||
|
||||
import requests
|
||||
|
||||
try:
|
||||
from discord_webhook import DiscordEmbed, DiscordWebhook
|
||||
except:
|
||||
os.system('pip3 install discord-webhook')
|
||||
|
||||
from discord_webhook import DiscordEmbed, DiscordWebhook
|
||||
|
||||
from . import logger
|
||||
|
||||
webhook_list = [
|
||||
#'https://discord.com/api/webhooks/933908493612744705/DGPWBQN8LiMnt2cnCSNVy6rCc5Gi_vj98QpJ3ZEeihohzsfOsCWvcixJU1A2fQuepGFq', # 1
|
||||
#'https://discord.com/api/webhooks/932754078839234731/R2iFzQ7P8IKV-MGWp820ToWX07s5q8X-st-QsUJs7j3JInUj6ZlI4uDYKeR_cwIi98mf', # 2
|
||||
#'https://discord.com/api/webhooks/932754171835351131/50RLrYa_B69ybk4BWoLruNqU7YlZ3pl3gpPr9bwuankWyTIGtRGbgf0CJ9ExJWJmvXwo', # 3
|
||||
'https://discord.com/api/webhooks/794661043863027752/A9O-vZSHIgfQ3KX7wO5_e2xisqpLw5TJxg2Qs1stBHxyd5PK-Zx0IJbAQXmyDN1ixZ-n', # 4
|
||||
'https://discord.com/api/webhooks/810373348776476683/h_uJLBBlHzD0w_CG0nUajFO-XEh3fvy-vQofQt1_8TMD7zHiR7a28t3jF-xBCP6EVlow', # 5
|
||||
'https://discord.com/api/webhooks/810373405508501534/wovhf-1pqcxW5h9xy7iwkYaf8KMDjHU49cMWuLKtBWjAnj-tzS1_j8RJ7tsMyViDbZCE', # 6
|
||||
'https://discord.com/api/webhooks/796558388326039552/k2VV356S1gKQa9ht-JuAs5Dqw5eVkxgZsLUzFoxmFG5lW6jqKl7zCBbbKVhs3pcLOetm', # 7
|
||||
'https://discord.com/api/webhooks/810373566452858920/Qf2V8BoLOy2kQzlZGHy5HZ1nTj7lK72ol_UFrR3_eHKEOK5fyR_fQ8Yw8YzVh9EQG54o', # 8
|
||||
'https://discord.com/api/webhooks/810373654411739157/SGgdO49OCkTNIlc_BSMSy7IXQwwXVonG3DsVfvBVE6luTCwvgCqEBpEk30WBeMMieCyI', # 9
|
||||
'https://discord.com/api/webhooks/810373722341900288/FwcRJ4YxYjpyHpnRwF5f2an0ltEm8JPqcWeZqQi3Qz4QnhEY-kR2sjF9fo_n6stMGnf_', # 10
|
||||
'https://discord.com/api/webhooks/931779811691626536/vvwCm1YQvE5tW4QJ4SNKRmXhQQrmOQxbjsgRjbTMMXOSiclB66qipiZaax5giAqqu2IB', # 11
|
||||
'https://discord.com/api/webhooks/931779905631420416/VKlDwfxWQPJfIaj94-ww_hM1MNEayRKoMq0adMffCC4WQS60yoAub_nqPbpnfFRR3VU5', # 12
|
||||
'https://discord.com/api/webhooks/931779947914231840/22amQuHSOI7wPijSt3U01mXwd5hTo_WHfVkeaowDQMawCo5tXVfeEMd6wAWf1n7CseiG', # 13
|
||||
'https://discord.com/api/webhooks/810374294416654346/T3-TEdKIg7rwMZeDzNr46KPDvO7ZF8pRdJ3lfl39lJw2XEZamAG8uACIXagbNMX_B0YN', # 14
|
||||
'https://discord.com/api/webhooks/810374337403289641/_esFkQXwlPlhxJWtlqDAdLg2Nujo-LjGPEG3mUmjiRZto69NQpkBJ0F2xtSNrCH4VAgb', # 15
|
||||
'https://discord.com/api/webhooks/810374384736534568/mH5-OkBVpi7XqJioaQ8Ma-NiL-bOx7B5nYJpL1gZ03JaJaUaIW4bCHeCt5O_VGLJwAtj', # 16
|
||||
'https://discord.com/api/webhooks/810374428604104724/Z1Tdxz3mb0ytWq5LHWi4rG5CeJnr9KWXy5aO_waeD0NcImQnhRXe7h7ra7UrIDRQ2jOg', # 17
|
||||
'https://discord.com/api/webhooks/810374475773509643/QCPPN4djNzhuOmbS3DlrGBunK0SVR5Py9vMyCiPL-0T2VPgitFZS4YM6GCLfM2fkrn4-', # 18
|
||||
'https://discord.com/api/webhooks/810374527652855819/5ypaKI_r-hYzwmdDlVmgAU6xNgU833L9tFlPnf3nw4ZDaPMSppjt77aYOiFks4KLGQk8', # 19
|
||||
'https://discord.com/api/webhooks/810374587917402162/lHrG7CEysGUM_41DMnrxL2Q8eh1-xPjJXstYE68WWfLQbuUAV3rOfsNB9adncJzinYKi', # 20
|
||||
]
|
||||
|
||||
|
||||
class SupportDiscord(object):
|
||||
|
||||
@classmethod
|
||||
def send_discord_message(cls, text, image_url=None, webhook_url=None):
|
||||
try:
|
||||
webhook = DiscordWebhook(url=webhook_url, content=text)
|
||||
if image_url is not None:
|
||||
embed = DiscordEmbed()
|
||||
embed.set_timestamp()
|
||||
embed.set_image(url=image_url)
|
||||
webhook.add_embed(embed)
|
||||
response = webhook.execute()
|
||||
return True
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
return False
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def discord_proxy_image(cls, image_url, webhook_url=None, retry=True):
|
||||
#2020-12-23
|
||||
#image_url = None
|
||||
if image_url == '' or image_url is None:
|
||||
return
|
||||
data = None
|
||||
|
||||
if webhook_url is None or webhook_url == '':
|
||||
webhook_url = webhook_list[random.randint(0,len(webhook_list)-1)]
|
||||
|
||||
try:
|
||||
webhook = DiscordWebhook(url=webhook_url, content='')
|
||||
embed = DiscordEmbed()
|
||||
embed.set_timestamp()
|
||||
embed.set_image(url=image_url)
|
||||
webhook.add_embed(embed)
|
||||
import io
|
||||
byteio = io.BytesIO()
|
||||
webhook.add_file(file=byteio.getvalue(), filename='dummy')
|
||||
response = webhook.execute()
|
||||
data = None
|
||||
if type(response) == type([]):
|
||||
if len(response) > 0:
|
||||
data = response[0].json()
|
||||
else:
|
||||
data = response.json()
|
||||
|
||||
if data is not None and 'embeds' in data:
|
||||
target = data['embeds'][0]['image']['proxy_url']
|
||||
if requests.get(target).status_code == 200:
|
||||
return target
|
||||
else:
|
||||
return image_url
|
||||
else:
|
||||
raise Exception(str(data))
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
if retry:
|
||||
time.sleep(1)
|
||||
return cls.discord_proxy_image(image_url, webhook_url=None, retry=False)
|
||||
else:
|
||||
return image_url
|
||||
|
||||
|
||||
@classmethod
|
||||
def discord_proxy_image_localfile(cls, filepath, retry=True):
|
||||
data = None
|
||||
webhook_url = webhook_list[random.randint(0,len(webhook_list)-1)]
|
||||
|
||||
try:
|
||||
webhook = DiscordWebhook(url=webhook_url, content='')
|
||||
import io
|
||||
with open(filepath, 'rb') as fh:
|
||||
byteio = io.BytesIO(fh.read())
|
||||
webhook.add_file(file=byteio.getvalue(), filename='image.jpg')
|
||||
embed = DiscordEmbed()
|
||||
embed.set_image(url="attachment://image.jpg")
|
||||
response = webhook.execute()
|
||||
data = None
|
||||
if type(response) == type([]):
|
||||
if len(response) > 0:
|
||||
data = response[0].json()
|
||||
else:
|
||||
data = response.json()
|
||||
|
||||
if data is not None and 'attachments' in data:
|
||||
target = data['attachments'][0]['url']
|
||||
if requests.get(target).status_code == 200:
|
||||
return target
|
||||
if retry:
|
||||
time.sleep(1)
|
||||
return cls.discord_proxy_image_localfile(filepath, retry=False)
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
if retry:
|
||||
time.sleep(1)
|
||||
return cls.discord_proxy_image_localfile(filepath, retry=False)
|
||||
|
||||
|
||||
@classmethod
|
||||
def discord_proxy_image_bytes(cls, bytes, retry=True):
|
||||
data = None
|
||||
idx = random.randint(0,len(webhook_list)-1)
|
||||
webhook_url = webhook_list[idx]
|
||||
try:
|
||||
webhook = DiscordWebhook(url=webhook_url, content='')
|
||||
webhook.add_file(file=bytes, filename='image.jpg')
|
||||
embed = DiscordEmbed()
|
||||
embed.set_image(url="attachment://image.jpg")
|
||||
response = webhook.execute()
|
||||
data = None
|
||||
if type(response) == type([]):
|
||||
if len(response) > 0:
|
||||
data = response[0].json()
|
||||
else:
|
||||
data = response.json()
|
||||
if data is not None and 'attachments' in data:
|
||||
target = data['attachments'][0]['url']
|
||||
if requests.get(target).status_code == 200:
|
||||
return target
|
||||
logger.error(f"discord webhook error : {webhook_url}")
|
||||
logger.error(f"discord webhook error : {idx}")
|
||||
if retry:
|
||||
time.sleep(1)
|
||||
return cls.discord_proxy_image_bytes(bytes, retry=False)
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
if retry:
|
||||
time.sleep(1)
|
||||
return cls.discord_proxy_image_bytes(bytes, retry=False)
|
||||
|
||||
|
||||
|
||||
|
||||
# RSS에서 자막 올린거
|
||||
@classmethod
|
||||
def discord_cdn(cls, byteio=None, filepath=None, filename=None, webhook_url=None, content='', retry=True):
|
||||
data = None
|
||||
if webhook_url is None:
|
||||
webhook_url = webhook_list[random.randint(0,9)]
|
||||
|
||||
try:
|
||||
webhook = DiscordWebhook(url=webhook_url, content=content)
|
||||
if byteio is None and filepath is not None:
|
||||
import io
|
||||
with open(filepath, 'rb') as fh:
|
||||
byteio = io.BytesIO(fh.read())
|
||||
|
||||
webhook.add_file(file=byteio.getvalue(), filename=filename)
|
||||
embed = DiscordEmbed()
|
||||
response = webhook.execute()
|
||||
data = None
|
||||
if type(response) == type([]):
|
||||
if len(response) > 0:
|
||||
data = response[0].json()
|
||||
else:
|
||||
data = response.json()
|
||||
|
||||
if data is not None and 'attachments' in data:
|
||||
target = data['attachments'][0]['url']
|
||||
if requests.get(target).status_code == 200:
|
||||
return target
|
||||
if retry:
|
||||
time.sleep(1)
|
||||
return cls.discord_proxy_image_localfile(filepath, retry=False)
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
if retry:
|
||||
time.sleep(1)
|
||||
return cls.discord_proxy_image_localfile(filepath, retry=False)
|
||||
|
||||
@@ -0,0 +1,368 @@
|
||||
import codecs
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import traceback
|
||||
|
||||
from . import logger
|
||||
|
||||
|
||||
class SupportFile(object):
|
||||
|
||||
@classmethod
|
||||
def read_file(cls, filename, mode='r'):
|
||||
try:
|
||||
ifp = codecs.open(filename, mode, encoding='utf8')
|
||||
data = ifp.read()
|
||||
ifp.close()
|
||||
return data
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
@classmethod
|
||||
def write_file(cls, filename, data, mode='w'):
|
||||
try:
|
||||
import codecs
|
||||
ofp = codecs.open(filename, mode, encoding='utf8')
|
||||
ofp.write(data)
|
||||
ofp.close()
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
@classmethod
|
||||
def read_json(cls, filepath):
|
||||
try:
|
||||
with open(filepath, "r", encoding='utf8') as json_file:
|
||||
data = json.load(json_file)
|
||||
return data
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
@classmethod
|
||||
def write_json(cls, filepath, data):
|
||||
try:
|
||||
if os.path.dirname(filepath) != '':
|
||||
os.makedirs(os.path.dirname(filepath), exist_ok=True)
|
||||
with open(filepath, "w", encoding='utf8') as json_file:
|
||||
json.dump(data, json_file, indent=4, ensure_ascii=False)
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def download_file(cls, url, filepath):
|
||||
try:
|
||||
headers = {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
|
||||
'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
|
||||
'Accept-Language' : 'ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7',
|
||||
'Connection': 'Keep-Alive',
|
||||
}
|
||||
|
||||
import requests
|
||||
with open(filepath, "wb") as file_is: # open in binary mode
|
||||
response = requests.get(url, headers=headers) # get request
|
||||
file_is.write(response.content) # write to file
|
||||
return True
|
||||
except Exception as exception:
|
||||
logger.debug('Exception:%s', exception)
|
||||
logger.debug(traceback.format_exc())
|
||||
return False
|
||||
|
||||
|
||||
@classmethod
|
||||
def text_for_filename(cls, text):
|
||||
#text = text.replace('/', '')
|
||||
# 2021-07-31 X:X
|
||||
#text = text.replace(':', ' ')
|
||||
text = re.sub('[\\/:*?\"<>|]', ' ', text).strip()
|
||||
text = re.sub("\s{2,}", ' ', text)
|
||||
return text
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def size(cls, start_path = '.'):
|
||||
total_size = 0
|
||||
for dirpath, dirnames, filenames in os.walk(start_path):
|
||||
for f in filenames:
|
||||
fp = os.path.join(dirpath, f)
|
||||
if not os.path.islink(fp):
|
||||
total_size += os.path.getsize(fp)
|
||||
return total_size
|
||||
|
||||
@classmethod
|
||||
def file_move(cls, source_path, target_dir, target_filename):
|
||||
try:
|
||||
import shutil
|
||||
import time
|
||||
if os.path.exists(target_dir) == False:
|
||||
os.makedirs(target_dir)
|
||||
target_path = os.path.join(target_dir, target_filename)
|
||||
if source_path != target_path:
|
||||
if os.path.exists(target_path):
|
||||
tmp = os.path.splitext(target_filename)
|
||||
new_target_filename = f"{tmp[0]} {str(time.time()).split('.')[0]}{tmp[1]}"
|
||||
target_path = os.path.join(target_dir, new_target_filename)
|
||||
shutil.move(source_path, target_path)
|
||||
except Exception as exception:
|
||||
logger.debug('Exception:%s', exception)
|
||||
logger.debug(traceback.format_exc())
|
||||
|
||||
"""
|
||||
@classmethod
|
||||
def makezip(cls, zip_path, zip_folder=None, zip_extension='zip', remove_folder=False):
|
||||
import zipfile
|
||||
try:
|
||||
zip_path = zip_path.rstrip('/')
|
||||
if zip_folder is None:
|
||||
zip_folder = os.path.dirname(zip_path)
|
||||
elif zip_folder == 'tmp':
|
||||
from framework import path_data
|
||||
zip_folder = os.path.join(path_data, 'tmp')
|
||||
if os.path.isdir(zip_path):
|
||||
zipfilepath = os.path.join(zip_folder, f"{os.path.basename(zip_path)}.{zip_extension}")
|
||||
fantasy_zip = zipfile.ZipFile(zipfilepath, 'w')
|
||||
for f in os.listdir(zip_path):
|
||||
src = os.path.join(zip_path, f)
|
||||
fantasy_zip.write(src, os.path.basename(src), compress_type = zipfile.ZIP_DEFLATED)
|
||||
fantasy_zip.close()
|
||||
if remove_folder:
|
||||
import shutil
|
||||
shutil.rmtree(zip_path)
|
||||
return zipfilepath
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
return
|
||||
"""
|
||||
|
||||
|
||||
@classmethod
|
||||
def rmtree(cls, folderpath):
|
||||
import shutil
|
||||
try:
|
||||
shutil.rmtree(folderpath)
|
||||
return True
|
||||
except:
|
||||
try:
|
||||
os.system("rm -rf '{folderpath}'")
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
@classmethod
|
||||
def rmtree2(cls, folderpath):
|
||||
import shutil
|
||||
try:
|
||||
for root, dirs, files in os.walk(folderpath):
|
||||
for name in files:
|
||||
os.remove(os.path.join(root, name))
|
||||
for name in dirs:
|
||||
shutil.rmtree(os.path.join(root, name))
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def write_binary(cls, filename, data):
|
||||
try:
|
||||
with open(filename, 'wb') as f:
|
||||
f.write(data)
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def makezip(cls, zip_path, zip_extension='zip', remove_zip_path=True):
|
||||
import shutil
|
||||
import zipfile
|
||||
try:
|
||||
if os.path.exists(zip_path) == False:
|
||||
return False
|
||||
zipfilepath = os.path.join(os.path.dirname(zip_path), f"{os.path.basename(zip_path)}.{zip_extension}")
|
||||
if os.path.exists(zipfilepath):
|
||||
return True
|
||||
zip = zipfile.ZipFile(zipfilepath, 'w')
|
||||
for f in os.listdir(zip_path):
|
||||
src = os.path.join(zip_path, f)
|
||||
zip.write(src, f, compress_type = zipfile.ZIP_DEFLATED)
|
||||
zip.close()
|
||||
if remove_zip_path:
|
||||
shutil.rmtree(zip_path)
|
||||
return zipfilepath
|
||||
except Exception as e:
|
||||
logger.error(f'Exception:{str(e)}')
|
||||
logger.error(traceback.format_exc())
|
||||
return None
|
||||
|
||||
|
||||
@classmethod
|
||||
def write_yaml(cls, filepath, data):
|
||||
import yaml
|
||||
with open(filepath, 'w', encoding='utf8') as f:
|
||||
yaml.dump(data, f, default_flow_style=False, allow_unicode=True)
|
||||
|
||||
|
||||
|
||||
@classmethod
|
||||
def makezip_all(cls, zip_path, zip_filepath=None, zip_extension='zip', remove_zip_path=True):
|
||||
import shutil
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
try:
|
||||
if os.path.exists(zip_path) == False:
|
||||
return False
|
||||
if zip_filepath == None:
|
||||
zipfilepath = os.path.join(os.path.dirname(zip_path), f"{os.path.basename(zip_path)}.{zip_extension}")
|
||||
if os.path.exists(zipfilepath):
|
||||
os.remove(zipfilepath)
|
||||
zip = zipfile.ZipFile(zipfilepath, 'w')
|
||||
for file_path in Path(zip_path).rglob("*"):
|
||||
zip.write(file_path, file_path.name)
|
||||
|
||||
|
||||
for (path, dir, files) in os.walk(zip_path):
|
||||
for file in files:
|
||||
zip.write(os.path.join(path.replace(zip_path+'/', '').replace(zip_path+'\\', ''), file), compress_type=zipfile.ZIP_DEFLATED)
|
||||
zip.close()
|
||||
if remove_zip_path:
|
||||
shutil.rmtree(zip_path)
|
||||
return zipfilepath
|
||||
except Exception as e:
|
||||
logger.error(f'Exception:{str(e)}')
|
||||
logger.error(traceback.format_exc())
|
||||
return None
|
||||
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def read(cls, filepath, mode='r'):
|
||||
try:
|
||||
import codecs
|
||||
ifp = codecs.open(filepath, mode, encoding='utf8')
|
||||
data = ifp.read()
|
||||
ifp.close()
|
||||
if isinstance(data, bytes):
|
||||
data = data.decode('utf-8')
|
||||
return data
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
"""
|
||||
@@ -0,0 +1,25 @@
|
||||
import os, sys, traceback, requests
|
||||
from io import BytesIO
|
||||
from . import logger
|
||||
|
||||
class SupportImage(object):
|
||||
|
||||
@classmethod
|
||||
def horizontal_to_vertical(cls, url):
|
||||
try:
|
||||
from PIL import Image
|
||||
im = Image.open(requests.get(url, stream=True).raw)
|
||||
width,height = im.size
|
||||
new_height = int(width * 1.5)
|
||||
new_im = Image.new('RGB', (width, new_height))
|
||||
new_im.paste(im, (0, int((new_height-height)/2)))
|
||||
|
||||
img_byte_arr = BytesIO()
|
||||
new_im.save(img_byte_arr, format='PNG')
|
||||
img_byte_arr = img_byte_arr.getvalue()
|
||||
from . import SupportDiscord
|
||||
return SupportDiscord.discord_proxy_image_bytes(img_byte_arr)
|
||||
except Exception as e:
|
||||
logger.error('Exception:%s', e)
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
from . import logger
|
||||
|
||||
|
||||
class SupportString(object):
|
||||
@classmethod
|
||||
def get_cate_char_by_first(cls, title): # get_first
|
||||
value = ord(title[0].upper())
|
||||
if value >= ord('0') and value <= ord('9'): return '0Z'
|
||||
elif value >= ord('A') and value <= ord('Z'): return '0Z'
|
||||
elif value >= ord('가') and value < ord('나'): return '가'
|
||||
elif value < ord('다'): return '나'
|
||||
elif value < ord('라'): return '다'
|
||||
elif value < ord('마'): return '라'
|
||||
elif value < ord('바'): return '마'
|
||||
elif value < ord('사'): return '바'
|
||||
elif value < ord('아'): return '사'
|
||||
elif value < ord('자'): return '아'
|
||||
elif value < ord('차'): return '자'
|
||||
elif value < ord('카'): return '차'
|
||||
elif value < ord('타'): return '카'
|
||||
elif value < ord('파'): return '타'
|
||||
elif value < ord('하'): return '파'
|
||||
elif value <= ord('힣'): return '하'
|
||||
else: return '0Z'
|
||||
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import queue
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from . import logger
|
||||
|
||||
|
||||
def demote(user_uid, user_gid):
|
||||
def result():
|
||||
os.setgid(user_gid)
|
||||
os.setuid(user_uid)
|
||||
return result
|
||||
|
||||
class SupportSubprocess(object):
|
||||
|
||||
@classmethod
|
||||
def command_for_windows(cls, command: list) -> str or list:
|
||||
if platform.system() == 'Windows':
|
||||
tmp = []
|
||||
if type(command) == type([]):
|
||||
for x in command:
|
||||
if x.find(' ') == -1:
|
||||
tmp.append(x)
|
||||
else:
|
||||
tmp.append(f'"{x}"')
|
||||
command = ' '.join(tmp)
|
||||
return command
|
||||
|
||||
# 2021-10-25
|
||||
# timeout 적용
|
||||
@classmethod
|
||||
def execute_command_return(cls, command, format=None, log=False, shell=False, env=None, timeout=None, uid=None, gid=None):
|
||||
|
||||
try:
|
||||
logger.debug(f"execute_command_return : {' '.join(command)}")
|
||||
command = cls.command_for_windows(command)
|
||||
|
||||
iter_arg = ''
|
||||
if platform.system() == 'Windows':
|
||||
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=shell, env=env, encoding='utf8')
|
||||
else:
|
||||
if uid == None:
|
||||
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=shell, env=env, encoding='utf8')
|
||||
else:
|
||||
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, shell=shell, env=env, preexec_fn=demote(uid, gid), encoding='utf8')
|
||||
|
||||
|
||||
|
||||
new_ret = {'status':'finish', 'log':None}
|
||||
try:
|
||||
process_ret = process.wait(timeout=timeout) # wait for the subprocess to exit
|
||||
except:
|
||||
import psutil
|
||||
process = psutil.Process(process.pid)
|
||||
for proc in process.children(recursive=True):
|
||||
proc.kill()
|
||||
process.kill()
|
||||
new_ret['status'] = "timeout"
|
||||
|
||||
ret = []
|
||||
with process.stdout:
|
||||
for line in iter(process.stdout.readline, iter_arg):
|
||||
ret.append(line.strip())
|
||||
if log:
|
||||
logger.debug(ret[-1])
|
||||
|
||||
if format is None:
|
||||
ret2 = '\n'.join(ret)
|
||||
elif format == 'json':
|
||||
try:
|
||||
index = 0
|
||||
for idx, tmp in enumerate(ret):
|
||||
#logger.debug(tmp)
|
||||
if tmp.startswith('{') or tmp.startswith('['):
|
||||
index = idx
|
||||
break
|
||||
ret2 = json.loads(''.join(ret[index:]))
|
||||
except:
|
||||
ret2 = None
|
||||
|
||||
new_ret['log'] = ret2
|
||||
return new_ret
|
||||
except Exception as exception:
|
||||
logger.error('Exception:%s', exception)
|
||||
logger.error(traceback.format_exc())
|
||||
logger.error('command : %s', command)
|
||||
|
||||
|
||||
__instance_list = []
|
||||
|
||||
|
||||
def __init__(self, command, print_log=False, shell=False, env=None, timeout=None, uid=None, gid=None, stdout_callback=None, call_id=None):
|
||||
self.command = command
|
||||
self.print_log = print_log
|
||||
self.shell = shell
|
||||
self.env = env
|
||||
self.timeout = timeout
|
||||
self.uid = uid
|
||||
self.gid = gid
|
||||
self.stdout_callback = stdout_callback
|
||||
self.process = None
|
||||
self.stdout_queue = None
|
||||
self.call_id = call_id
|
||||
self.timestamp = time.time()
|
||||
|
||||
|
||||
def start(self, join=True):
|
||||
try:
|
||||
self.thread = threading.Thread(target=self.__execute_thread_function, args=())
|
||||
self.thread.setDaemon(True)
|
||||
self.thread.start()
|
||||
if join:
|
||||
self.thread.join()
|
||||
except Exception as e:
|
||||
logger.error(f'Exception:{str(e)}')
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
|
||||
def __execute_thread_function(self):
|
||||
try:
|
||||
self.command = self.command_for_windows(self.command)
|
||||
logger.debug(f"{self.command=}")
|
||||
if platform.system() == 'Windows':
|
||||
self.process = subprocess.Popen(self.command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=self.shell, env=self.env, encoding='utf8', bufsize=0)
|
||||
else:
|
||||
if self.uid == None:
|
||||
self.process = subprocess.Popen(self.command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=self.shell, env=self.env, encoding='utf8', bufsize=0)
|
||||
else:
|
||||
self.process = subprocess.Popen(self.command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=self.shell, env=self.env, preexec_fn=demote(self.uid, self.gid), encoding='utf8', bufsize=0)
|
||||
SupportSubprocess.__instance_list.append(self)
|
||||
self.__start_communicate()
|
||||
self.__start_send_callback()
|
||||
if self.process is not None:
|
||||
if self.timeout != None:
|
||||
self.process.wait(timeout=self.timeout)
|
||||
self.process_close()
|
||||
else:
|
||||
self.process.wait()
|
||||
logger.info(f"{self.command} END")
|
||||
except Exception as e:
|
||||
logger.error(f'Exception:{str(e)}')
|
||||
logger.error(traceback.format_exc())
|
||||
logger.warning(self.command)
|
||||
if self.stdout_callback != None:
|
||||
self.stdout_callback('error', str(e))
|
||||
self.stdout_callback('error', str(traceback.format_exc()))
|
||||
finally:
|
||||
if self.stdout_callback != None:
|
||||
self.stdout_callback('thread_end', None)
|
||||
|
||||
|
||||
def __start_communicate(self):
|
||||
self.stdout_queue = queue.Queue()
|
||||
sout = io.open(self.process.stdout.fileno(), 'rb', closefd=False)
|
||||
|
||||
def Pump(stream):
|
||||
_queue = queue.Queue()
|
||||
|
||||
def rdr():
|
||||
while True:
|
||||
buf = self.process.stdout.read(1)
|
||||
if buf:
|
||||
_queue.put( buf )
|
||||
else:
|
||||
_queue.put( None )
|
||||
break
|
||||
_queue.put( None )
|
||||
time.sleep(1)
|
||||
|
||||
def clct():
|
||||
active = True
|
||||
while active:
|
||||
r = _queue.get()
|
||||
if r is None:
|
||||
break
|
||||
try:
|
||||
while True:
|
||||
r1 = _queue.get(timeout=0.005)
|
||||
if r1 is None:
|
||||
active = False
|
||||
break
|
||||
else:
|
||||
r += r1
|
||||
except:
|
||||
pass
|
||||
if r is not None:
|
||||
#print(f"{r=}")
|
||||
self.stdout_queue.put(r)
|
||||
self.stdout_queue.put('<END>')
|
||||
for tgt in [rdr, clct]:
|
||||
th = threading.Thread(target=tgt)
|
||||
th.setDaemon(True)
|
||||
th.start()
|
||||
Pump(sout)
|
||||
|
||||
|
||||
def __start_send_callback(self):
|
||||
def func():
|
||||
while self.stdout_queue:
|
||||
line = self.stdout_queue.get()
|
||||
if line == '<END>':
|
||||
if self.stdout_callback != None:
|
||||
self.stdout_callback('end', None)
|
||||
break
|
||||
else:
|
||||
if self.stdout_callback != None:
|
||||
self.stdout_callback('log', line)
|
||||
self.remove_instance(self)
|
||||
|
||||
th = threading.Thread(target=func, args=())
|
||||
th.setDaemon(True)
|
||||
th.start()
|
||||
|
||||
|
||||
|
||||
def process_close(self):
|
||||
try:
|
||||
if self.process is not None and self.process.poll() is None:
|
||||
#import psutil
|
||||
#process = psutil.Process(instance.process.pid)
|
||||
#for proc in instance.process.children(recursive=True):
|
||||
# proc.kill()
|
||||
self.process.kill()
|
||||
except Exception as e:
|
||||
logger.error(f'Exception:{str(e)}')
|
||||
logger.error(traceback.format_exc())
|
||||
finally:
|
||||
try:
|
||||
#self.stdout_queue = None
|
||||
self.process.kill()
|
||||
except: pass
|
||||
|
||||
self.remove_instance(self)
|
||||
|
||||
def input_command(self, cmd):
|
||||
if self.process != None:
|
||||
self.process.stdin.write(f'{cmd}\n')
|
||||
self.process.stdin.flush()
|
||||
|
||||
|
||||
@classmethod
|
||||
def all_process_close(cls):
|
||||
for instance in cls.__instance_list:
|
||||
instance.process_close()
|
||||
cls.__instance_list = []
|
||||
|
||||
|
||||
@classmethod
|
||||
def remove_instance(cls, remove_instance):
|
||||
new = []
|
||||
for instance in cls.__instance_list:
|
||||
if remove_instance.timestamp == instance.timestamp:
|
||||
continue
|
||||
new.append(instance)
|
||||
cls.__instance_list = new
|
||||
|
||||
@classmethod
|
||||
def print(cls):
|
||||
for instance in cls.__instance_list:
|
||||
logger.info(instance.command)
|
||||
|
||||
|
||||
@classmethod
|
||||
def get_instance_by_call_id(cls, call_id):
|
||||
for instance in cls.__instance_list:
|
||||
if instance.call_id == call_id:
|
||||
return instance
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import argparse
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
from . import logger
|
||||
|
||||
|
||||
class SupportSC:
|
||||
LIBRARY_LOADING = False
|
||||
try:
|
||||
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'libsc'))
|
||||
import sc
|
||||
LIBRARY_LOADING = True
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
@classmethod
|
||||
def encode(cls, text, mode=0):
|
||||
try:
|
||||
import sc
|
||||
return sc.encode(text, mode)
|
||||
except Exception as e:
|
||||
logger.error(f'Exception:{str(e)}')
|
||||
logger.error(traceback.format_exc())
|
||||
return None
|
||||
|
||||
|
||||
@classmethod
|
||||
def decode(cls, text):
|
||||
try:
|
||||
import sc
|
||||
return sc.decode(text)
|
||||
except:
|
||||
return None
|
||||
|
||||
@classmethod
|
||||
def load_module(cls, module_name, module_code):
|
||||
try:
|
||||
import sc
|
||||
mod = sc.load_module(module_name, module_code)
|
||||
sys.modules[mod] = mod
|
||||
logger.warning(f"C-LOADING : {module_name}")
|
||||
return mod
|
||||
except Exception as e:
|
||||
logger.error(f'Exception:{str(e)}')
|
||||
logger.error(traceback.format_exc())
|
||||
|
||||
@classmethod
|
||||
def load_module_P(cls, plugin_ins, filename):
|
||||
return cls.load_module_f(plugin_ins.setting['filepath'], filename)
|
||||
|
||||
@classmethod
|
||||
def load_module_f(cls, package_filepath, filename):
|
||||
dirname = os.path.dirname(package_filepath)
|
||||
filepath = os.path.join(dirname, filename + '.pyf')
|
||||
if os.path.exists(filepath) and os.path.exists(filepath):
|
||||
from support import SupportFile
|
||||
code = SupportFile.read_file(filepath)
|
||||
return cls.load_module(f"{os.path.basename(dirname)}.{filename}", code)
|
||||
|
||||
@classmethod
|
||||
def td(self, mediacode, ts, url):
|
||||
try:
|
||||
import sc
|
||||
ret = sc.td1(mediacode, str(ts), url).strip()
|
||||
ret = re.sub('[^ -~]+', '', ret).strip()
|
||||
return ret
|
||||
except:
|
||||
return None
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user