feat: initial version

The initial version of the frontend was written in Angular. It has been
since rewritten from scratch in React. This commit contains the squashed
version of the original write.
pull/69/head
Artem Golub 6 years ago committed by Samuel Rowe
commit a3e9ec0486

@ -0,0 +1,5 @@
.git
Dockerfile
.DS_Store
README.md
env.*

186
.gitignore vendored

@ -0,0 +1,186 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/tmp
/out-tsc
# Only exists if Bazel was run
/bazel-out
# dependencies
node_modules
# profiling files
chrome-profiler-events*.json
speed-measure-plugin*.json
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
yarn-error.log
testem.log
/typings
# System Files
.DS_Store
Thumbs.db
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
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/
cover/
# 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
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .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/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/

@ -0,0 +1,31 @@
# Contributing #
:heart: Thanks for taking the time and for your help improving this project!
## Getting Help ##
If you have a question about nuxx or have encountered problems using it,
start by asking a question on [slack][slack]
## Submitting a Pull Request ##
Do you have an improvement?
1. Submit an [issue][issue] describing your proposed change.
2. I will try to respond to your issue promptly.
3. Fork this repo, develop and test your code changes.
4. Submit a pull request against this repo's `master` branch.
- Include instructions on how to test your changes.
5. Your branch may be merged once all configured checks pass.
## Committing ##
Squash or rebase commits so that all changes from a branch are
committed to master as a single commit. All pull requests are squashed when
merged, but rebasing prior to merge gives you better control over the commit
message.
<!----variables---->
[slack]: https://join.slack.com/t/nuxxapp/shared_invite/zt-fkgoyz5h-CYo5tqAT0CwRZMpuOJYAJA

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

@ -0,0 +1,48 @@
BACKEND_CONTAINER_NAME = nuxx-api
NGINX_CONTAINER_NAME = nuxx-nginx
.PHONY : validate build pull up down down_clean reset run backend_dev shell_backend shell_nginx local_setup local_build
validate :
docker-compose config
build : validate
docker-compose build
pull :
docker-compose pull
up :
@ docker-compose up -d
down :
docker-compose down
down_clean : down
-docker volume rm nuxx_postgres_data
-docker volume rm nuxx_django_static
reset : down
make up
run : validate
docker-compose run $(BACKEND_CONTAINER_NAME) -c "cd /home/app/ && python manage.py runserver 0.0.0.0:9001"
dev_backend :
docker exec -ti $(BACKEND_CONTAINER_NAME) python /home/app/manage.py runserver 0.0.0.0:9001
shell_backend:
docker exec -it ${BACKEND_CONTAINER_NAME} bash
shell_nginx:
docker exec -it ${NGINX_CONTAINER_NAME} bash
local_build:
@ cd ./src/composer && npm install && npm run build_local
local_setup: local_build up
@ echo "Waiting for PostgreSQL..." \
&& sleep 5 \
&& docker exec -it ${BACKEND_CONTAINER_NAME} python /home/app/manage.py makemigrations \
&& docker exec -it ${BACKEND_CONTAINER_NAME} python /home/app/manage.py migrate \
&& docker exec -it ${BACKEND_CONTAINER_NAME} python /home/app/manage.py collectstatic --noinput

@ -0,0 +1,27 @@
# Nuxx Visual Docker Composer
## Local setup
On a Mac/Linux/Windows you need Docker, Docker Compose installed. Optionally GCC to run make commands for convenience, or just run the commands from the Makefile by hand.
To get the tool working locally, just run:
```shell script
$ make local_setup
```
... this command will bring up the backend, the database, sync migrations, and build and serve the Angular app in an Nginx container (for working locally with the tool). For production, you can build and deploy your own images or use mine as a base.
## Local development
- You can run the backend in dev mode with `make backend_dev`.
- For developing the frontend run `cd ./src/composer && npm run start`. It will expect the backend connection on http://localhost:9001/api, but you can change this to your liking in src/composer/src/environment/environment.ts.
## Project roadmap
- Ongoing improvements and features for docker compose yaml generation.
- Kubernetes yaml generation.
- Application stack deployments directly from the web tool and CLI.
- Nuxx CLI.
For anynone interested on trying out deployments, and the CLI, please message me on Slack. These features need some more work and testing.

@ -0,0 +1,38 @@
# vi:syntax=nginx
upstream django {
server backend:9000;
}
server {
listen 80;
listen [::]:80;
server_name localhost;
charset utf-8;
location /static {
alias /home/backend/static;
}
location /admin {
uwsgi_pass django;
include /home/config/uwsgi/uwsgi_params;
}
location /api {
uwsgi_pass django;
include /home/config/uwsgi/uwsgi_params;
}
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

@ -0,0 +1,44 @@
user www-data;
worker_processes 4;
pid /run/nginx.pid;
events {
worker_connections 768;
# multi_accept on;
}
http {
# Basic Settings
tcp_nopush on;
tcp_nodelay on;
#keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log ;
sendfile on;
#tcp_nopush on;
client_max_body_size 20M;
keepalive_timeout 0;
uwsgi_read_timeout 86400;
uwsgi_send_timeout 86400;
# Gzip Settings
gzip on;
gzip_disable "msie6";
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
# Virtual Host Configs
include /etc/nginx/conf.d/*.conf;
#include /etc/nginx/sites-enabled/*;
}

@ -0,0 +1,15 @@
uwsgi_param QUERY_STRING $query_string;
uwsgi_param REQUEST_METHOD $request_method;
uwsgi_param CONTENT_TYPE $content_type;
uwsgi_param CONTENT_LENGTH $content_length;
uwsgi_param REQUEST_URI $request_uri;
uwsgi_param PATH_INFO $document_uri;
uwsgi_param DOCUMENT_ROOT $document_root;
uwsgi_param SERVER_PROTOCOL $server_protocol;
uwsgi_param HTTPS $https if_not_empty;
uwsgi_param REMOTE_ADDR $remote_addr;
uwsgi_param REMOTE_PORT $remote_port;
uwsgi_param SERVER_PORT $server_port;
uwsgi_param SERVER_NAME $server_name;

@ -0,0 +1,63 @@
version: "3.4"
volumes:
postgres-data:
driver: local
name: nuxx_postgres_data
django-static:
driver: local
name: nuxx_django_static
services:
postgres:
container_name: nuxx-postgres
image: postgres:9.6.1
ports:
- 5432:5432
healthcheck:
test: ["CMD-SHELL", "pg_isready"]
interval: 30s
timeout: 30s
retries: 3
volumes:
- postgres-data:/var/lib/postgresql/data
backend:
container_name: nuxx-api
restart: always
build: src/backend
image: nuxxapp/nuxx-api:1.0.0
working_dir: /home
depends_on:
- postgres
links:
- postgres
volumes:
- ./src/backend/server:/home/app/
- django-static:/static/
ports:
- "9001:9001"
env_file:
- local.env
nginx:
container_name: nuxx-nginx
restart: always
image: nginx:latest
depends_on:
- backend
links:
- backend
volumes:
# configs
- ${PWD}/configs/nginx/uwsgi_params:/home/config/uwsgi/uwsgi_params
- ${PWD}/configs/nginx/localhost.conf:/etc/nginx/conf.d/default.conf
- ${PWD}/configs/nginx/nginx.conf:/etc/nginx/nginx.conf
# serve django static stuff
- django-static:/home/backend/static/
# serve composer "built" angular app
- ./src/composer/dist/frontend:/usr/share/nginx/html/
ports:
- "80:80"

@ -0,0 +1,8 @@
#AWS_STORAGE_BUCKET_NAME=
DB_REMOTE=False
#DB_HOST=
#DB_NAME=
#DB_USER=
#DB_PASS=
#SOCIAL_AUTH_CUSTOM_CALLBACK=
#SOCIAL_AUTH_CUSTOM_CALLBACK_PAGE=

@ -0,0 +1,45 @@
FROM python:3.6-stretch
COPY server /home/app
COPY configs/supervisor/backend.conf /etc/supervisor/conf.d/backend.conf
COPY configs/uwsgi /home/config/uwsgi
COPY requirements.txt /home/requirements.txt
COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN apt-get update && \
apt-get install -y \
software-properties-common \
build-essential
RUN apt-get update && \
apt-get install -y \
postgresql \
postgresql-contrib \
wget \
git \
htop \
nano \
curl \
lsof \
supervisor \
dos2unix && \
rm -rf /var/lib/apt/lists/*
RUN useradd uwsgi && adduser uwsgi root
RUN useradd supervisor && adduser supervisor root
RUN pip install --upgrade pip && \
pip install -r /home/requirements.txt
RUN touch /var/log/backend_out.log && \
touch /var/log/django.log
RUN chmod g+w -R /var/log/
RUN dos2unix /docker-entrypoint.sh
RUN chown -R root /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
EXPOSE 9000 9001
ENTRYPOINT ["/docker-entrypoint.sh"]

@ -0,0 +1,8 @@
ORGANIZATION = nuxxapp
CONTAINER = nuxx-api
VERSION = 1.0.0
.PHONY: build
build :
docker build -t $(ORGANIZATION)/$(CONTAINER):$(VERSION) .

@ -0,0 +1,7 @@
[program:app-uwsgi]
user = uwsgi
command = /usr/local/bin/uwsgi --ini /tmp/uwsgi/uwsgi.ini
autostart=true
autorestart=true
killasgroup=true
stopsignal=QUIT

@ -0,0 +1,17 @@
[uwsgi]
ini = :base
socket = 0.0.0.0:9000
master = true
processes = 5
[base]
chdir = /home/app
module = server.wsgi:application
chmod-socket=666
uid = uwsgi
gid = uwsgi
[dev]

@ -0,0 +1,15 @@
uwsgi_param QUERY_STRING $query_string;
uwsgi_param REQUEST_METHOD $request_method;
uwsgi_param CONTENT_TYPE $content_type;
uwsgi_param CONTENT_LENGTH $content_length;
uwsgi_param REQUEST_URI $request_uri;
uwsgi_param PATH_INFO $document_uri;
uwsgi_param DOCUMENT_ROOT $document_root;
uwsgi_param SERVER_PROTOCOL $server_protocol;
uwsgi_param HTTPS $https if_not_empty;
uwsgi_param REMOTE_ADDR $remote_addr;
uwsgi_param REMOTE_PORT $remote_port;
uwsgi_param SERVER_PORT $server_port;
uwsgi_param SERVER_NAME $server_name;

@ -0,0 +1,22 @@
#!/bin/bash
set -e
if [ "${DB_REMOTE}" = False ]; then
echo "Waiting for Postgres..."
while ! pg_isready -h "postgres" -p "5432" > /dev/null 2> /dev/null; do
echo "Connecting to postgres Failed"
sleep 1
done
>&2 echo "Postgres is up - executing command"
fi
rm -rf /tmp/uwsgi && \
mkdir -p /tmp/uwsgi && \
ln -s /home/config/uwsgi/uwsgi.ini /tmp/uwsgi/
/usr/bin/supervisord -n -c /etc/supervisor/supervisord.conf
exec "$@"

@ -0,0 +1,27 @@
requests-oauth==0.4.1
requests-oauthlib==1.3.0
requests==2.23.0
django==3.1.14
django-storages==1.9.1
django-filter==2.2.0
django-cors-headers==3.2.1
django-user-accounts==3.0.0
django-rest-auth==0.9.5
django-prettyjson==0.4.1
djangorestframework==3.11.2
djangorestframework-jwt==1.11.0
django-allauth==0.42.0
psycopg2-binary==2.8.4
zappa==0.48.2
uwsgi==2.0.19.1
django-anymail[mailgun]==7.0.0
botocore==1.15.34
boto3==1.12.34
python-magic==0.4.15
Pygments==2.7.4
pyaml==20.4.0
docker==4.2.0
ruamel.yaml==0.16.10
better_profanity==0.6.1

@ -0,0 +1,89 @@
import re
from django.utils.translation import gettext as _
from django.conf import settings
from allauth.socialaccount.models import SocialLogin
from allauth.socialaccount.providers.base import AuthAction
from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter
from allauth.socialaccount.providers.oauth2.client import OAuth2Client
from allauth.socialaccount.providers.oauth2.views import OAuth2LoginView
from rest_auth.registration.views import SocialConnectView, SocialLoginView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from .serializers import CallbackSerializer
class CallbackMixin:
adapter_class = GitHubOAuth2Adapter
client_class = OAuth2Client
# This is our serializer from above
# You can omit this if you handle CSRF protection in the frontend
serializer_class = CallbackSerializer
# Not the prettiest but single source of truth
@property
def callback_url(self):
url = self.adapter_class(self.request).get_callback_url(
self.request,
None,
)
url = settings.SOCIAL_AUTH_CUSTOM_CALLBACK_PAGE
return url
class CallbackCreate(CallbackMixin, SocialLoginView):
"""
Logs the user in with the providers data.
Creates a new user account if it doesn't exist yet.
"""
class CallbackConnect(CallbackMixin, SocialConnectView):
"""
Connects a provider's user account to the currently logged in user.
"""
# You can override this method here if you don't want to
# receive a token. Omit it otherwise.
def get_response(self):
return Response({'detail': _('Connection completed.')})
class Login(APIView):
adapter_class = GitHubOAuth2Adapter
permission_classes = (AllowAny,)
def post(self, request, format=None):
"""
Returns the URL to the login page of provider's authentication server.
"""
# You should have CSRF protection enabled, see
# https://security.stackexchange.com/a/104390 (point 3).
# Therefore this is a POST endpoint.
# This code is inspired by `OAuth2LoginView.dispatch`.
adapter = self.adapter_class(request)
provider = adapter.get_provider()
app = provider.get_app(request)
view = OAuth2LoginView()
view.request = request
view.adapter = adapter
client = view.get_client(request, app)
# You can modify `action` if you have more steps in your auth flow
action = AuthAction.AUTHENTICATE
auth_params = provider.get_auth_params(request, action)
# You can omit this if you want to validate the state in the frontend
#client.state = SocialLogin.stash_state(request)
url = client.get_redirect_url(adapter.authorize_url, auth_params)
custom_call_back_url = settings.SOCIAL_AUTH_CUSTOM_CALLBACK
if custom_call_back_url:
url = custom_call_back_url
else:
url = re.sub('api.', 'app.', url)
url = re.sub('staging-api.', 'staging-app.', url)
return Response({'url': url})

@ -0,0 +1,44 @@
from django.contrib import admin
from .models import Project, Recipe, UserProfile
class UserProfileAdmin(admin.ModelAdmin):
list_display = (
'user',
)
class ProjectAdmin(admin.ModelAdmin):
list_display = (
'id',
'user',
'name',
'uuid',
'mutable',
'private',
'anonymous',
'date_created',
'date_updated')
search_fields = []
list_filter = ()
class RecipeAdmin(admin.ModelAdmin):
list_display = (
'id',
'user',
'uuid',
'name',
'keywords',
'date_created',
'date_updated')
search_fields = ['name', 'keywords']
list_filter = ()
admin.site.register(UserProfile, UserProfileAdmin)
admin.site.register(Project, ProjectAdmin)
admin.site.register(Recipe, RecipeAdmin)

@ -0,0 +1,5 @@
from django.apps import AppConfig
class ApiConfig(AppConfig):
name = 'api'

@ -0,0 +1,172 @@
import json
import yaml
import requests
from urllib.parse import unquote
from yaml.scanner import ScannerError
from requests.exceptions import HTTPError
from django.http import Http404
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status, generics
from utils.utils import generate_dc, random_string, generate_uuid
from utils.generators import RevereseGenerator
class RepoDetail(generics.GenericAPIView):
permission_classes = ()
def get(self, request):
repo_name = request.query_params.get('r', None)
resp = {}
if repo_name:
if '/' in repo_name:
base_url = "https://hub.docker.com/v2/repositories"
else:
base_url = "https://hub.docker.com/v2/repositories/library"
_results = requests.get(f"{base_url}/{repo_name}")
data = json.dumps(_results.json())
resp = json.loads(data)
return Response(resp)
class RepoSearch(generics.GenericAPIView):
permission_classes = ()
def get(self, request):
base_url = "https://hub.docker.com/v2/search/repositories"
search_string = request.query_params.get('q', None)
page = request.query_params.get('page', 1)
resp = {}
if search_string:
payload = {'query': search_string, 'page': page}
_results = requests.get(f"{base_url}/", params=payload)
data = json.dumps(_results.json())
resp = json.loads(data)
return Response(resp)
class Tags(generics.GenericAPIView):
permission_classes = ()
def get(self, request):
repo_name = request.query_params.get('r', None)
page = request.query_params.get('page', 1)
page_size = request.query_params.get('page_size', 100)
resp = {}
if repo_name:
if '/' in repo_name:
base_url = "https://hub.docker.com/v2/repositories"
else:
base_url = "https://hub.docker.com/v2/repositories/library"
payload = {
'page': page,
'page_size': page_size
}
_results = requests.get(f"{base_url}/{repo_name}/tags/", params=payload)
data = json.dumps(_results.json())
resp = json.loads(data)
return Response(resp)
class Import(generics.GenericAPIView):
def post(self, request, format=None):
resp = {}
request_data = request.data
yaml_string = request_data.get('yaml', None)
project_data = request_data.get('project_data', None)
original_canvas = None
url = request_data.get('url', None)
canvas_lookup_by_s_name = {}
canvas_lookup_by_s_uuid = {}
request_data = None
if project_data:
try:
for canvas_obj in project_data['data']['canvas']:
canvas_lookup_by_s_uuid[canvas_obj['uuid']] = canvas_obj
for service_obj in project_data['data']['services']:
if service_obj['uuid'] in canvas_lookup_by_s_uuid:
canvas_lookup_by_s_name[service_obj['name']] = canvas_lookup_by_s_uuid[service_obj['uuid']]
except KeyError:
original_canvas = None
try:
if yaml_string:
reverse_generator = RevereseGenerator(
yaml_string,
canvas_lookup_by_s_uuid=canvas_lookup_by_s_uuid,
canvas_lookup_by_s_name=canvas_lookup_by_s_name)
resp = reverse_generator.yaml_dict_to_system_obj()
resp['code'] = unquote(yaml_string)
if url:
try:
response = requests.get(url)
if response.status_code == 200:
content = response.text
reverse_generator = RevereseGenerator(
content,
canvas_lookup_by_s_uuid=canvas_lookup_by_s_uuid,
canvas_lookup_by_s_name=canvas_lookup_by_s_name)
resp = reverse_generator.yaml_dict_to_system_obj()
resp['code'] = content
# If the response was successful, no Exception will be raised
response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}') # Python 3.6
except ScannerError as err:
#print(f'Yaml error: {err}')
err_string = f'<div class="error-modal-message">Malformed yaml error, check to make sure your yaml is correct.</div> \
<div class="error-modal-code-wrap"><pre>{err}</pre></div> \
<small class="helper-text">Note! Url import expects a raw yaml string.</small>'
return Response(err_string, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
except Exception as err:
#print(f'Other error occurred: {err}') # Python 3.6
err_string = f'<div class="error-modal-message">Malformed yaml error, check to make sure your yaml is correct.</div> \
<div class="error-modal-code-wrap"><pre>{err}</pre></div> \
<small class="helper-text">Note! Url import expects a raw yaml string.</small>'
return Response(err_string, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
else:
pass
return Response(resp, status=status.HTTP_200_OK)
class Generate(generics.GenericAPIView):
def post(self, request, format=None):
request_data = request.data
version = request_data['data'].get('version', '3')
services = request_data['data'].get('services', None)
volumes = request_data['data'].get('volumes', None)
networks = request_data['data'].get('networks', None)
secrets = request_data['data'].get('secrets', None)
configs = request_data['data'].get('configs', None)
code = generate_dc(
services,
volumes,
networks,
secrets,
configs,
version=version,
return_format='yaml')
resp = {'code': code}
return Response(resp, status=status.HTTP_200_OK)

@ -0,0 +1,61 @@
from django.http import Http404
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status, generics
from .models import Init
from .serializers import InitSerializer
from rest_framework.permissions import IsAuthenticated, IsAdminUser
class CreateList(generics.GenericAPIView):
permission_classes = ()
objects = Init.objects.all()
serializer_class = InitSerializer
def get(self, request):
objects = Init.objects.all()
serializer = InitSerializer(objects, many=True)
return Response(serializer.data)
def post(self, request):
data = request.data.copy()
serializer = InitSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class Detail(generics.GenericAPIView):
def get_object(self, user, obj_id):
try:
return Init.objects.get(id=obj_id)
except Init.DoesNotExist:
raise Http404
def get(self, request, obj_id, format=None):
_object = self.get_object(user=request.user, obj_id=obj_id)
serializer = InitSerializer(_object)
return Response(serializer.data, status=status.HTTP_200_OK)
def put(self, request, obj_id, format=None):
update_data = request.data
_object = self.get_object(user=request.user, obj_id=obj_id)
serializer = InitSerializer(_object, data=update_data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, obj_id, format=None):
_object = self.get_object(user=request.user, obj_id=obj_id)
_object.delete()
return Response(status=status.HTTP_204_NO_CONTENT)

@ -0,0 +1,31 @@
# Generated by Django 3.0.4 on 2020-04-29 12:32
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Project',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True)),
('date_updated', models.DateTimeField(auto_now=True)),
('name', models.CharField(max_length=255)),
('uuid', models.CharField(max_length=255)),
('data', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=dict, help_text='project json')),
],
options={
'verbose_name': 'Project',
'verbose_name_plural': 'Projects',
'ordering': ['-id'],
},
),
]

@ -0,0 +1,18 @@
# Generated by Django 3.0.4 on 2020-05-31 13:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='project',
name='mutable',
field=models.BooleanField(default=True),
),
]

@ -0,0 +1,18 @@
# Generated by Django 3.0.4 on 2020-06-07 10:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0002_project_mutable'),
]
operations = [
migrations.AddField(
model_name='project',
name='owned',
field=models.BooleanField(default=False),
),
]

@ -0,0 +1,18 @@
# Generated by Django 3.0.4 on 2020-06-07 10:47
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0003_project_owned'),
]
operations = [
migrations.RenameField(
model_name='project',
old_name='owned',
new_name='private',
),
]

@ -0,0 +1,26 @@
# Generated by Django 3.0.4 on 2020-06-08 08:38
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('auth', '0011_update_proxy_permissions'),
('api', '0004_auto_20200607_1047'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='profile', serialize=False, to=settings.AUTH_USER_MODEL, verbose_name='user')),
('avatar_url', models.CharField(blank=True, max_length=256, null=True)),
],
options={
'db_table': 'user_profile',
},
),
]

@ -0,0 +1,21 @@
# Generated by Django 3.0.4 on 2020-06-08 09:47
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0005_userprofile'),
]
operations = [
migrations.AddField(
model_name='project',
name='user',
field=models.ForeignKey(blank=True, help_text='user', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='user_projects', to=settings.AUTH_USER_MODEL),
),
]

@ -0,0 +1,18 @@
# Generated by Django 3.0.4 on 2020-06-08 10:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0006_project_user'),
]
operations = [
migrations.AddField(
model_name='project',
name='anonymous',
field=models.BooleanField(default=True),
),
]

@ -0,0 +1,36 @@
# Generated by Django 3.0.4 on 2020-06-25 14:19
from django.conf import settings
import django.contrib.postgres.fields
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0007_project_anonymous'),
]
operations = [
migrations.CreateModel(
name='Recipe',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True)),
('date_updated', models.DateTimeField(auto_now=True)),
('uuid', models.CharField(max_length=255)),
('name', models.CharField(max_length=255)),
('keywords', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, max_length=150), size=None)),
('data', django.contrib.postgres.fields.jsonb.JSONField(blank=True, default=dict, help_text='recipe json')),
('user', models.ForeignKey(blank=True, help_text='user', null=True, on_delete=django.db.models.deletion.CASCADE, related_name='user_recipes', to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'Recipe',
'verbose_name_plural': 'Recipes',
'ordering': ['-id'],
},
),
]

@ -0,0 +1,19 @@
# Generated by Django 3.0.4 on 2020-06-25 16:28
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0008_recipe'),
]
operations = [
migrations.AlterField(
model_name='recipe',
name='keywords',
field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, max_length=150), blank=True, null=True, size=None),
),
]

@ -0,0 +1,25 @@
# Generated by Django 3.0.4 on 2020-06-27 13:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0009_auto_20200625_1628'),
]
operations = [
migrations.AddField(
model_name='recipe',
name='branch',
field=models.CharField(default='master', max_length=255),
preserve_default=False,
),
migrations.AddField(
model_name='recipe',
name='repo',
field=models.CharField(default='', max_length=500),
preserve_default=False,
),
]

@ -0,0 +1,18 @@
# Generated by Django 3.0.4 on 2020-06-27 19:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0010_auto_20200627_1319'),
]
operations = [
migrations.AddField(
model_name='recipe',
name='desc',
field=models.TextField(blank=True, max_length=2500, null=True),
),
]

@ -0,0 +1,24 @@
# Generated by Django 3.0.4 on 2020-06-28 11:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0011_recipe_desc'),
]
operations = [
migrations.AddField(
model_name='recipe',
name='private',
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name='recipe',
name='raw_url',
field=models.CharField(default='', max_length=500),
preserve_default=False,
),
]

@ -0,0 +1,28 @@
# Generated by Django 3.0.4 on 2020-06-28 11:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0012_auto_20200628_1117'),
]
operations = [
migrations.AlterField(
model_name='recipe',
name='branch',
field=models.CharField(blank=True, max_length=255, null=True),
),
migrations.AlterField(
model_name='recipe',
name='raw_url',
field=models.CharField(blank=True, max_length=500, null=True),
),
migrations.AlterField(
model_name='recipe',
name='repo',
field=models.CharField(blank=True, max_length=500, null=True),
),
]

@ -0,0 +1,19 @@
# Generated by Django 3.0.4 on 2020-07-01 05:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0013_auto_20200628_1131'),
]
operations = [
migrations.AddField(
model_name='recipe',
name='url_name',
field=models.CharField(default='', max_length=255),
preserve_default=False,
),
]

@ -0,0 +1,38 @@
# Generated by Django 3.0.4 on 2020-07-01 21:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0014_recipe_url_name'),
]
operations = [
migrations.AlterField(
model_name='recipe',
name='branch',
field=models.CharField(blank=True, max_length=500, null=True),
),
migrations.AlterField(
model_name='recipe',
name='desc',
field=models.TextField(blank=True, null=True),
),
migrations.AlterField(
model_name='recipe',
name='name',
field=models.CharField(max_length=500),
),
migrations.AlterField(
model_name='recipe',
name='raw_url',
field=models.CharField(blank=True, max_length=1000, null=True),
),
migrations.AlterField(
model_name='recipe',
name='url_name',
field=models.CharField(max_length=1000),
),
]

@ -0,0 +1,18 @@
# Generated by Django 3.0.4 on 2020-07-05 14:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0015_auto_20200701_2139'),
]
operations = [
migrations.AlterField(
model_name='recipe',
name='url_name',
field=models.CharField(blank=True, max_length=1000, null=True),
),
]

@ -0,0 +1,9 @@
from django.db import models
class TimeStamp(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True

@ -0,0 +1,187 @@
import hashlib
import requests
from django.db import models
from django.contrib.postgres.fields import ArrayField
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.contrib.postgres.fields import JSONField, ArrayField
from django.dispatch import receiver
from django.db.utils import IntegrityError
from allauth.socialaccount.models import SocialAccount, SocialToken, SocialApp
from allauth.account.signals import user_signed_up, user_logged_in
try:
from django.utils.encoding import force_text
except ImportError:
from django.utils.encoding import force_unicode as force_text
from utils.utils import random_string
from .mixins import TimeStamp
User = get_user_model()
class UserProfile(models.Model):
user = models.OneToOneField(
User,
primary_key=True,
verbose_name='user',
related_name='profile',
on_delete=models.CASCADE)
avatar_url = models.CharField(max_length=256, blank=True, null=True)
def __str__(self):
return force_text(self.user.email)
class Meta():
db_table = 'user_profile'
class Recipe(TimeStamp):
user = models.ForeignKey(
User,
related_name='user_recipes',
on_delete=models.CASCADE,
blank=True,
null=True,
help_text='user'
)
uuid = models.CharField(max_length=255, blank=False, null=False)
name = models.CharField(max_length=500, blank=False, null=False)
url_name = models.CharField(max_length=1000, blank=True, null=True)
desc = models.TextField(blank=True, null=True)
keywords = ArrayField(
models.CharField(max_length=150, blank=True),
blank=True,
null=True,
)
repo = models.CharField(max_length=500, blank=True, null=True)
branch = models.CharField(max_length=500, blank=True, null=True)
raw_url = models.CharField(max_length=1000, blank=True, null=True)
data = JSONField(default=dict, blank=True, help_text="recipe json")
# not listed publicly, needs a direct link
private = models.BooleanField(default=False, blank=False, null=False)
class Meta(object):
verbose_name = 'Recipe'
verbose_name_plural = 'Recipes'
ordering = ['-id']
def __str__(self):
return "{}".format(self.id)
class Project(TimeStamp):
user = models.ForeignKey(
User,
related_name='user_projects',
on_delete=models.CASCADE,
blank=True,
null=True,
help_text='user'
)
name = models.CharField(max_length=255, blank=False, null=False)
uuid = models.CharField(max_length=255, blank=False, null=False)
data = JSONField(default=dict, blank=True, help_text="project json")
# anonymous projects that can not be mutitated, only cloned anonymously or authenticated
mutable = models.BooleanField(default=True, blank=False, null=False)
# not listed publicly, needs a direct link
private = models.BooleanField(default=False, blank=False, null=False)
# for projects created anonymously, stay anonymous forever
# if a user is logged in, they can clone the anonymous project to make it their own
anonymous = models.BooleanField(default=True, blank=False, null=False)
class Meta(object):
verbose_name = 'Project'
verbose_name_plural = 'Projects'
ordering = ['-id']
def __str__(self):
return "{}".format(self.id)
@receiver(post_save, sender=SocialToken)
def get_user_email(sender, instance=None, created=False, **kwargs):
django_user_obj = instance.account.user
access_token = instance.token
email = None
with requests.Session() as session:
params = {'access_token': access_token}
headers = {'Connection': 'close'}
req_return = session.get('https://api.github.com/user/emails', params=params, headers=headers)
status_code = req_return.status_code
if status_code == 200:
req_return_data = req_return.json()[0]
email = req_return_data['email']
session.close()
try:
if email:
django_user_obj.email = email
django_user_obj.save()
except IntegrityError as e:
print('Exception:', e)
@receiver(user_signed_up)
def social_login_fname_lname_profilepic(sociallogin=None, user=None, **kwargs):
preferred_avatar_size_pixels=256
email_first_part = user.email.split("@")[0]
username_postfix = random_string(5)
username = f"{email_first_part}_{username_postfix}"
user.username = username
picture_url = "http://www.gravatar.com/avatar/{0}?s={1}".format(
hashlib.md5(user.email.encode('UTF-8')).hexdigest(),
preferred_avatar_size_pixels
)
if sociallogin:
# Extract first / last names from social nets and store on User record
if sociallogin.account.provider == 'twitter':
name = sociallogin.account.extra_data['name']
user.first_name = name.split()[0]
user.last_name = name.split()[1]
if sociallogin.account.provider == 'facebook':
f_name = sociallogin.account.extra_data['first_name']
l_name = sociallogin.account.extra_data['last_name']
if f_name:
user.first_name = f_name
if l_name:
user.last_name = l_name
#verified = sociallogin.account.extra_data['verified']
picture_url = "http://graph.facebook.com/{0}/picture?width={1}&height={1}".format(
sociallogin.account.uid, preferred_avatar_size_pixels)
if sociallogin.account.provider == 'google':
f_name = sociallogin.account.extra_data['given_name']
l_name = sociallogin.account.extra_data['family_name']
if f_name:
user.first_name = f_name
if l_name:
user.last_name = l_name
#verified = sociallogin.account.extra_data['verified_email']
picture_url = sociallogin.account.extra_data['picture']
if sociallogin.account.provider == 'github':
#name = sociallogin.account.extra_data['name']
#user.first_name = name.split()[0]
#user.last_name = name.split()[1]
picture_url = sociallogin.account.extra_data['avatar_url']
user.save()
profile = UserProfile(user=user, avatar_url=picture_url)
profile.save()

@ -0,0 +1,29 @@
from rest_framework import permissions
class IsOwner(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Instance must have an attribute named `owner`.
return obj.user == request.user
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
Assumes the model instance has an `owner` attribute.
"""
def has_object_permission(self, request, view, obj):
# Read permissions are allowed to any request,
# so we'll always allow GET, HEAD or OPTIONS requests.
if request.method in permissions.SAFE_METHODS:
return True
# Instance must have an attribute named `owner`.
return obj.owner == request.user

@ -0,0 +1,146 @@
from django.http import Http404
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status, generics
from .models import Project
from .serializers import ProjectSerializer, ProjectUpdateSerializer
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from utils.utils import random_string
from utils.pagination import CustomPagination
from .permissions import IsOwner
class ListPrivate(generics.ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = ProjectSerializer
pagination_class = CustomPagination
queryset = Project.objects.all()
ordering_fields = ('date_updated', 'date_created')
def filter_queryset(self, queryset):
user = self.request.user
queryset_filters = {'user': user}
queryset = Project.objects.filter(**queryset_filters)
return queryset
class DetailPrivate(generics.GenericAPIView):
permission_classes = [IsAuthenticated & IsOwner]
def get_object(self, user, uuid):
try:
return Project.objects.get(uuid=uuid)
except Project.DoesNotExist:
raise Http404
"""
def get(self, request, uuid, format=None):
user = request.user
_object = self.get_object(user=user, uuid=uuid)
self.check_object_permissions(request, _object)
serializer = ProjectSerializer(_object)
return Response(serializer.data, status=status.HTTP_200_OK)
"""
def put(self, request, uuid, format=None):
user = request.user
update_data = request.data
_object = self.get_object(user=user, uuid=uuid)
self.check_object_permissions(request, _object)
serializer = ProjectUpdateSerializer(_object, data=update_data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, uuid, format=None):
_object = self.get_object(user=request.user, uuid=uuid)
_object.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
class CreateList(generics.ListAPIView):
permission_classes = ()
serializer_class = ProjectSerializer
pagination_class = CustomPagination
queryset = Project.objects.all()
ordering_fields = ('date_updated', 'date_created')
def filter_queryset(self, queryset):
queryset_filters = {'user': None, 'private': False}
queryset = Project.objects.filter(**queryset_filters)
return queryset
def post(self, request):
user = request.user
data = request.data.copy()
data['user'] = user.id
data['uuid'] = random_string()
if request.user.is_authenticated:
data['anonymous'] = False
data['private'] = True
serializer = ProjectSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class Detail(generics.GenericAPIView):
def get_object(self, user, uuid):
try:
_project = Project.objects.get(uuid=uuid)
if _project.user == None and _project.private == False:
return _project
if user.is_authenticated:
if user == _project.user:
return _project
raise Http404
except Project.DoesNotExist:
raise Http404
def get(self, request, uuid, format=None):
_object = self.get_object(user=request.user, uuid=uuid)
serializer = ProjectSerializer(_object)
return Response(serializer.data, status=status.HTTP_200_OK)
def put(self, request, uuid, format=None):
update_data = request.data
_object = self.get_object(user=request.user, uuid=uuid)
if request.user.is_authenticated:
update_data['anonymous'] = False
update_data['private'] = True
serializer = ProjectUpdateSerializer(_object, data=update_data)
# prevent anonymous projects from getting owned by an authenticated user
if serializer.is_valid():
if request.user.is_authenticated and _object.user != request.user:
update_data['user'] = request.user
update_data['uuid'] = random_string()
serializer.create(validated_data=update_data)
else:
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, uuid, format=None):
_object = self.get_object(user=request.user, uuid=uuid)
_object.delete()
return Response(status=status.HTTP_204_NO_CONTENT)

@ -0,0 +1,205 @@
import html
import requests
from yaml.scanner import ScannerError
from requests.exceptions import HTTPError
from django.http import Http404
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status, generics
from .models import Recipe
from .serializers import RecipeSerializer, RecipeUpdateSerializer, RecipeReadSerializer
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from utils.utils import random_string, clean_string
from utils.pagination import CustomPagination
from utils.generators import RevereseGenerator
from .permissions import IsOwner
class CreateList(generics.ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = RecipeReadSerializer
pagination_class = CustomPagination
queryset = Recipe.objects.all()
ordering_fields = ('date_updated', 'date_created')
def filter_queryset(self, queryset):
user = self.request.user
queryset_filters = {'user': user}
queryset = Recipe.objects.filter(**queryset_filters)
return queryset
def post(self, request):
user = request.user
data = request.data.copy()
data['user'] = user.id
data['uuid'] = random_string()
data['data'] = data.get('data', {})
data['url_name'] = clean_string(data['name'])
repo = data.get('repo', None)
branch = data.get('branch', 'master')
raw_url = data.get('raw_url', None)
try:
if not repo and not raw_url:
return Response({'message': 'Empty repo or raw url!'}, status=status.HTTP_400_BAD_REQUEST)
if repo:
_recipe_obj = Recipe.objects.get(repo=repo, branch=branch)
else:
_recipe_obj = Recipe.objects.get(raw_url=raw_url)
return Response({'message': 'Recipe already exists!'}, status=status.HTTP_400_BAD_REQUEST)
except Recipe.DoesNotExist:
serializer = RecipeSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class DetailByUrlName(generics.GenericAPIView):
def get_object(self, url_name):
try:
_recipe = Recipe.objects.get(url_name=url_name)
return _recipe
except Recipe.DoesNotExist:
raise Http404
def get(self, request, url_name, format=None):
_object = self.get_object(url_name=url_name)
serialized = RecipeReadSerializer(_object).data
return Response(serialized, status=status.HTTP_200_OK)
class Detail(generics.GenericAPIView):
def get_object(self, user, uuid):
try:
_recipe = Recipe.objects.get(user=user.id, uuid=uuid)
return _recipe
except Recipe.DoesNotExist:
raise Http404
def get_object_by_uuid(self, uuid):
try:
_recipe = Recipe.objects.get(uuid=uuid)
return _recipe
except Recipe.DoesNotExist:
raise Http404
def get(self, request, uuid, format=None):
resp = {}
_object = self.get_object_by_uuid(uuid=uuid)
raw_url = _object.raw_url
canvas_lookup_by_s_name = {}
canvas_lookup_by_s_uuid = {}
try:
if raw_url:
try:
response = requests.get(raw_url)
if response.status_code == 200:
content = response.text
reverse_generator = RevereseGenerator(
content,
canvas_lookup_by_s_uuid=canvas_lookup_by_s_uuid,
canvas_lookup_by_s_name=canvas_lookup_by_s_name)
resp = reverse_generator.yaml_dict_to_system_obj()
resp['name'] = _object.name
resp['code'] = content
# If the response was successful, no Exception will be raised
response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}') # Python 3.6
except ScannerError as err:
#print(f'Yaml error: {err}')
err_string = f'<div class="error-modal-message">Malformed yaml error, check to make sure your yaml is correct.</div> \
<div class="error-modal-code-wrap"><pre>{err}</pre></div> \
<small class="helper-text">Note! Url import expects a raw yaml string.</small>'
return Response(err_string, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
except Exception as err:
#print(f'Other error occurred: {err}') # Python 3.6
err_string = f'<div class="error-modal-message">Malformed yaml error, check to make sure your yaml is correct.</div> \
<div class="error-modal-code-wrap"><pre>{err}</pre></div> \
<small class="helper-text">Note! Url import expects a raw yaml string.</small>'
return Response(err_string, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
else:
pass
return Response(resp, status=status.HTTP_200_OK)
def put(self, request, uuid, format=None):
update_data = request.data
_object = self.get_object(user=request.user, uuid=uuid)
update_data['desc'] = html.escape(update_data['desc'])
update_data['url_name'] = clean_string(update_data['name'])
serializer = RecipeUpdateSerializer(_object, data=update_data)
if serializer.is_valid():
if request.user.is_authenticated and _object.user != request.user:
update_data['user'] = request.user
update_data['uuid'] = random_string()
serializer.create(validated_data=update_data)
else:
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, uuid, format=None):
_object = self.get_object(user=request.user, uuid=uuid)
_object.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
class Popular(generics.ListAPIView):
permission_classes = ()
serializer_class = RecipeReadSerializer
pagination_class = CustomPagination
queryset = Recipe.objects.all()
ordering_fields = ('date_updated', 'date_created')
def filter_queryset(self, queryset):
queryset_filters = {'private': False}
queryset = Recipe.objects.filter(**queryset_filters)
return queryset
class Search(generics.GenericAPIView):
permission_classes = ()
serializer_class = RecipeReadSerializer
pagination_class = CustomPagination
def get(self, request, format=None):
search_string = request.query_params.get('q', None)
search_string_list = search_string.split(',')
resp = {}
if search_string:
_results = Recipe.objects.filter(keywords__contains=search_string_list)
page = self.paginate_queryset(_results)
if page is not None:
serializer = self.get_serializer(page, many=True)
result = self.get_paginated_response(serializer.data)
resp = result.data # pagination data
else:
serializer = self.get_serializer(queryset, many=True)
resp = serializer.data
#serialized = RecipeSerializer(_results, many=True)
#resp = serialized.data
return Response(resp)

@ -0,0 +1,103 @@
import html
from django.core.exceptions import PermissionDenied
from django.utils.translation import gettext as _
from allauth.socialaccount.models import SocialLogin
from rest_auth.registration.serializers import SocialLoginSerializer
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.authentication import SessionAuthentication
from rest_framework import serializers
from .models import Project, Recipe
from rest_framework.authtoken.models import Token
class TokenSerializer(serializers.ModelSerializer):
class Meta:
model = Token
fields = ('key', 'user')
class RecipeSerializer(serializers.ModelSerializer):
class Meta(object):
model = Recipe
fields = '__all__'
class RecipeReadSerializer(serializers.BaseSerializer):
def to_representation(self, instance):
return {
'uuid': instance.uuid,
'name': instance.name,
'url_name': instance.url_name,
'desc': html.unescape(instance.desc),
'keywords': instance.keywords,
'data': instance.data,
'repo': instance.repo,
'branch': instance.branch,
'raw_url': instance.raw_url,
'private': instance.private
}
class RecipeUpdateSerializer(serializers.ModelSerializer):
class Meta(object):
model = Recipe
fields = [
'name',
'url_name',
'desc',
'keywords',
'data',
'repo',
'raw_url',
'private'
]
class ProjectSerializer(serializers.ModelSerializer):
class Meta(object):
model = Project
fields = '__all__'
class ProjectUpdateSerializer(serializers.ModelSerializer):
class Meta(object):
model = Project
fields = [
'name',
'mutable',
'private',
'anonymous',
'data'
]
class CallbackSerializer(SocialLoginSerializer):
'''
state = serializers.CharField()
def validate_state(self, value):
"""
Checks that the state is equal to the one stored in the session.
"""
try:
SocialLogin.verify_and_unstash_state(
self.context['request'],
value,
)
# Allauth raises PermissionDenied if the validation fails
except PermissionDenied:
raise ValidationError(_('State did not match.'))
return value
'''

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

@ -0,0 +1,98 @@
from django.urls import include, path, re_path
from django.views.generic import TemplateView
from . import projectViews, projectViews, recipeViews, generatorViews
from rest_auth.registration.views import (
SocialAccountListView, SocialAccountDisconnectView
)
from . import LoginViews as views
EMAIL_CONFIRMATION = r'^auth/confirm-email/(?P<key>[-:\w]+)$'
PASSWORD_RESET = (
r'^auth/password/reset/confirm/'
'(?P<uidb64>[0-9A-Za-z_\-]+)-'
'(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$'
)
# NOTE: If you change this URL you have to update the callback URL
# in the OAuth providers' accounts, too
OAUTH_CALLBACK = 'auth/social/{provider}/callback'
# github URL patterns
github_urlpatterns = [
path('auth-server/', views.Login.as_view(), name='github_auth_server'),
path(
'login/',
views.CallbackCreate.as_view(),
name='github_callback_login',
),
path(
'connect/',
views.CallbackConnect.as_view(),
name='github_callback_connect',
),
]
# default URL patterns
api_urlpatterns = [
path('project/private/', projectViews.ListPrivate.as_view()),
path('project/private/<str:uuid>/', projectViews.DetailPrivate.as_view()),
path('project/', projectViews.CreateList.as_view()),
path('project/<str:uuid>/', projectViews.Detail.as_view()),
path('recipe/', recipeViews.CreateList.as_view()),
path('recipe/name/<str:url_name>/', recipeViews.DetailByUrlName.as_view()),
path('recipe/popular/', recipeViews.Popular.as_view()),
path('recipe/search/', recipeViews.Search.as_view()),
path('recipe/<str:uuid>/', recipeViews.Detail.as_view()),
path('generate/', generatorViews.Generate.as_view()),
path('import/', generatorViews.Import.as_view()),
path('repo/search/', generatorViews.RepoSearch.as_view()),
path('repo/detail/', generatorViews.RepoDetail.as_view()),
path('tags/', generatorViews.Tags.as_view()),
# non social auth endpoints
path('auth/', include('rest_auth.urls')),
path('auth/registration/', include('rest_auth.registration.urls')),
path('auth/social/github/', include(github_urlpatterns)),
path(
'auth/user/accounts/',
SocialAccountListView.as_view(),
name='social_account_list',
),
path(
'auth/user/accounts/<int:pk>/disconnect/',
SocialAccountDisconnectView.as_view(),
name='social_account_disconnect',
),
]
urlpatterns = [
# The SPA serves these URLs but the backend has to know
# where they point to for reference, don't change the url names.
re_path(
EMAIL_CONFIRMATION,
TemplateView.as_view(),
name='account_confirm_email',
),
re_path(
PASSWORD_RESET,
TemplateView.as_view(),
name='password_reset_confirm',
),
path(
OAUTH_CALLBACK.format(provider='github'),
TemplateView.as_view(),
name='github_callback',
),
# This has to be last because rest_auth.registration.urls
# also defines `account_confirm_email` what we override above.
path('api/', include(api_urlpatterns)),
]

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

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

@ -0,0 +1,256 @@
"""
Django settings for server project.
Generated by 'django-admin startproject' using Django 3.0.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
import datetime
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SITE_ID = 1
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '*otro=7@1!e2(-qx6*rd$%l5q01ki-0$-=4)%#6e=v(yf!8@d('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = os.getenv(
'DEBUG',
'true').lower() == 'true'
SITE_ID = 1
ALLOWED_HOSTS = [
'*'
]
CORS_ORIGIN_ALLOW_ALL = True
# Application definition
INSTALLED_APPS = [
'corsheaders',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'allauth',
'allauth.account',
'rest_auth.registration',
'rest_auth',
'allauth.socialaccount',
'allauth.socialaccount.providers.github',
'allauth.socialaccount.providers.google',
'storages',
'api',
'utils',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'server.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'server.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DB_REMOTE = os.environ.get(
'DB_REMOTE',
'False'
).lower() == 'true'
if DB_REMOTE:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'HOST': os.getenv('DB_HOST', None),
'NAME': os.getenv('DB_NAME', None),
'USER': os.getenv('DB_USER', None),
'PASSWORD': os.getenv('DB_PASS', None),
'PORT': 5432,
}
}
else:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'HOST': 'postgres',
'NAME': 'postgres',
'USER': 'postgres',
'PASSWORD': 'postgres',
'PORT': 5432,
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
DEFAULT_FILE_STORAGE = 'server.server..settings.storage_backends.PublicStorage'
# AWS
AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME', None)
AWS_S3_FILE_OVERWRITE = True
AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME
AWS_S3_OBJECT_PARAMETERS = {
'CacheControl': 'max-age=86400',
}
AWS_DEFAULT_REGION = os.environ.get(
'AWS_DEFAULT_REGION',
'us-east-1'
)
AWS_LOCATION = 'static'
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
STATICFILES_DIRS = []
if AWS_STORAGE_BUCKET_NAME:
STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION)
STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
else:
STATIC_URL = '/static/'
STATIC_ROOT = '/static/'
# Rest Framework.
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.TokenAuthentication'
),
'DEFAULT_PERMISSION_CLASSES': (),
'DEFAULT_FILTER_BACKENDS': (
'django_filters.rest_framework.DjangoFilterBackend',
),
'DEFAULT_RENDERER_CLASSES': (
'rest_framework.renderers.JSONRenderer',
)
}
AUTHENTICATION_BACKENDS = (
"django.contrib.auth.backends.ModelBackend",
"allauth.account.auth_backends.AuthenticationBackend"
)
# JWT.
JWT_AUTH = {
'JWT_RESPONSE_PAYLOAD_HANDLER': 'organization.utils.jwt_response_payload_handler',
# How long the original token is valid for.
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=30),
# Allow refreshing of tokens.
'JWT_ALLOW_REFRESH': True,
# This is the maximum time AFTER the token was issued that
# it can be refreshed. expired tokens can't be refreshed.
'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
}
# Auth.
# this will try to send an email if an email is added to the user object
ACCOUNT_EMAIL_VERIFICATION = "none"
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_AUTHENTICATION_METHOD = 'email'
REST_USE_JWT = True
SOCIAL_AUTH_CUSTOM_CALLBACK = os.getenv('SOCIAL_AUTH_CUSTOM_CALLBACK', None)
SOCIAL_AUTH_CUSTOM_CALLBACK_PAGE = os.getenv('SOCIAL_AUTH_CUSTOM_CALLBACK_PAGE', None)

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

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

@ -0,0 +1,5 @@
from django.apps import AppConfig
class UtilsConfig(AppConfig):
name = 'utils'

@ -0,0 +1,458 @@
import yaml
import ast
from urllib.parse import unquote
#from anytree import Node, AnyNode, RenderTree
from .utils import generate_uuid
class RevereseGenerator():
def __init__(self, yaml_str, canvas_lookup_by_s_name=None, canvas_lookup_by_s_uuid=None):
self.yaml_str = yaml_str
self.canvas_lookup_by_s_name = canvas_lookup_by_s_name
self.canvas_lookup_by_s_uuid = canvas_lookup_by_s_uuid
self.service_uuid_lookup = {}
self.volume_uuid_lookup = {}
self.network_uuid_lookup = {}
self.initial_top = 130
self.initial_left = 200
self.services_counter = 0
self.canvas_obj = {
"top": 512,
"left": 434,
"uuid": "",
"zoomLevel": 1
}
self.volume_obj = {
"name": "",
"volume_name": "",
"uuid": "",
"driver": None,
"labels": [],
"external": False,
"driver_opts": None,
"external_name": None
}
self.network_obj = {
"name": "",
"object_name": "",
"uuid": "",
"driver": "local",
"labels": [],
"external": False,
"driver_opts": [],
"network_name": "",
"external_name": None
}
self.build_obj = {
"context": "",
"dockerfile": "",
"args": [],
"cache_from": [],
"labels": [],
"network": "",
"shm_size": "",
"target": "",
}
self.port_obj = {
"published": "80",
"target": "8080",
"mode": "host",
"protocol": "TCP"
}
self.resp = {
'name': 'Imported project',
'id': None,
'date_created': None,
'date_updated': None,
'uuid': None,
'data': {
'canvas': [],
'version': '3',
'volumes': [],
'networks': [],
'services': [],
'secrets': [],
'configs': []
},
'mutable': True
}
def populate_service_lookup_table(self, services):
for service_k, _ in services.items():
obj_uuid = generate_uuid()
self.service_uuid_lookup[service_k] = obj_uuid
def parse_top_level_volumes(self, volumes):
"""
Parses top level volume objects only, excluding path mounts.
"""
if not volumes:
return
for volume_k, volume_v in volumes.items():
obj_uuid = generate_uuid()
volume_obj_cp = self.volume_obj.copy()
volume_obj_cp['uuid'] = obj_uuid
volume_obj_cp['name'] = volume_k
try:
external = volume_v.get('external', False)
if external:
external_name = external.get('name', None)
volume_obj_cp['external'] = True
volume_obj_cp['external_name'] = external_name
except (AttributeError, KeyError):
pass
try:
volume_obj_cp['volume_name'] = volume_v.get('name', None)
except (AttributeError, KeyError):
pass
try:
volume_obj_cp['driver'] = volume_v.get('driver', None)
except (AttributeError, KeyError):
pass
try:
volume_obj_cp['labels'] = []
volume_labels = volume_v.get('labels', None)
for lbl_key, lbl_val in volume_labels.items():
volume_obj_cp['labels'].append({
'key': lbl_key,
'value': lbl_val
})
except (AttributeError, KeyError):
pass
self.volume_uuid_lookup[volume_k] = obj_uuid
self.resp['data']['volumes'].append(volume_obj_cp)
def to_key_val_pairs(self, items):
ret = []
if isinstance(items, list):
for item in items:
item_parts = item.split('=')
ret.append({'key': item_parts[0], 'value': item_parts[1]})
if isinstance(items, dict):
try:
for _key, _val in items.items():
ret.append({'key': _key, 'value': _val})
except AttributeError:
pass
return ret
def parse_build_obj(self, build):
ret = self.build_obj.copy()
if isinstance(build, str):
ret['build'] = build
else:
for _key, _val in build.items():
if _key in ['args', 'cache_from', 'labels']:
if _val:
ret[_key] = self.to_key_val_pairs(_val)
else:
if _val:
ret[_key] = _val
return ret
def parse_top_level_networks(self, networks):
if not networks:
return
for network_k, network_v in networks.items():
obj_uuid = generate_uuid()
network_obj_cp = self.network_obj.copy()
network_obj_cp['name'] = network_k
network_obj_cp['uuid'] = obj_uuid
try:
network_obj_cp['object_name'] = network_v.get('name', None)
network_obj_cp['driver'] = network_v.get('driver', None)
network_obj_cp['external'] = network_v.get('external', False)
except (AttributeError, KeyError):
pass
try:
network_obj_cp['labels'] = self.to_key_val_pairs(network_v['labels'])
except Exception:
pass
try:
network_obj_cp['driver_opts'] = self.to_key_val_pairs(network_v['driver_opts'])
except Exception:
pass
self.network_uuid_lookup[network_k] = obj_uuid
self.resp['data']['networks'].append(network_obj_cp)
def yaml_dict_to_system_obj(self):
yaml_str = unquote(self.yaml_str)
_dict = yaml.safe_load(yaml_str)
if not _dict:
return self.resp
version = _dict.get('version', '3')
services = _dict.get('services', None)
volumes = _dict.get('volumes', None)
networks = _dict.get('networks', None)
secrets = _dict.get('secrets', None)
configs = _dict.get('configs', None)
self.resp['data']['version'] = version
# populate lookup tables, and parse top level objects
self.parse_top_level_volumes(volumes)
self.parse_top_level_networks(networks)
if not services:
return self.resp
self.populate_service_lookup_table(services)
# construct services
for service_k, service_v in services.items():
service_obj = {}
# canvas object for each service object
try:
canvas_obj_cp = self.canvas_lookup_by_s_name[service_k]
except KeyError:
canvas_obj_cp = self.canvas_obj.copy()
canvas_obj_cp['uuid'] = self.service_uuid_lookup[service_k]
# construct service obj
image = service_v.get('image', None)
if image:
image_parts = service_v['image'].split(':')
service_obj['image'] = image_parts[0]
try:
service_obj['tag'] = image_parts[1]
except IndexError:
service_obj['tag'] = 'latest'
service_obj['name'] = service_k
service_obj['uuid'] = self.service_uuid_lookup[service_k]
build = service_v.get('build', None)
if build:
service_obj['build'] = self.parse_build_obj(build)
try:
service_obj['command'] = service_v['command']
except Exception:
pass
try:
service_obj['working_dir'] = service_v['working_dir']
except Exception:
pass
try:
service_obj['environment'] = []
envs = service_v['environment']
if isinstance(envs, list):
for env_set in envs:
env_set_parts = env_set.split('=')
service_obj['environment'].append({
'key': env_set_parts[0],
'value': env_set_parts[1]
})
else:
for env_key, env_val in service_v['environment'].items():
service_obj['environment'].append({
'key': env_key,
'value': env_val
})
except Exception:
pass
try:
service_obj['labels'] = []
service_labels = service_v.get('labels', None)
if isinstance(service_labels, list):
for label_set in service_labels:
label_set_parts = label_set.split('=')
service_obj['labels'].append({
'key': label_set_parts[0],
'value': label_set_parts[1]
})
if isinstance(service_labels, dict):
for lbl_key, lbl_val in service_labels.items():
service_obj['labels'].append({
'key': lbl_key,
'value': lbl_val
})
except Exception as e:
print(e)
try:
service_obj['ports'] = []
for port in service_v['ports']:
if isinstance(port, str):
port_parts = port.split(':')
port_obj_cp = self.port_obj.copy()
port_obj_cp['published'] = port_parts[0]
port_obj_cp['protocol'] = 'tcp'
port_obj_cp['mode'] = 'host'
try:
port_obj_cp['target'] = port_parts[1]
except IndexError:
port_obj_cp['target'] = None
service_obj['ports'].append(port_obj_cp)
if isinstance(port, dict):
service_obj['ports'].append(port)
except KeyError:
pass
try:
service_obj['volumes'] = []
for volume in service_v['volumes']:
volume_obj_uuid = generate_uuid()
volume_obj_cp = self.volume_obj.copy()
volume_obj_cp['uuid'] = volume_obj_uuid
volume_obj_cp['name'] = volume_obj_uuid
volume_parts = volume.split(':')
if len(volume_parts) > 1:
try:
volume_id = self.volume_uuid_lookup[volume_parts[0]]
if volume_id:
service_obj['volumes'].append({
"volume": volume_id,
"destination": volume_parts[1]
})
except KeyError:
service_obj['volumes'].append({
"relativePathSource": volume_parts[0],
"destination": volume_parts[1]
})
else:
service_obj['volumes'].append({
"relativePathSource": volume_parts[0],
"destination": volume_parts[0]
})
except KeyError:
pass
try:
service_obj['networks'] = []
for network in service_v['networks']:
service_obj['networks'].append(self.network_uuid_lookup[network])
except KeyError:
pass
try:
service_obj['depends_on'] = []
for dep in service_v['depends_on']:
service_obj['depends_on'].append(self.service_uuid_lookup[dep])
except KeyError:
pass
if float(version) < 2:
try:
service_obj['links'] = []
for dep in service_v['links']:
service_obj['links'].append(self.service_uuid_lookup[dep])
except KeyError:
pass
try:
service_obj['container_name'] = service_v['container_name']
except KeyError:
pass
try:
service_obj['restart'] = service_v['restart']
except KeyError:
pass
try:
deploy = service_v['deploy']
service_obj['deploy'] = deploy
'''
try:
placement_preferences = deploy['placement']['preferences']
service_obj['deploy']['placement']['preferences'] = self.to_key_val_pairs(placement_preferences)
except Exception:
pass
'''
try:
labels = deploy['labels']
service_obj['deploy']['labels'] = self.to_key_val_pairs(labels)
except Exception:
pass
except KeyError:
pass
# append to object lists
self.resp['data']['services'].append(service_obj)
self.resp['data']['canvas'].append(canvas_obj_cp)
levels = {}
for parsed_service in self.resp['data']['services']:
dep_count = len(parsed_service['depends_on'])
try:
levels[dep_count].append({
'uuid': parsed_service['uuid'],
'name': parsed_service['name']
})
except KeyError:
levels[dep_count] = []
levels[dep_count].append({
'uuid': parsed_service['uuid'],
'name': parsed_service['name']
})
canvas = []
initial_top = 20
initial_left = 20
iter_node_count = 0
for _, l_values in levels.items():
for l_value in l_values:
if not iter_node_count % 5:
initial_left = 20
initial_top += 200
initial_left += 200
try:
canvas_obj_cp = self.canvas_lookup_by_s_name[l_value['name']]
canvas_obj_cp['uuid'] = l_value['uuid']
canvas.append(canvas_obj_cp)
except KeyError:
canvas_obj_cp = self.canvas_obj.copy()
canvas_obj_cp['top'] = initial_top
canvas_obj_cp['left'] = initial_left
canvas_obj_cp['uuid'] = l_value['uuid']
canvas_obj_cp['zoomLevel'] = 0.7
canvas.append(canvas_obj_cp)
iter_node_count += 1
self.resp['data']['canvas'] = list(reversed(canvas))
return self.resp

@ -0,0 +1,9 @@
from django.db import models
class TimeStamp(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True

@ -0,0 +1,18 @@
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class CustomPagination(PageNumberPagination):
page_size_query_param = 'page_size'
page_size = 30
def get_paginated_response(self, data):
return Response({
'links': {
'next': self.get_next_link(),
'previous': self.get_previous_link()
},
'total': self.page.paginator.count,
'current_total': len(data),
'results': data
})

@ -0,0 +1,737 @@
import io
import os
import re
import sys
import json
import boto3
import copy
import random
import string
import stat
import decimal
import time
import pyaml
import docker
import yaml
import ast
import uuid
import ruamel.yaml
from better_profanity import profanity
from io import StringIO
from collections import OrderedDict
from time import mktime
from datetime import date, datetime
from operator import itemgetter
from botocore.exceptions import ClientError
from ruamel.yaml import YAML
from ruamel.yaml.tokens import CommentToken
from ruamel.yaml.comments import CommentedMap, CommentedSeq
from ruamel.yaml.scalarstring import PreservedScalarString, SingleQuotedScalarString, DoubleQuotedScalarString
try:
import textwrap
textwrap.indent
except AttributeError: # undefined function (wasn't added until Python 3.3)
def indent(text, amount, ch=' '):
padding = amount * ch
return ''.join(padding+line for line in text.splitlines(True))
else:
def indent(text, amount, ch=' '):
return textwrap.indent(text, amount * ch)
def sequence_indent_four(s):
ret_val = ''
first_indent = True
for line in s.splitlines(True):
ls = line.lstrip()
indent = len(line) - len(ls)
if indent == 2 and first_indent == False:
ret_val += "\n"
ret_val += line
if indent == 2 and first_indent == True:
first_indent = False
return ret_val
def sequence_indent_one(s):
ret_val = ''
first_indent = True
for line in s.splitlines(True):
ls = line.lstrip()
indent = len(line) - len(ls)
if indent == 0 and first_indent == False:
ret_val += "\n"
ret_val += line
if indent == 0 and first_indent == True:
first_indent = False
return ret_val
def format_quotes(s):
if '\'' in s:
return SingleQuotedScalarString(s.replace("'", ''))
if '"' in s:
return DoubleQuotedScalarString(s.replace('"', ''))
return SingleQuotedScalarString(s)
def format_volumes_top_level(volumes, compose_version):
ret = {}
for volume in volumes:
volume_custom_name = volume.get('volume_name', None)
volume_driver = volume.get('driver', None)
external = volume.get('external', False)
external_name = volume.get('external_name', False)
ret[volume['name']] = {}
if external:
ret[volume['name']]['external'] = True
if external_name:
ret[volume['name']]['external'] = {
'name': external_name
}
if volume_custom_name:
ret[volume['name']]['name'] = volume_custom_name
if volume_driver:
ret[volume['name']]['driver'] = volume_driver
if compose_version in [2, 3]:
labels = volume.get('labels', None)
if labels:
ret[volume['name']]['labels'] = {}
for label in labels:
ret[volume['name']]['labels'][label['key']] = format_quotes(label['value'])
if not ret[volume['name']]:
ret[volume['name']] = None
return ret
def format_networks_top_level(networks, compose_version):
ret = {}
for network in networks:
network_custom_name = network.get('object_name', None)
network_driver = network.get('driver', None)
network_custom_driver = network.get('driver_custom', False)
external = network.get('external', False)
external_name = network.get('external_name', False)
driver_opts = network.get('driver_opts', None)
ret[network['name']] = {}
if external:
ret[network['name']]['external'] = True
ret[network['name']]['name'] = external_name
if network_custom_name:
ret[network['name']]['name'] = network_custom_name
if network_driver:
ret[network['name']]['driver'] = network_driver
if driver_opts:
ret[network['name']]['driver_opts'] = {}
for driver_opt in driver_opts:
ret[network['name']]['driver_opts'][driver_opt['key']] = format_quotes(driver_opt['value'])
if compose_version in [2, 3]:
labels = network.get('labels', None)
if labels:
ret[network['name']]['labels'] = {}
for label in labels:
ret[network['name']]['labels'][label['key']] = format_quotes(label['value'])
if not ret[network['name']]:
ret[network['name']] = None
return ret
def format_key_val_pairs(pairs):
ret = {}
for pair_part in pairs:
ret[pair_part['key']] = pair_part['value']
return ret
def format_ports(ports):
service_ports_formatted = []
for port in ports:
port_published = port['published']
port_target = port['target']
formatter_string = DoubleQuotedScalarString(f"{port_published}")
if port_target:
formatter_string = DoubleQuotedScalarString(f"{port_published}:{port_target}")
service_ports_formatted.append(formatter_string)
return service_ports_formatted
def format_volumes(service_volumes, volumes):
ret = []
for service_volume in service_volumes:
for volume in volumes:
if 'volume' in service_volume:
if service_volume['volume'] == volume['uuid']:
volume_mount_str = f"{volume['name']}:{service_volume['destination']}"
ret.append(volume_mount_str)
if 'relativePathSource' in service_volume:
volume_mount_str = f"{service_volume['relativePathSource']}:{service_volume['destination']}"
ret.append(volume_mount_str)
return ret
def format_networks(service_networks, networks):
ret = []
if service_networks:
for service_network_uuid in service_networks:
for network in networks:
if service_network_uuid == network['uuid']:
network_str = f"{network['name']}"
ret.append(network_str)
return ret
def clean_string(string):
string = " ".join(re.findall(r"[a-zA-Z0-9]+", string))
string = string.lower()
string = string.replace(' ', '-')
return string
def format_command_string(command):
"""
Format command list of string for v1, v2, v3.
param: command: string
return: list
"""
command_list = []
command = str(command)
command_list = command.replace("\n", "")
try:
# try to convert the string into list
command_list = ast.literal_eval(command_list)
except (ValueError, SyntaxError) as e:
#print('ValueError SyntaxError', e)
# special case
if "\n" in command:
command_list = command.split("\n")
else:
return command
except Exception as e:
#print('Exception', e)
return command
if len(command_list) > 1:
longest_str = max(command_list, key=len)
if len(longest_str) >= 30:
return [format_quotes(i) for i in command_list]
return FSlist(command_list)
return command_list[0]
def format_build(specified_version, build):
if isinstance(build, str):
return build
build_str = build.get('build', None)
context_str = build.get('context', None)
if specified_version < 2:
if build_str:
return build_str
elif context_str:
return context_str
else:
return None
if build_str:
return build_str
ret = {}
for _key, _val in build.items():
if _key in ['args', 'cache_from', 'labels']:
if _val:
ret[_key] = format_key_val_pairs(_val)
else:
if _val:
ret[_key] = _val
return ret
def _remove_missing_and_underscored_keys(d):
if not d: return d
for key in list(d.keys()):
if isinstance(d[key], list):
d[key] = list(filter(None, d[key]))
if not d.get(key):
del d[key]
elif isinstance(d[key], dict):
d[key] = _remove_missing_and_underscored_keys(d[key])
if d[key] == None or d[key] == {}:
del d[key]
return d
def format_deploy(specified_version, deploy):
ret = deploy
try:
placement_preferences = deploy['placement']['preferences']
ret['placement']['preferences'] = format_key_val_pairs(placement_preferences)
except Exception:
pass
try:
labels = deploy['labels']
ret['labels'] = format_key_val_pairs(labels)
except Exception:
pass
ret = _remove_missing_and_underscored_keys(ret)
return ret
def get_version(verion):
try:
return int(verion)
except ValueError:
return float(verion)
def format_services_version_one(specified_version, services, volumes, networks):
services_formatted = {}
for service in services:
service_formatted = {}
image = service.get('image', None)
if image:
image_tag = "latest"
try:
image_tag = service['tag']
service_formatted['image'] = f"{image}:{image_tag}"
except KeyError:
service_formatted['image'] = f"{image}"
try:
if service['container_name']:
service_formatted['container_name'] = service['container_name']
except KeyError:
pass
try:
if service['restart']:
service_formatted['restart'] = service['restart']
except KeyError:
pass
try:
if service['command']:
service_formatted['command'] = format_command_string(service['command'])
except KeyError:
pass
try:
if service['entrypoint']:
service_formatted['entrypoint'] = format_command_string(service['entrypoint'])
except KeyError:
pass
try:
if service['working_dir']:
service_formatted['working_dir'] = service['working_dir']
except KeyError:
pass
try:
if service['ports']:
service_formatted['ports'] = format_ports(service['ports'])
except KeyError:
pass
try:
links = service.get('links', [])
if links:
service_formatted['links'] = []
for link in links:
for service_obj in services:
if link == service_obj['uuid']:
service_formatted['links'].append(f"{service_obj['name']}")
except KeyError:
pass
try:
if service['environment']:
envs = service['environment']
service_formatted['environment'] = format_key_val_pairs(envs)
except KeyError:
pass
try:
service_volumes = service['volumes']
formatted_volumes = format_volumes(service_volumes, volumes)
if formatted_volumes:
service_formatted['volumes'] = formatted_volumes
else:
del service_formatted['volumes']
except KeyError:
pass
try:
build = format_build(specified_version, service['build'])
if build:
service_formatted['build'] = build
except KeyError:
pass
services_formatted[service['name']] = service_formatted
return services_formatted
def format_services_version_three(specified_version, services, volumes, networks):
services_formatted = {}
for service in services:
service_formatted = {}
image = service.get('image', None)
if image:
image_tag = "latest"
try:
image_tag = service['tag']
service_formatted['image'] = f"{image}:{image_tag}"
except KeyError:
service_formatted['image'] = f"{image}"
try:
if service['container_name']:
service_formatted['container_name'] = service['container_name']
except KeyError:
pass
try:
if service['restart']:
service_formatted['restart'] = service['restart']
except KeyError:
pass
try:
if service['command']:
service_formatted['command'] = format_command_string(service['command'])
except KeyError:
pass
try:
if service['entrypoint']:
service_formatted['entrypoint'] = format_command_string(service['entrypoint'])
except KeyError:
pass
try:
working_dir_str = service['working_dir']
if working_dir_str:
service_formatted['working_dir'] = working_dir_str
except KeyError:
pass
try:
if service['ports']:
service_formatted['ports'] = format_ports(service['ports'])
except KeyError:
pass
try:
if service['depends_on']:
depends_on = service['depends_on']
service_formatted['depends_on'] = []
for depends in depends_on:
for service_obj in services:
if depends == service_obj['uuid']:
service_formatted['depends_on'].append(f"{service_obj['name']}")
except KeyError:
pass
try:
if service['environment']:
envs = service['environment']
service_formatted['environment'] = format_key_val_pairs(envs)
except KeyError:
pass
try:
service_volumes = service['volumes']
formatted_volumes = format_volumes(service_volumes, volumes)
if formatted_volumes:
service_formatted['volumes'] = formatted_volumes
else:
del service_formatted['volumes']
except KeyError:
pass
try:
labels = service.get('labels', None)
if labels:
service_formatted['labels'] = {}
for label in labels:
service_formatted['labels'][label['key']] = format_quotes(label['value'])
except KeyError:
pass
try:
service_networks = service.get('networks', [])
formatted_networks = format_networks(service_networks, networks)
if formatted_networks:
service_formatted['networks'] = formatted_networks
else:
del service_formatted['networks']
except KeyError:
pass
try:
build = format_build(specified_version, service['build'])
if build:
service_formatted['build'] = build
except KeyError:
pass
if int(float(specified_version)) >= 3:
try:
deploy = format_deploy(specified_version, service['deploy'])
if deploy:
service_formatted['deploy'] = deploy
except KeyError:
pass
services_formatted[service['name']] = service_formatted
return services_formatted
def FSlist(l): # concert list into flow-style (default is block style)
from ruamel.yaml.comments import CommentedSeq
double_quoted_list = [DoubleQuotedScalarString(x) for x in l]
cs = CommentedSeq(double_quoted_list)
cs.fa.set_flow_style()
return cs
def generate_dc(services, volumes, networks, secrets, configs, version="3", return_format='yaml'):
if return_format == 'yaml':
s = io.StringIO()
ret_yaml = YAML()
ret_yaml.indent(mapping=2, sequence=4, offset=2)
ret_yaml.explicit_start = True
specified_version = get_version(version)
base_version = int(specified_version)
if services:
if base_version in [2, 3]:
ret_yaml.dump({'version': DoubleQuotedScalarString(specified_version)}, s)
ret_yaml.explicit_start = False
s.write('\n')
services_formatted = format_services_version_three(specified_version, services, volumes, networks)
ret_yaml.dump({'services': services_formatted}, s, transform=sequence_indent_four)
if base_version == 1:
ret_yaml.dump({'version': DoubleQuotedScalarString(specified_version)}, s)
ret_yaml.explicit_start = False
s.write('\n')
services_formatted = format_services_version_one(specified_version, services, volumes, networks)
ret_yaml.dump(services_formatted, s, transform=sequence_indent_one)
s.write('\n')
if base_version in [3, 2]:
if networks:
networks_formatted = format_networks_top_level(networks, version)
ret_yaml.dump({'networks': networks_formatted}, s)
s.write('\n')
if volumes:
volumes_formatted = format_volumes_top_level(volumes, version)
ret_yaml.dump({'volumes': volumes_formatted}, s)
s.write('\n')
if secrets:
ret_yaml.dump({'secrets': secrets}, s)
s.write('\n')
if configs:
ret_yaml.dump({'configs': configs}, s)
s.write('\n')
s.seek(0)
return s
def generate(cname):
c = docker.from_env()
try:
cid = [x.short_id for x in c.containers.list() if cname == x.name or x.short_id in cname][0]
except IndexError:
print("That container is not running.")
sys.exit(1)
cattrs = c.containers.get(cid).attrs
# Build yaml dict structure
cfile = {}
cfile[cattrs['Name'][1:]] = {}
ct = cfile[cattrs['Name'][1:]]
values = {
'cap_add': cattrs['HostConfig']['CapAdd'],
'cap_drop': cattrs['HostConfig']['CapDrop'],
'cgroup_parent': cattrs['HostConfig']['CgroupParent'],
'container_name': cattrs['Name'][1:],
'devices': cattrs['HostConfig']['Devices'],
'dns': cattrs['HostConfig']['Dns'],
'dns_search': cattrs['HostConfig']['DnsSearch'],
'environment': cattrs['Config']['Env'],
'extra_hosts': cattrs['HostConfig']['ExtraHosts'],
'image': cattrs['Config']['Image'],
'labels': cattrs['Config']['Labels'],
'links': cattrs['HostConfig']['Links'],
#'log_driver': cattrs['HostConfig']['LogConfig']['Type'],
#'log_opt': cattrs['HostConfig']['LogConfig']['Config'],
'logging': {'driver': cattrs['HostConfig']['LogConfig']['Type'], 'options': cattrs['HostConfig']['LogConfig']['Config']},
'networks': {x: {'aliases': cattrs['NetworkSettings']['Networks'][x]['Aliases']} for x in cattrs['NetworkSettings']['Networks'].keys()},
'security_opt': cattrs['HostConfig']['SecurityOpt'],
'ulimits': cattrs['HostConfig']['Ulimits'],
'volumes': cattrs['HostConfig']['Binds'],
'volume_driver': cattrs['HostConfig']['VolumeDriver'],
'volumes_from': cattrs['HostConfig']['VolumesFrom'],
'cpu_shares': cattrs['HostConfig']['CpuShares'],
'cpuset': cattrs['HostConfig']['CpusetCpus']+','+cattrs['HostConfig']['CpusetMems'],
'entrypoint': cattrs['Config']['Entrypoint'],
'user': cattrs['Config']['User'],
'working_dir': cattrs['Config']['WorkingDir'],
'domainname': cattrs['Config']['Domainname'],
'hostname': cattrs['Config']['Hostname'],
'ipc': cattrs['HostConfig']['IpcMode'],
'mac_address': cattrs['NetworkSettings']['MacAddress'],
'mem_limit': cattrs['HostConfig']['Memory'],
'memswap_limit': cattrs['HostConfig']['MemorySwap'],
'privileged': cattrs['HostConfig']['Privileged'],
'restart': cattrs['HostConfig']['RestartPolicy']['Name'],
'read_only': cattrs['HostConfig']['ReadonlyRootfs'],
'stdin_open': cattrs['Config']['OpenStdin'],
'tty': cattrs['Config']['Tty']
}
networklist = c.networks.list()
networks = {}
for network in networklist:
if network.attrs['Name'] in values['networks'].keys():
networks[network.attrs['Name']] = {'external': (not network.attrs['Internal'])}
# Check for command and add it if present.
if cattrs['Config']['Cmd'] != None:
values['command'] = " ".join(cattrs['Config']['Cmd']),
# Check for exposed/bound ports and add them if needed.
try:
expose_value = list(cattrs['Config']['ExposedPorts'].keys())
ports_value = [cattrs['HostConfig']['PortBindings'][key][0]['HostIp']+':'+cattrs['HostConfig']['PortBindings'][key][0]['HostPort']+':'+key for key in cattrs['HostConfig']['PortBindings']]
# If bound ports found, don't use the 'expose' value.
if (ports_value != None) and (ports_value != "") and (ports_value != []) and (ports_value != 'null') and (ports_value != {}) and (ports_value != "default") and (ports_value != 0) and (ports_value != ",") and (ports_value != "no"):
for index, port in enumerate(ports_value):
if port[0] == ':':
ports_value[index] = port[1:]
values['ports'] = ports_value
else:
values['expose'] = expose_value
except (KeyError, TypeError):
# No ports exposed/bound. Continue without them.
ports = None
# Iterate through values to finish building yaml dict.
for key in values:
value = values[key]
if (value != None) and (value != "") and (value != []) and (value != 'null') and (value != {}) and (value != "default") and (value != 0) and (value != ",") and (value != "no"):
ct[key] = value
return cfile, networks
def generate_uuid():
return uuid.uuid4().hex[:6].upper()
def random_string(string_length=10):
"""
Generate a random string of fixed length
:param string_length: integer
:return: string
"""
final_string = ''.join(random.choice(
string.ascii_uppercase +
string.ascii_lowercase +
string.digits) for _ in range(string_length))
final_string = profanity.censor(final_string, '').lower()
return final_string
def generate_rand_string():
rand_string = "".join(random.choice(
string.ascii_uppercase +
string.ascii_lowercase +
string.digits) for _ in range(16))
return rand_string

@ -0,0 +1,13 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false

@ -0,0 +1,27 @@
# Composer
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 9.0.6.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--configuration=production` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).

@ -0,0 +1,137 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"frontend": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/frontend",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.app.json",
"aot": true,
"assets": ["src/favicon.ico", "src/assets"],
"styles": [
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"scripts": [
"./node_modules/jsplumb/dist/js/jsplumb.min.js"
]
},
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true,
"budgets": [
{
"type": "initial",
"maximumWarning": "2mb",
"maximumError": "5mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "6kb",
"maximumError": "10kb"
}
]
},
"staging": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.staging.ts"
}
]
},
"local": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.local.ts"
}
]
}
}
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "frontend:build"
},
"configurations": {
"production": {
"browserTarget": "frontend:build:production"
},
"staging": {
"browserTarget": "frontend:build:staging"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "frontend:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"main": "src/test.ts",
"polyfills": "src/polyfills.ts",
"tsConfig": "tsconfig.spec.json",
"karmaConfig": "karma.conf.js",
"assets": ["src/favicon.ico", "src/assets"],
"styles": ["./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", "src/styles.scss"],
"scripts": []
}
},
"lint": {
"builder": "@angular-devkit/build-angular:tslint",
"options": {
"tsConfig": ["tsconfig.app.json", "tsconfig.spec.json", "e2e/tsconfig.json"],
"exclude": ["**/node_modules/**"]
}
},
"e2e": {
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "frontend:serve"
},
"configurations": {
"production": {
"devServerTarget": "frontend:serve:production"
}
}
}
}
}
},
"defaultProject": "frontend"
}

@ -0,0 +1,12 @@
# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.
# For additional information regarding the format and rule options, please see:
# https://github.com/browserslist/browserslist#queries
# You can see what browsers were selected by your queries by running:
# npx browserslist
> 0.5%
last 2 versions
Firefox ESR
not dead
not IE 9-11 # For IE 9-11 support, remove 'not'.

@ -0,0 +1,32 @@
// @ts-check
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
/**
* @type { import("protractor").Config }
*/
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./src/**/*.e2e-spec.ts'
],
capabilities: {
browserName: 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require('ts-node').register({
project: require('path').join(__dirname, './tsconfig.json')
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};

@ -0,0 +1,23 @@
import { AppPage } from './app.po';
import { browser, logging } from 'protractor';
describe('workspace-project App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('composer app is running!');
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});

@ -0,0 +1,11 @@
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo(): Promise<unknown> {
return browser.get(browser.baseUrl) as Promise<unknown>;
}
getTitleText(): Promise<string> {
return element(by.css('app-root .content span')).getText() as Promise<string>;
}
}

@ -0,0 +1,13 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/e2e",
"module": "commonjs",
"target": "es5",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}

@ -0,0 +1,32 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/frontend'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};

File diff suppressed because it is too large Load Diff

@ -0,0 +1,66 @@
{
"name": "composer",
"version": "1.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve --port=4300 --disable-host-check",
"build": "ng build --configuration=production",
"build_local": "ng build --configuration=local",
"staging": "ng serve --configuration=staging --port=4300",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "~9.1.4",
"@angular/cdk": "^9.2.2",
"@angular/common": "~9.1.4",
"@angular/compiler": "~9.1.4",
"@angular/core": "~11.0.5",
"@angular/flex-layout": "^9.0.0-beta.29",
"@angular/forms": "~9.1.4",
"@angular/material": "^9.2.2",
"@angular/platform-browser": "~9.1.4",
"@angular/platform-browser-dynamic": "~9.1.4",
"@angular/router": "~9.1.4",
"@ctrl/ngx-codemirror": "3.1.3",
"@ngrx/effects": "^9.1.1",
"@ngrx/store": "^9.1.1",
"angular-split": "^3.0.3",
"codemirror": "5.58.2",
"highlight.js": "^10.4.1",
"jsplumb": "^2.13.2",
"marked": "^4.0.10",
"nan": "^2.14.1",
"ngx-highlightjs": "^4.1.0-beta",
"panzoom": "^9.2.4",
"rxjs": "^6.5.5",
"rxjs-compat": "^6.5.5",
"tslib": "^1.10.0",
"uuid": "^8.0.0",
"zone.js": "~0.10.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.901.4",
"@angular/cli": "~9.1.4",
"@angular/compiler-cli": "~9.1.4",
"@angular/language-service": "~9.1.4",
"@types/highlight.js": "^9.12.3",
"@types/jasmine": "~3.5.0",
"@types/jasminewd2": "~2.0.3",
"@types/node": "^12.11.1",
"codelyzer": "^5.1.2",
"jasmine-core": "~3.5.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~6.3.16",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage-istanbul-reporter": "~2.1.0",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.2",
"protractor": "~5.4.3",
"ts-node": "~8.3.0",
"tslint": "~5.18.0",
"typescript": "~3.7.5"
}
}

@ -0,0 +1,57 @@
import { NgModule } from '@angular/core'
import { Routes, RouterModule } from '@angular/router'
import { HomeComponent } from './core/components/home/home.component'
import { LoginComponent } from './login/login.component'
import { RegistrationComponent } from './registration/registration.component'
import { CallbackComponent } from './callback/callback.component'
const routes: Routes = [
{
path: '',
children: [
{
path: '',
component: HomeComponent
},
{
path: ':uuid',
component: HomeComponent
},
],
},
{
path: 'compose',
children: [
{
path: '',
component: HomeComponent
},
{
path: ':uuid',
component: HomeComponent
},
],
},
{
path: 'auth',
children: [
{
path: 'social/github/callback',
component: CallbackComponent
},
{
path: 'login',
component: LoginComponent
},
{
path: 'registration',
component: RegistrationComponent
}
],
},
]
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}

@ -0,0 +1 @@
<router-outlet></router-outlet>

@ -0,0 +1,35 @@
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'composer'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('composer');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement;
expect(compiled.querySelector('.content span').textContent).toContain('composer app is running!');
});
});

@ -0,0 +1,11 @@
import { Component } from '@angular/core';
import { AuthGuard } from './core/helpers/auth.gourd'
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'Compose';
constructor(private authGuard: AuthGuard) {}
}

@ -0,0 +1,160 @@
import { BrowserModule } from '@angular/platform-browser'
import { NgModule } from '@angular/core'
import { StoreModule } from '@ngrx/store'
import { EffectsModule } from '@ngrx/effects'
import { ProjectEffects } from './core/store/effects/projects.effects'
import { AppRoutingModule } from './app-routing.module'
import { AppComponent } from './app.component'
import { MatButtonModule } from '@angular/material/button'
import { MatSidenavModule } from '@angular/material/sidenav'
import { MatCardModule } from '@angular/material/card'
import { MatFormFieldModule } from '@angular/material/form-field'
import { MatIconModule } from '@angular/material/icon'
import { MatInputModule } from '@angular/material/input'
import { MatDialogModule } from '@angular/material/dialog'
import { MatSelectModule } from '@angular/material/select'
import { MatTabsModule } from '@angular/material/tabs'
import { ClipboardModule } from '@angular/cdk/clipboard'
import { DragDropModule } from '@angular/cdk/drag-drop'
import { MatButtonToggleModule } from '@angular/material/button-toggle'
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner'
import { MatSliderModule } from '@angular/material/slider'
import { MatTooltipModule } from '@angular/material/tooltip'
import { MatCheckboxModule } from '@angular/material/checkbox'
import { MatMenuModule } from '@angular/material/menu'
import { MatStepperModule } from '@angular/material/stepper'
import { MatAutocompleteModule } from '@angular/material/autocomplete'
import { RepoSearchComponent, DialogDetails, DialogAddCustom } from './core/components/repo-search/repo-search.component'
import { HeaderComponent } from './core/components/header/header.component'
import { CodeViewComponent } from './core/components/code-view/code-view.component'
import { CanvasComponent } from './core/components/canvas/canvas.component'
import { HomeComponent } from './core/components/home/home.component'
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { projectReducer } from './core/store/project.reducer'
import { globalSpinnerReducer } from './core/store/reducers/global-spinner.reducer'
import { globalDialogReducer } from './core/store/reducers/global-dialog.reducer'
import { globalConfigurationReducer } from './core/store/reducers/global-app-configuration.reducer'
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'
import { FlexLayoutModule } from '@angular/flex-layout'
import { HighlightModule, HIGHLIGHT_OPTIONS, HighlightOptions } from 'ngx-highlightjs'
import { ManageProjectDialogComponent } from './core/components/dialogs/manage-project-dialog/manage-project-dialog.component'
import { ManageVolumesDialogComponent } from './core/components/dialogs/manage-volumes-dialog/manage-volumes-dialog.component'
import { SpinnerComponent } from './core/components/widgets/spinner/spinner.component'
import { CheckCircleComponent } from './core/components/widgets/check-circle/check-circle.component'
import { AngularSplitModule } from 'angular-split'
import { ConfirmDialogComponent } from './core/components/dialogs/confirm-dialog/confirm-dialog.component'
import { NodeComponent } from './core/components/canvas/jsplumb/node/node.component'
import { NodeService } from './core/components/canvas/jsplumb/node.service'
import { EventEmitterService } from './core/services/event-emitter.service'
import { MarkedPipe } from './core/pipe/marked.pipe'
import { TruncateTextPipe } from './core/pipe/truncate-text.pipe'
import { KeyValueComponent } from './core/components/common/key-value/key-value/key-value.component'
import { ManageNetworksDialogComponent } from './core/components/dialogs/manage-networks-dialog/manage-networks-dialog.component'
import { SideBarComponent } from './core/components/side-bar/side-bar.component'
import { LoginComponent } from './login/login.component'
import { RegistrationComponent } from './registration/registration.component'
import { JwtInterceptor} from './core/helpers/jwt.interceptor'
import { ErrorInterceptor } from './core/helpers/error.interceptor'
import { ManageUserDialogComponent } from './core/components/dialogs/manage-user-dialog/manage-user-dialog.component'
import { CallbackComponent } from './callback/callback.component'
import { ImportDialogComponent } from './core/components/dialogs/import-dialog/import-dialog.component'
import { GlobalDialogComponent } from './core/components/dialogs/global-dialog/global-dialog.component'
import { CodemirrorModule } from '@ctrl/ngx-codemirror';
import { RecipeComponent, DialogPublishRecipe, DialogRecipeDetails } from './core/components/recipe/recipe.component';
import { BuildDialogComponent } from './core/components/dialogs/build-dialog/build-dialog.component';
import { DeployDialogComponent } from './core/components/dialogs/deploy-dialog/deploy-dialog.component';
export function getHighlightLanguages() {
return {
yaml: () => import('highlight.js/lib/languages/yaml'),
}
}
@NgModule({
declarations: [
AppComponent,
RepoSearchComponent,
DialogDetails,
DialogAddCustom,
HeaderComponent,
CodeViewComponent,
CanvasComponent,
HomeComponent,
ManageProjectDialogComponent,
ManageVolumesDialogComponent,
SpinnerComponent,
CheckCircleComponent,
ConfirmDialogComponent,
NodeComponent,
MarkedPipe,
TruncateTextPipe,
KeyValueComponent,
ManageNetworksDialogComponent,
SideBarComponent,
LoginComponent,
RegistrationComponent,
ManageUserDialogComponent,
CallbackComponent,
ImportDialogComponent,
GlobalDialogComponent,
RecipeComponent,
DialogPublishRecipe,
DialogRecipeDetails,
BuildDialogComponent,
DeployDialogComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatSidenavModule,
MatCardModule,
MatFormFieldModule,
MatInputModule,
MatDialogModule,
MatButtonModule,
MatIconModule,
MatSelectModule,
MatTabsModule,
MatButtonToggleModule,
MatProgressSpinnerModule,
MatSliderModule,
MatTooltipModule,
MatCheckboxModule,
MatMenuModule,
MatStepperModule,
MatAutocompleteModule,
DragDropModule,
HighlightModule,
FlexLayoutModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
StoreModule.forRoot({ project: projectReducer, globalSpinnerState: globalSpinnerReducer, globalError: globalDialogReducer, globalAppConfiguration: globalConfigurationReducer }),
ClipboardModule,
EffectsModule.forRoot([ProjectEffects]),
AngularSplitModule.forRoot(),
CodemirrorModule
],
providers: [
{
provide: HIGHLIGHT_OPTIONS,
useValue: <HighlightOptions>{
lineNumbers: true,
languages: getHighlightLanguages(),
}
},
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
EventEmitterService,
NodeService,
],
bootstrap: [AppComponent],
})
export class AppModule {}

@ -0,0 +1,7 @@
import { Project, GlobalDialog, GlobalAppConfiguration } from './core/store/models';
export interface AppState {
project: Project;
globalSpinnerState: boolean;
globalError: GlobalDialog;
globalAppConfiguration: GlobalAppConfiguration;
}

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CallbackComponent } from './callback.component';
describe('CallbackComponent', () => {
let component: CallbackComponent;
let fixture: ComponentFixture<CallbackComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CallbackComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CallbackComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

@ -0,0 +1,31 @@
import { Component, OnInit } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { AuthenticationService } from '../core/services/authentication.service'
import { first } from 'rxjs/operators'
@Component({
selector: 'app-callback',
templateUrl: './callback.component.html',
styleUrls: ['./callback.component.scss']
})
export class CallbackComponent implements OnInit {
constructor(private activetedRoute: ActivatedRoute, private router: Router, private authenticationService: AuthenticationService) { }
ngOnInit(): void {
const code = this.activetedRoute.snapshot.queryParams['code']
if (code) {
this.authenticationService.gitHubLogin(code)
.pipe(first())
.subscribe(
data => {
const lastPageBeferoLogin = localStorage.getItem('lastPageBeforeRegistrationOrLogin')
lastPageBeferoLogin ? this.router.navigate([lastPageBeferoLogin]) : this.router.navigate(['/'])
});
} else {
const lastPageBeferoLogin = localStorage.getItem('lastPageBeforeRegistrationOrLogin')
lastPageBeferoLogin ? this.router.navigate([lastPageBeferoLogin]) : this.router.navigate(['/'])
}
}
}

@ -0,0 +1,24 @@
<div class="canvas-tools" fxLayout="column" fxLayoutGap="10px">
<button mat-raised-button (click)="manageProjectVolumes()">
Volumes
</button>
<button mat-raised-button (click)="manageProjectNetworks()">
Networks
</button>
</div>
<div fxFill class="canvas-boundary">
<div
id="canvas"
class="container"
#nodeContainer
[ngStyle]="{ width: containerSize + 'px', height: containerSize + 'px' }"
(mousedown)="onMouseDown($event)"
(mousemove)="onMouseMove($event)"
(mouseup)="onMouseUp()"
(mousewheel)="onMouseWheel($event)"
>
<ng-template #nodes></ng-template>
</div>
</div>

@ -0,0 +1,38 @@
.canvas-tools {
position: absolute;
top: 10px;
right: 10px;
z-index: 2;
}
.canvas-box {
position: absolute;
width: 150px;
height: 150px;
padding: 10px;
border: solid 1px #ccc;
color: rgba(0, 0, 0, 0.87);
cursor: move;
transition: box-shadow 200ms cubic-bezier(0, 0, 0.2, 1);
background-color: white;
box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2), 0 2px 2px 0 rgba(0, 0, 0, 0.14),
0 1px 5px 0 rgba(0, 0, 0, 0.12);
}
.canvas-box:active {
box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
0 8px 10px 1px rgba(0, 0, 0, 0.14), 0 3px 14px 2px rgba(0, 0, 0, 0.12);
}
.canvas-boundary {
outline: none;
overflow: hidden;
position: relative;
}
#canvas {
top: -100px;
left: -100px;
position: absolute;
overflow: hidden;
}

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CanvasComponent } from './canvas.component';
describe('CanvasComponent', () => {
let component: CanvasComponent;
let fixture: ComponentFixture<CanvasComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CanvasComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CanvasComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

@ -0,0 +1,229 @@
import { Observable } from 'rxjs/Observable'
import { Store } from '@ngrx/store'
import { Component, OnInit, OnDestroy, ViewChild, ViewContainerRef, AfterViewInit, ElementRef } from '@angular/core'
import { MatDialog } from '@angular/material/dialog'
import { AppState } from './../../../app.state'
import { Project, Service, IPosition, Volume } from './../../store/models'
import { ManageVolumesDialogComponent } from '../dialogs/manage-volumes-dialog/manage-volumes-dialog.component'
import { ManageNetworksDialogComponent } from '../dialogs/manage-networks-dialog/manage-networks-dialog.component'
import { jsPlumb } from 'jsplumb'
import { EventEmitterService } from '../../services/event-emitter.service'
import { NodeService } from './jsplumb/node.service'
import * as ProjectActions from './../../store/project.actions'
import * as GlobalSpinnerActions from './../../store/actions/global-spinner.actions'
import panzoom from 'panzoom'
import { Subject } from 'rxjs'
import { takeUntil } from 'rxjs/operators'
@Component({
selector: 'app-canvas',
templateUrl: './canvas.component.html',
styleUrls: ['./canvas.component.scss'],
})
export class CanvasComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('nodeContainer') nodeContainer: ElementRef;
project: Observable<Project>
services: Service[]
positions: IPosition[]
volumes: Volume[]
projectData = {}
jsPlumbInstance
nodes = []
connections = []
onFirstLoad = false
prevPanState: any
dragStatus = false
zoomLevel = 1
zoomLevelUnit = 0.065
minZoomLevel = 0.5
maxZoomLevel = 2
containerSize = 3000
private unSubscribe$ = new Subject()
private unSubscribeEventService: Function
@ViewChild('nodes', { read: ViewContainerRef, static: true }) viewContainerRef: ViewContainerRef
constructor(
private store: Store<AppState>,
private dialog: MatDialog,
private eventEmitterService: EventEmitterService,
private nodeService: NodeService,
) {
this.project = this.store.select('project')
this.project.pipe(takeUntil(this.unSubscribe$)).subscribe((v) => {
if(v.services && v.canvas && v.volumes) {
this.services = v.services
this.positions = v.canvas
this.volumes = v.volumes
if (this.onFirstLoad == true) {
let zoomLevel = 1
this.nodeService.clear()
this.positions.forEach((p: IPosition) => {
this.nodeService.addDynamicNode(p)
p.zoomLevel ? (zoomLevel = p.zoomLevel) : (zoomLevel = 1)
})
setTimeout(() => {
this.nodeContainer.nativeElement.click()
this.services.forEach((s: Service) => {
s.depends_on
? s.depends_on.forEach((uuid) => {
this.nodeService.addConnection(s.uuid, uuid)
})
: null
})
this.zoomLevel = zoomLevel
this.setZoom()
})
this.onFirstLoad = false
}
this.store.dispatch(GlobalSpinnerActions.OffSpinner())
}
})
this.eventEmitterService.subscribe('remove:node', (uuid) => {
this.nodeService.removeNode(uuid)
})
this.eventEmitterService.subscribe('change:connections', (data: { source: string; targets: Array<string> }) => {
this.nodeService.removeConnections(data.source)
data.targets
? data.targets.forEach((target) => {
this.nodeService.addConnection(data.source, target)
})
: ''
})
this.eventEmitterService.subscribe('add:depends_on', (data: { source: any; target: any }) => {
const service = this.services.find((s) => s.uuid === data.source)
if (service.depends_on) {
const currentTargetAlreadyExisted = service.depends_on.find((uuid) => uuid === data.target)
if (!currentTargetAlreadyExisted) {
this.store.dispatch(
ProjectActions.UpdateService({
data: {
...service,
depends_on: [...service.depends_on, data.target],
},
}),
)
}
} else {
this.store.dispatch(
ProjectActions.UpdateService({
data: {
...service,
depends_on: [data.target],
},
}),
)
}
})
this.eventEmitterService.subscribe('remove:depends_on', (data: { source: any; target: any }) => {
const service = this.services.find((s) => s.uuid === data.source)
const dependsOn = service.depends_on.filter((d) => d !== data.target)
this.store.dispatch(
ProjectActions.UpdateService({
data: {
...service,
depends_on: dependsOn,
},
}),
)
})
this.unSubscribeEventService = this.eventEmitterService.subscribe('save:project', () => {
const positionData = this.nodeService.getData()
this.store.dispatch(ProjectActions.SetPositions({ data: positionData }))
this.store.dispatch(ProjectActions.SaveProject())
})
this.eventEmitterService.subscribe('initialize:node', () => {
this.onFirstLoad = true
})
}
ngOnInit() {}
ngAfterViewInit() {
this.jsPlumbInstance = jsPlumb.getInstance()
this.nodeService.setRootViewContainerRef(this.viewContainerRef, this.jsPlumbInstance)
}
onMouseDown(event) {
this.dragStatus = true
this.prevPanState = {
x: event.x,
y: event.y,
}
}
onMouseMove(event) {
if (!this.dragStatus) return
this.nodeService.updateNodesPosition({
left: event.x - this.prevPanState.x,
top: event.y - this.prevPanState.y,
})
this.prevPanState = {
x: event.x,
y: event.y,
}
}
onMouseUp() {
this.dragStatus = false
}
onMouseWheel(event) {
let zoom = event.wheelDelta > 0 ? this.zoomLevel - this.zoomLevelUnit : this.zoomLevel + this.zoomLevelUnit
if (zoom > this.maxZoomLevel || zoom < this.minZoomLevel) return
this.zoomLevel = zoom
this.setZoom()
}
setZoom() {
this.viewContainerRef.element.nativeElement.parentElement.style.transform = `scale(${this.zoomLevel})`
this.viewContainerRef.element.nativeElement.parentElement.style.width = `${this.containerSize / this.zoomLevel}px`
this.viewContainerRef.element.nativeElement.parentElement.style.height = `${this.containerSize / this.zoomLevel}px`
this.viewContainerRef.element.nativeElement.parentElement.style.top = `${-(this.containerSize / this.zoomLevel - this.containerSize) / 2 - 100}px`
this.viewContainerRef.element.nativeElement.parentElement.style.left = `${
-(this.containerSize / this.zoomLevel - this.containerSize) / 2 - 100
}px`
this.nodeService.setZoom(this.zoomLevel)
}
manageProjectVolumes(): void {
this.dialog.open(ManageVolumesDialogComponent, {
width: '50%',
minWidth: '640px',
data: this.volumes,
})
}
manageProjectSecrets(): void {
//console.log('manageProjectSecrets')
}
manageProjectNetworks(): void {
this.dialog.open(ManageNetworksDialogComponent, {
width: '50%',
minWidth: '640px',
})
}
ngOnDestroy() {
this.unSubscribeEventService()
this.unSubscribe$.next(true)
this.unSubscribe$.complete()
}
}

@ -0,0 +1,105 @@
import { ComponentFactoryResolver, Injectable, ComponentFactory } from '@angular/core'
import { jsPlumb, Connection } from 'jsplumb'
import { NodeComponent } from './node/node.component'
import { IPosition } from 'src/app/core/store/models'
import { Store } from '@ngrx/store'
import { EventEmitterService } from 'src/app/core/services/event-emitter.service'
@Injectable()
export class NodeService {
private rootViewContainer: any
jsPlumbInstance
constructor(private factoryResolver: ComponentFactoryResolver, public eventEmitter: EventEmitterService) {}
public setRootViewContainerRef(viewContainerRef, jsplumbInstance) {
this.jsPlumbInstance = jsplumbInstance
this.rootViewContainer = viewContainerRef
const eventEmitter = this.eventEmitter
this.jsPlumbInstance.bind('dblclick', function (connection, event) {
this.deleteConnection(connection)
eventEmitter.broadcast('remove:depends_on', { source: connection.sourceId, target: connection.targetId })
})
this.jsPlumbInstance.bind('connectionDetached', (connection, event) => {
if (event) eventEmitter.broadcast('remove:depends_on', { source: connection.sourceId, target: connection.targetId })
})
this.jsPlumbInstance.bind('connection', (connection, event) => {
if (event && connection.sourceId !== connection.targetId)
this.eventEmitter.broadcast('add:depends_on', { source: connection.sourceId, target: connection.targetId })
})
}
public addDynamicNode(node: IPosition) {
const factory = this.factoryResolver.resolveComponentFactory(NodeComponent)
const component = factory.create(this.rootViewContainer.parentInjector)
;(<any>component.instance).node = node
;(<any>component.instance).jsPlumbInstance = this.jsPlumbInstance
this.rootViewContainer.insert(component.hostView)
}
public addConnection(source, target) {
this.jsPlumbInstance.connect({ uuids: [source + '_bottom', target + '_top'] })
}
public removeConnections(source) {
const connections = []
this.jsPlumbInstance.getAllConnections().forEach((con) => {
if (con.sourceId === source) connections.push(con)
})
connections.forEach((con) => this.jsPlumbInstance.deleteConnection(con))
}
public getData() {
const nodeList = document.querySelectorAll('.node')
let result: IPosition[] = []
nodeList.forEach((node: HTMLElement) => {
result.push({
uuid: node.id,
top: node.offsetTop,
left: node.offsetLeft,
zoomLevel: this.jsPlumbInstance.getZoom(),
})
})
return result
}
public removeNode(uuid: string) {
const nodeList = document.querySelectorAll('.node')
nodeList.forEach((node) => {
if (node.id === uuid) {
this.jsPlumbInstance.remove(uuid)
}
})
}
public updateNodesPosition(offset: { top: number; left: number }) {
const nodeList = document.querySelectorAll('.node')
nodeList.forEach((node: HTMLElement) => {
node.style.left = `${node.offsetLeft + offset.left}px`
node.style.top = `${node.offsetTop + offset.top}px`
this.jsPlumbInstance.revalidate(node)
})
}
public setZoom(zoomLevel: number) {
this.jsPlumbInstance.setZoom(zoomLevel, true)
}
public clear() {
const nodeList = document.querySelectorAll('.node')
const points = document.querySelectorAll('.jtk-endpoint')
points.forEach((node) => node.remove())
nodeList.forEach((node) => {
this.jsPlumbInstance.remove(node.id)
node.remove()
})
this.rootViewContainer.clear()
}
}

@ -0,0 +1,46 @@
<div class="node" id="{{ node.uuid }}" [style.top.px]="node.top || 0" [style.left.px]="node.left || 20">
<div class="node-body" fxLayout="column">
<div fxFlex fxLayoutAlign="center center" fxLayout="column">
<div class="node-title" [innerHTML]="(currentService ? currentService.name : '') | truncateText:15:false"></div>
<!--
<div *ngIf="currentService !== undefined;then image_tag else build_context"></div>
<ng-template #image_tag>
<div class="node-subtitle">
<span [innerHTML]="(currentService ? currentService.image : '') | truncateText:50:false" class="image-name"></span>{{ currentService.tag ? ":" : "" }}<span>{{ currentService ? currentService.tag : '' }}</span>
</div>
</ng-template>
<ng-template #build_context>other content here...</ng-template>
-->
<div *ngIf="currentService !== undefined" class="node-subtitle">
<div *ngIf="currentService.image;then image_tag else build_context"></div>
<ng-template #image_tag>
<span [innerHTML]="(currentService ? currentService.image : '') | truncateText:50:false" class="image-name"></span>{{ currentService.tag ? ":" : "" }}<span>{{ currentService ? currentService.tag : '' }}</span>
</ng-template>
<ng-template #build_context>
<span>custom build</span>
</ng-template>
</div>
</div>
<div fxLayout="row" fxLayoutAlign="space-between center" class="node-actions">
<button mat-icon-button matTooltip="Deploy" aria-label="Build" (click)="deployDialogOpen()">
<span class="material-icons">cloud_upload</span>
</button>
<button mat-icon-button matTooltip="Build" aria-label="Build" (click)="buildDialogOpen()">
<span class="material-icons">build</span>
</button>
<button fxFlexAlign="center" mat-icon-button matTooltip="Manage" aria-label="Manage" (click)="manageProjectService()">
<mat-icon>create</mat-icon>
</button>
</div>
<div fxLayout="row" fxLayoutAlign="center center" class="node-actions">
<button class="node-remove-btn" mat-icon-button matTooltip="Remove" aria-label="Remove" (click)="removeService()">
<mat-icon>close</mat-icon>
</button>
</div>
</div>
</div>

@ -0,0 +1,62 @@
.node {
position: absolute;
text-align: center;
z-index: 1;
border-radius: 10px;
background: #e8e8e8;
border: 1px solid #dadada;
/* box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0), 0 2px 2px 0 rgba(0,0,0,.14), 0 1px 5px 0 rgba(0,0,0,.12); */
.node-body {
position: relative;
width: 155px;
height: 145px;
padding: 4px;
.node-remove-btn {
position: absolute;
top: -8px;
left: -6px;
}
}
:hover {
cursor: all-scroll;
}
.node-actions {
:hover {
cursor: pointer;
}
button {
cursor: pointer;
}
}
.node-title {
font-weight: 600;
font-size: 16px;
}
.node-subtitle {
color: #656565;
word-break: break-all;
line-height: 14px;
padding: 5px 0 0;
font-size: 12px;
.image-name {
font-weight: 600;
}
}
::ng-deep .mat-icon {
width: 20px;
height: 20px;
}
::ng-deep .material-icons {
font-size: 18px;
font-weight: 600;
}
}

@ -0,0 +1,151 @@
import { Component, Input, AfterViewInit, OnDestroy } from '@angular/core'
import { IPosition, Service } from 'src/app/core/store/models'
import { Store } from '@ngrx/store'
import { AppState } from 'src/app/app.state'
import { RestService } from 'src/app/core/services/rest.service'
import { MatDialog } from '@angular/material/dialog'
import { ManageProjectDialogComponent } from '../../../dialogs/manage-project-dialog/manage-project-dialog.component'
import { ConfirmDialogComponent } from '../../../dialogs/confirm-dialog/confirm-dialog.component'
import { BuildDialogComponent } from '../../../dialogs/build-dialog/build-dialog.component'
import { DeployDialogComponent } from '../../../dialogs/deploy-dialog/deploy-dialog.component'
import * as ProjectActions from './../../../../store/project.actions'
import { NodeService } from '../node.service'
import { EventEmitterService } from 'src/app/core/services/event-emitter.service'
import { Subject } from 'rxjs'
import { takeUntil } from 'rxjs/operators'
@Component({
selector: 'node',
templateUrl: './node.component.html',
styleUrls: ['./node.component.scss'],
})
export class NodeComponent implements AfterViewInit, OnDestroy {
@Input() node: IPosition
@Input() jsPlumbInstance
services = []
currentService: Service
widthNode: number = 150
heightNode: number = 150
widthCanvasBorder: number = 15
private unSubscribe$ = new Subject()
constructor(private store: Store<AppState>, public rest: RestService, public dialog: MatDialog, private eventEmitterService: EventEmitterService) {
const project = this.store.select('project')
project.pipe(takeUntil(this.unSubscribe$)).subscribe((v) => {
this.services = v.services
setTimeout(() => {
this.currentService = this.services.find((s: Service) => s.uuid === this.node.uuid)
})
})
}
ngAfterViewInit() {
const exampleDropOptions = {
tolerance: 'touch',
hoverClass: 'dropHover',
activeClass: 'dragActive',
}
let Endpoint1 = {
endpoint: ['Dot', { radius: 7 }],
paintStyle: { fill: '#99cb3a' },
scope: 'jsPlumb_DefaultScope',
connectorStyle: { stroke: '#99cb3a', strokeWidth: 2 },
connector: ['Bezier', { curviness: 63 }],
maxConnections: -1,
isSource: true,
isTarget: false,
connectorOverlays: [['Arrow', { location: 1, width: 10, length: 10 }]],
dropOptions: exampleDropOptions,
}
let Endpoint2 = {
endpoint: ['Dot', { radius: 5 }],
paintStyle: { fill: '#ffcb3a' },
scope: 'jsPlumb_DefaultScope',
maxConnections: -1,
isSource: false,
isTarget: true,
dropOptions: exampleDropOptions,
}
const { uuid } = this.node
this.jsPlumbInstance.addEndpoint(uuid, { anchor: 'Bottom', uuid: uuid + '_bottom' }, Endpoint1)
this.jsPlumbInstance.addEndpoint(uuid, { anchor: 'Top', uuid: uuid + '_top' }, Endpoint2)
this.jsPlumbInstance.draggable(uuid, {
drag: ({ pos, el }) => {
const { width, height } = el.parentElement.parentElement.getBoundingClientRect()
const [left, top] = pos
//left-top
left < this.widthCanvasBorder ? (el.style.left = `${this.widthCanvasBorder}px`) : ''
top < this.widthCanvasBorder ? (el.style.top = `${this.widthCanvasBorder}px`) : ''
//left-top
//right-bottom
left + this.widthNode + this.widthCanvasBorder > width ? (el.style.left = `${width - this.heightNode - this.widthCanvasBorder}px`) : ''
top + this.heightNode + this.widthCanvasBorder > height ? (el.style.top = `${height - this.heightNode - this.widthCanvasBorder}px`) : ''
//right-bottom
},
})
}
manageProjectService(): void {
const dialogRef = this.dialog.open(ManageProjectDialogComponent, {
width: '50%',
minWidth: '740px',
data: this.currentService,
})
dialogRef
.afterClosed()
.pipe(takeUntil(this.unSubscribe$))
.subscribe((result: { data: Service }) => {
if (result) {
this.store.dispatch(ProjectActions.UpdateService({ data: result.data }))
}
})
}
removeService(): void {
const dialogRef = this.dialog.open(ConfirmDialogComponent, {
data: {
title: 'Confirm delete',
content: 'Are you sure want to delete this service?',
},
})
dialogRef
.afterClosed()
.pipe(takeUntil(this.unSubscribe$))
.subscribe((result: boolean) => {
if (result == true) {
this.store.dispatch(ProjectActions.RemoveService({ data: this.currentService }))
this.store.dispatch(ProjectActions.RemovePosition({ data: this.node }))
this.eventEmitterService.broadcast('remove:node', this.currentService.uuid)
}
})
}
buildDialogOpen() {
this.dialog.open(BuildDialogComponent, {
width: '50%',
minWidth: '740px',
data: this.currentService,
})
}
deployDialogOpen() {
this.dialog.open(DeployDialogComponent, {
width: '50%',
minWidth: '740px',
data: this.currentService,
})
}
ngOnDestroy() {
this.unSubscribe$.next(true)
this.unSubscribe$.complete()
}
}

@ -0,0 +1,15 @@
.code-mirror {
height: 100%;
.CodeMirror {
height: 100%;
.CodeMirror-hscrollbar {
display: none!important;
}
.CodeMirror-scroll {
padding-top: 12px;
.CodeMirror-lines {
padding-bottom: 120px;
}
}
}
}

@ -0,0 +1,64 @@
<div fxLayout="column" fxFill>
<div fxLayout="row" class="code-container" fxLayoutGap="8px" fxLayoutAlign="flex-end center">
<button *ngIf="mode === 'compose'" (click)="codeRefresh()" mat-icon-button color="primary" aria-label="refresh code" class="btn-code-refresh">
<mat-icon>loop</mat-icon>
</button>
<form [formGroup]="versionSelectForm">
<mat-form-field *ngIf="mode === 'compose'" appearance="outline" class="input-short">
<mat-select [(value)]="selectedSpecificVersion" name="version" (selectionChange)="changeVersion('select')">
<mat-option [value]="version" *ngFor="let version of specificVersions">
{{ version.title }}
</mat-option>
</mat-select>
</mat-form-field>
</form>
<button [matMenuTriggerFor]="menu" class="gear-menu" mat-icon-button>
<mat-icon>settings</mat-icon>
</button>
<mat-menu #menu="matMenu">
<button class="link-button" mat-menu-item color="primary" (click)="openImportDialog()">
Import
</button>
</mat-menu>
<div class="editor-buttons-block" fxLayout="row" fxLayoutGap="8px" fxLayoutAlign="flex-end center">
<!-- <button mat-raised-button [disabled]="mode === 'compose'" (click)="save()">
Save
</button> -->
<button *ngIf="mode === 'compose'" mat-icon-button color="white" (click)="changeMode()">
<mat-icon *ngIf="mode === 'compose'">edit</mat-icon>
</button>
<button *ngIf="mode === 'import'" mat-flat-button (click)="changeMode()">
<span>Done</span>
</button>
<button mat-flat-button [cdkCopyToClipboard]="code" (click)="changeButtonText()">
{{buttonText}}
</button>
</div>
<!-- <mat-button-toggle-group [(value)]="selectedVersion.value">
<span class="pseudo-toggle-button">
<mat-button-toggle [value]="0"></mat-button-toggle>
</span>
<mat-button-toggle *ngFor="let version of versions" [value]="version.value" (change)="changeVersion('toggle')">{{
version.title
}}</mat-button-toggle>
</mat-button-toggle-group> -->
</div>
<ngx-codemirror
[(ngModel)]="code"
[options]="{
lineNumbers: true,
theme: 'material',
mode: codeFormat,
readOnly: mode === 'compose',
extraKeys: extraKeys
}"
(click)="handelEditorClick()"
(touchend)="handelEditorClick()"
(focusout)="handelFocusout()"
class="code-mirror"
></ngx-codemirror>
</div>

@ -0,0 +1,41 @@
.code-container {
margin: 0 0 0 16px;
position: relative;
.editor-buttons-block {
position: absolute;
top: 65px;
right: 20px;
z-index: 4;
}
}
.code {
overflow: auto;
position: relative;
}
.btn-code-refresh {
color: #222;
background-color: #fff;
box-shadow: none;
.mat-icon {
font-size: 20px;
height: 21px;
}
}
.pseudo-toggle-button {
display: none;
}
@media (max-width: 410px) {
.code-container {
flex-direction: column!important;
}
}
.gear-menu {
margin: 10px 0 10px 0;
}

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CodeViewComponent } from './code-view.component';
describe('CodeViewComponent', () => {
let component: CodeViewComponent;
let fixture: ComponentFixture<CodeViewComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CodeViewComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CodeViewComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

@ -0,0 +1,227 @@
import { Component, OnInit, OnDestroy } from '@angular/core'
import { Router, Params, ActivatedRoute } from '@angular/router'
import { FormControl, Validators, FormGroup, FormBuilder } from '@angular/forms'
import { Observable } from 'rxjs/Observable'
import { Store } from '@ngrx/store'
import { MatDialog } from '@angular/material/dialog'
import { Project, GlobalAppConfiguration } from './../../store/models'
import { AppState } from './../../../app.state'
import { RestService } from './../../services/rest.service'
import * as ProjectActions from './../../store/project.actions'
import * as GlobalAppConfigurationActions from './../../store/actions/global-app-configuration.actions'
import * as GlobalDialogActions from './../../store/actions/global-dialog.actions'
import { EventEmitterService } from 'src/app/core/services/event-emitter.service'
import * as GlobalSpinnerActions from './../../store/actions/global-spinner.actions'
import { Subject } from 'rxjs'
import { takeUntil, throttleTime } from 'rxjs/operators'
import { ImportDialogComponent } from '../dialogs/import-dialog/import-dialog.component'
import { strict } from 'assert'
const THROTTLE_TIMEOUT = 1000
interface Version {
value: number
title: string
}
@Component({
selector: 'app-code-view',
templateUrl: './code-view.component.html',
styleUrls: ['./code-view.component.scss'],
})
export class CodeViewComponent implements OnInit, OnDestroy {
globalConfig: Observable<GlobalAppConfiguration>
mode: string
project: Observable<Project>
versionSelectForm: FormGroup
code: ''
codeFormat: string = 'yaml'
versions: Version[] = [
{ value: 1, title: 'version 1' },
{ value: 2, title: 'version 2' },
{ value: 3, title: 'version 3' },
]
specificVersions: Version[] = [
{ value: 1, title: 'version 1' },
{ value: 2, title: 'version 2' },
{ value: 3, title: 'version 3' },
]
selectedVersion: Version = { value: 0, title: 'unSelected' }
selectedSpecificVersion: Version
buttonText: string = 'Copy'
showSpinner: boolean = false
importUrl: string = null
recipeToLoadUuid: string = null
private unSubscribe$ = new Subject()
extraKeys = {
'Tab': cm => cm.replaceSelection(' '),
"Ctrl-S": () => this.changeMode(), //save current project like "done"
"Cmd-S": () => this.changeMode() //save current project like "done"
}
constructor(private fb: FormBuilder, private store: Store<AppState>, public rest: RestService, private eventEmitterService: EventEmitterService, public dialog: MatDialog, private router: Router, private activatedRoute: ActivatedRoute) {
this.project = store.select('project')
this.globalConfig = store.select('globalAppConfiguration')
this.selectedSpecificVersion = this.specificVersions[2]
this.globalConfig.pipe(takeUntil(this.unSubscribe$)).subscribe(({mode}) => {
this.mode = mode
})
this.versionSelectForm = this.fb.group({
versionSelectControl: [this.specificVersions]
})
}
codeRefresh(): void {
if (this.mode === 'compose') {
this.eventEmitterService.broadcast('save:project', {})
} else if (this.mode === 'import') {
if (!this.importUrl) {
this.store.dispatch(GlobalDialogActions.ProjectNotFound({ message: 'Import url is empty<br>Click on the Link button top right corner', _type: 'Error'}))
} else {
this.store.dispatch(GlobalSpinnerActions.OnSpinner())
this.store.dispatch(ProjectActions.ImportProject({data: {type: 'url', payload: this.importUrl}}))
this.eventEmitterService.broadcast('initialize:node', {})
}
}
}
containsVersion(obj, list): boolean {
for (let i = 0; i < list.length; i++) {
if (list[i].value === obj.value) {
return true;
}
}
return false
}
getVersion(version_number): Version {
for (let i = 0; i < this.specificVersions.length; i++) {
if (this.specificVersions[i].value === version_number) {
return this.specificVersions[i]
}
}
}
ngOnInit(): void {
const importUrl = this.activatedRoute.snapshot.queryParams['import_url']
const loadRecipeUrl = this.activatedRoute.snapshot.queryParams['recipe']
if (importUrl) {
this.importUrl = importUrl
this.store.dispatch(GlobalAppConfigurationActions.OnImportMode())
this.codeRefresh()
}
if (loadRecipeUrl) {
this.recipeToLoadUuid = loadRecipeUrl
this.store.dispatch(GlobalAppConfigurationActions.OnRecipeLoadMode())
}
this.project.pipe(takeUntil(this.unSubscribe$), throttleTime(THROTTLE_TIMEOUT, undefined, { trailing: true, leading: true})).subscribe((data) => {
if (this.mode === 'compose') {
let baseVersion = Math.floor(data.version)
let versionObject = this.getVersion(baseVersion)
this.selectedSpecificVersion = versionObject
const sendData = {
name: data.name,
data: {
version: data.version,
volumes: data.volumes,
services: data.services,
networks: data.networks,
secrets: data.secrets,
configs: data.configs,
},
}
this.showSpinner = true
this.rest
.generateCode(sendData)
.pipe(takeUntil(this.unSubscribe$))
.subscribe((data: {}) => {
for (var i = 0; i < data['code'].length; ++i) {
data['code'][i] = data['code'][i].replace(/(\r\n|\n|\r)/gm, '')
}
this.code = data['code'].join('\n')
if (data['code_format']) {
this.codeFormat = data['code_format']
}
this.showSpinner = false
})
}
})
this.eventEmitterService.subscribe('load: code', (code) => {
this.code = code
})
}
changeVersion(type: string): void {
if (type === 'select') {
this.selectedVersion = { value: 0, title: 'unSlected' }
this.store.dispatch(ProjectActions.UpdateVersion({ data: this.selectedSpecificVersion.value }))
} else if (type === 'toggle') {
this.selectedSpecificVersion = { value: 0, title: 'Select version' }
this.store.dispatch(ProjectActions.UpdateVersion({ data: this.selectedVersion.value }))
}
}
changeButtonText() {
this.buttonText = 'Copied'
setTimeout(() => (this.buttonText = 'Copy'), 5000)
}
ngOnDestroy() {
this.unSubscribe$.next(true)
this.unSubscribe$.complete()
}
changeMode() {
if (this.mode === 'compose') {
this.store.dispatch(GlobalAppConfigurationActions.OnImportMode())
} else {
this.store.dispatch(ProjectActions.ImportCurrentProject({data: {type: 'yaml', payload: this.code}}))
this.eventEmitterService.broadcast('initialize:node', {})
this.store.dispatch(GlobalAppConfigurationActions.OnComposeMode())
}
}
openImportDialog() {
const importDialog = this.dialog.open(ImportDialogComponent, {
data: { importUrl: this.importUrl },
width: '800px'
})
importDialog.componentInstance.onImport.pipe(takeUntil(this.unSubscribe$)).subscribe((importUrl) => {
this.store.dispatch(GlobalAppConfigurationActions.OnImportMode())
this.importUrl = importUrl
const queryParams: Params = { import_url: importUrl }
this.router.navigate(
['/'],
{
relativeTo: this.activatedRoute,
queryParams: queryParams,
queryParamsHandling: 'merge', // remove to replace all query params by provided
})
!this.activatedRoute.snapshot.params['uuid'] ? this.codeRefresh() : ''
this.eventEmitterService.broadcast('initialize:node', {})
})
}
handelEditorClick() {
this.store.dispatch(GlobalAppConfigurationActions.OnImportMode())
}
handelFocusout() {
this.store.dispatch(GlobalAppConfigurationActions.OnComposeMode())
}
}

@ -0,0 +1,14 @@
<div class="key-value-container" fxLayout="row" fxLayoutGap="6px" *ngFor="let pair of currentKeyValuePairs; let i = index">
<mat-form-field appearance="outline" class="pd-b-0">
<mat-label>key</mat-label>
<input matInput required [formControl]="pair.key" />
</mat-form-field>
<mat-form-field appearance="outline" class="pd-b-0">
<mat-label>value</mat-label>
<input matInput [formControl]="pair.value" />
</mat-form-field>
<button mat-icon-button (click)="removePair(i)"><mat-icon>remove</mat-icon></button>
</div>
<button mat-icon-button color="primary" (click)="addPair()"><mat-icon>add</mat-icon> new set</button>

@ -0,0 +1,13 @@
.key-value-container {
.mat-form-field {
&:nth-child(2) {
min-width: calc(100% - 200px - 80px);
}
}
}
.ng-star-inserted {
.mat-icon-button {
margin-top: 7px;
}
}

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { KeyValueComponent } from './key-value.component';
describe('KeyValueComponent', () => {
let component: KeyValueComponent;
let fixture: ComponentFixture<KeyValueComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ KeyValueComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(KeyValueComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save