🎉 First commit of the open source project !

This commit is contained in:
Alex
2022-07-23 01:44:03 +02:00
commit 0b392a6953
329 changed files with 22060 additions and 0 deletions

22
.dockerignore Normal file
View File

@@ -0,0 +1,22 @@
.dockerignore
# there are valid reasons to keep the .git, namely so that you can get the
# current commit hash
#.git
.log
tmp
# Mix artifacts
_build
deps
*.ez
releases
# Generate on crash by the VM
erl_crash.dump
# Static artifacts
node_modules
assets/node_modules/
deps/
assets/yarn.lock

6
.env.sample Normal file
View File

@@ -0,0 +1,6 @@
AWS_ACCESS_KEY_ID=xxx
AWS_SECRET_ACCESS_KEY=xxx
AWS_REGION=eu-west-3
AWS_PRES_BUCKET=xxx
PRESENTATION_STORAGE=local
MAIL=local

5
.formatter.exs Normal file
View File

@@ -0,0 +1,5 @@
[
import_deps: [:ecto, :phoenix],
inputs: ["*.{ex,exs}", "priv/*/seeds.exs", "{config,lib,test}/**/*.{ex,exs}"],
subdirectories: ["priv/*/migrations"]
]

42
.github/workflows/docker-image.yml vendored Normal file
View File

@@ -0,0 +1,42 @@
name: Docker Image CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up QEMU
id: qemu
uses: docker/setup-qemu-action@v1
with:
image: tonistiigi/binfmt:latest
platforms: all
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
with:
buildkitd-flags: --debug
driver-opts: image=moby/buildkit:v0.9.1
- name: Log in to registry
# This is where you will update the PAT to GITHUB_TOKEN
run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login ghcr.io -u $ --password-stdin
- name: Build and push Docker images
# You may pin to the exact commit or the version.
# uses: docker/build-push-action@ac9327eae2b366085ac7f6a2d02df8aa8ead720a
uses: docker/build-push-action@v2.10.0
with:
context: .
push: true
tags: ghcr.io/${{ github.repository }}/claper
cache-from: type=registry,ref=ghcr.io/${{ github.repository }}/claper:latest
cache-to: type=inline

44
.gitignore vendored Normal file
View File

@@ -0,0 +1,44 @@
# The directory Mix will write compiled artifacts to.
/_build/
# If you run "mix test --cover", coverage assets end up here.
/cover/
# The directory Mix downloads your dependencies sources to.
/deps/
# Where 3rd-party dependencies like ExDoc output generated docs.
/doc/
# Ignore .fetch files in case you like to edit your project deps locally.
/.fetch
# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump
# Also ignore archive artifacts (built via "mix archive.build").
*.ez
# Ignore package tarball (built via "mix hex.build").
claper-*.tar
# Ignore assets that are produced by build tools.
/priv/static/assets/
/priv/static/uploads
# Ignore digested assets cache.
/priv/static/cache_manifest.json
# In case you use Node.js/npm, you want to ignore these.
npm-debug.log
/assets/node_modules/
priv/static/images/.DS_Store
priv/static/.DS_Store
.env
priv/static/fonts/.DS_Store
test/e2e/node_modules
.DS_Store
priv/static/.well-known/apple-developer-merchantid-domain-association
priv/static/loaderio-eb3b956a176cdd4f54eb8570ce8bbb06.txt

100
Dockerfile Normal file
View File

@@ -0,0 +1,100 @@
# Find eligible builder and runner images on Docker Hub. We use Ubuntu/Debian instead of
# Alpine to avoid DNS resolution issues in production.
#
# https://hub.docker.com/r/hexpm/elixir/tags?page=1&name=ubuntu
# https://hub.docker.com/_/ubuntu?tab=tags
#
#
# This file is based on these images:
#
# - https://hub.docker.com/r/hexpm/elixir/tags - for the build image
# - https://hub.docker.com/_/debian?tab=tags&page=1&name=bullseye-20210902-slim - for the release image
# - https://pkgs.org/ - resource for finding needed packages
# - Ex: hexpm/elixir:1.13.2-erlang-24.2.1-debian-bullseye-20210902-slim
#
ARG BUILDER_IMAGE="hexpm/elixir:1.13.2-erlang-24.2.1-debian-bullseye-20210902-slim"
ARG RUNNER_IMAGE="debian:bullseye-20210902-slim"
FROM ${BUILDER_IMAGE} as builder
# install build dependencies
RUN apt-get update -y && apt-get install -y build-essential git nodejs npm \
&& apt-get clean && rm -f /var/lib/apt/lists/*_*
# prepare build dir
WORKDIR /app
# install hex + rebar
RUN mix local.hex --force && \
mix local.rebar --force
# set build ENV
ENV MIX_ENV="prod"
# install mix dependencies
COPY mix.exs mix.lock ./
RUN mix deps.get --only $MIX_ENV
RUN mkdir config
# copy compile-time config files before we compile dependencies
# to ensure any relevant config change will trigger the dependencies
# to be re-compiled.
COPY config/config.exs config/${MIX_ENV}.exs config/
RUN mix deps.compile
COPY priv priv
# note: if your project uses a tool like https://purgecss.com/,
# which customizes asset compilation based on what it finds in
# your Elixir templates, you will need to move the asset compilation
# step down so that `lib` is available.
COPY assets assets
# Compile the release
COPY lib lib
RUN mix compile
# compile assets
RUN mix assets.deploy
# Changes to config/runtime.exs don't require recompiling the code
COPY config/runtime.exs config/
COPY rel rel
RUN mix release
# start a new build stage so that the final image will only contain
# the compiled release and other runtime necessities
FROM ${RUNNER_IMAGE}
RUN apt-get update -y && apt-get install -y libstdc++6 openssl libncurses5 locales ghostscript \
&& apt-get install -y libreoffice --no-install-recommends && apt-get clean && rm -f /var/lib/apt/lists/*_*
# Set the locale
RUN sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && locale-gen
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
ENV HOME "/home/nobody"
RUN mkdir /home/nobody && chown nobody /home/nobody
WORKDIR "/app"
RUN chown nobody /app
# Only copy the final release from the build stage
COPY --from=builder --chown=nobody:root /app/_build/prod/rel/claper ./
RUN chmod +x /app/bin/*
USER nobody
EXPOSE 4000
CMD ["sh", "-c", "/app/bin/claper eval Claper.Release.migrate && /app/bin/claper start"]
# Appended by flyctl
#ENV ECTO_IPV6 true
#ENV ERL_AFLAGS "-proto_dist inet6_tcp"

674
LICENSE.txt Normal file
View File

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

201
README.md Normal file
View File

@@ -0,0 +1,201 @@
[![Contributors][contributors-shield]][contributors-url]
[![Forks][forks-shield]][forks-url]
[![Stargazers][stars-shield]][stars-url]
[![Issues][issues-shield]][issues-url]
[![MIT License][license-shield]][license-url]
<!-- PROJECT LOGO -->
<br />
<div align="center">
<a href="https://github.com/ClaperCo/Claper">
<img src="priv/static/images/logo.png" alt="Logo" >
</a>
<h3 align="center">Claper</h3>
<p align="center">
The ultimate tool to interact with your audience.
<br />
<a href="https://github.com/ClaperCo/Claper"><strong>Explore the docs »</strong></a>
<br />
<br />
<a href="https://github.com/ClaperCo/Claper/issues">Report Bug</a>
·
<a href="https://github.com/ClaperCo/Claper/issues">Request Feature</a>
</p>
</div>
<!-- TABLE OF CONTENTS -->
<details>
<summary>Table of Contents</summary>
<ol>
<li>
<a href="#about-the-project">About The Project</a>
<ul>
<li><a href="#built-with">Built With</a></li>
</ul>
</li>
<li>
<a href="#getting-started">Getting Started</a>
<ul>
<li><a href="#prerequisites">Prerequisites</a></li>
<li><a href="#configuration">Configuration</a></li>
<li><a href="#installation">Installation</a></li>
</ul>
</li>
<li><a href="#usage">Usage</a></li>
<li><a href="#roadmap">Roadmap</a></li>
<li><a href="#contributing">Contributing</a></li>
<li><a href="#license">License</a></li>
<li><a href="#contact">Contact</a></li>
</ol>
</details>
<!-- ABOUT THE PROJECT -->
## About The Project
[![Product Name Screen Shot][product-screenshot]](https://claper.co)
Claper turns your presentations into an interactive, engaging and exciting experience.
Claper has a two-sided mission:
- The first one is to help these people presenting an idea or a message by giving them the opportunity to make their presentation unique and to have real-time feedback from their audience.
- The second one is to help each participant to take their place, to be an actor in the presentation, in the meeting and to feel important and useful.
### Built With
Claper is proudly powered by Phoenix and Elixir.
* [![Phoenix][Phoenix]][Phoenix-url]
* [![Elixir][Elixir]][Elixir-url]
* [![Tailwind][Tailwind]][Tailwind-url]
<!-- GETTING STARTED -->
## Getting Started
This is an example of how you may give instructions on setting up your project locally.
To get a local copy up and running follow these simple example steps.
### Prerequisites
To run Claper on your local environment you need to have:
* Postgres >= 9
* Elixir >= 1.13.2
* Erland >= 24
You can also use Docker to easily run a Postgres instance:
```sh
docker run -p 5432:5432 -e POSTGRES_PASSWORD=claper -e POSTGRES_USER=claper -e POSTGRES_DB=claper --name claper-db -d postgres:9
```
### Configuration
All configuration used by the app is store on the `.env` file. You can find an example file in `.env.sample`, but you should copy it to `.env` and fill it with your own values.
- **PRESENTATION_STORAGE** : `local` or `s3`, define where the presentation files will be stored.
- **MAIL** : `local` or `smtp`, define how the mails will be sent.
_(only if s3 is used)_ :
- **AWS_ACCESS_KEY_ID** : Your AWS Access Key ID.
- **AWS_SECRET_ACCESS_KEY** : Your AWS Secret Access Key.
- **AWS_S3_BUCKET** : The name of the bucket where the presentation files will be stored.
- **AWS_S3_REGION** : The region where the bucket is located.
### Installation
1. Clone the repo
```sh
git clone https://github.com/ClaperCo/Claper.git
```
2. Install dependencies
```sh
mix deps.get
```
3. Migrate your database
```sh
mix ecto.migrate
```
4. Start Phoenix endpoint with
```sh
mix phx.server
```
Now you can visit [`localhost:4000`](http://localhost:4000) from your browser.
If you have configured `MAIL` to `local`, you can access to the mailbox at [`localhost:4000/dev/mailbox`](http://localhost:4000/dev/mailbox).
<!-- USAGE EXAMPLES -->
## Usage
### Login/Signup
Claper is passwordless, so you don't have to create an account. Just login with your email, check your mailbox ([localhost:4000/dev/mailbox](http://localhost:4000/dev/mailbox) if you have configured mail to be in local) and click on the link to get connected.
<!-- ROADMAP -->
## Roadmap
- [ ] Add Changelog
- [ ] Remove dead code
- [ ] Add additional tests for better coverage
- [ ] Add more docs
See the [open issues](https://github.com/ClaperCo/Claper/issues) for a full list of proposed features (and known issues).
<!-- CONTRIBUTING -->
## Contributing
Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement".
Don't forget to give the project a star! Thanks again!
1. Fork the Project
2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`)
3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
<!-- LICENSE -->
## License
Distributed under the GPLv3 License. See `LICENSE.txt` for more information.
<!-- CONTACT -->
## Contact
[![](https://img.shields.io/badge/@alexlionco-1DA1F2?style=for-the-badge&logo=twitter&logoColor=white)](https://twitter.com/alexlionco)
Project Link: [https://github.com/ClaperCo/Claper](https://github.com/ClaperCo/Claper)
<!-- MARKDOWN LINKS & IMAGES -->
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
[contributors-shield]: https://img.shields.io/github/contributors/ClaperCo/Claper.svg?style=for-the-badge
[contributors-url]: https://github.com/ClaperCo/Claper/graphs/contributors
[forks-shield]: https://img.shields.io/github/forks/ClaperCo/Claper.svg?style=for-the-badge
[forks-url]: https://github.com/ClaperCo/Claper/network/members
[stars-shield]: https://img.shields.io/github/stars/ClaperCo/Claper.svg?style=for-the-badge
[stars-url]: https://github.com/ClaperCo/Claper/stargazers
[issues-shield]: https://img.shields.io/github/issues/ClaperCo/Claper.svg?style=for-the-badge
[issues-url]: https://github.com/ClaperCo/Claper/issues
[license-shield]: https://img.shields.io/github/license/ClaperCo/Claper.svg?style=for-the-badge
[license-url]: https://github.com/ClaperCo/Claper/blob/master/LICENSE.txt
[product-screenshot]: /priv/static/images/preview.png
[Elixir]: https://img.shields.io/badge/elixir-4B275F?style=for-the-badge&logo=elixir&logoColor=white
[Elixir-url]: https://elixir-lang.org/
[Tailwind]: https://img.shields.io/badge/tailwind-06B6D4?style=for-the-badge&logo=tailwindcss&logoColor=white
[Tailwind-url]: https://tailwindcss.com/
[Phoenix]: https://img.shields.io/badge/phoenix-f35424?style=for-the-badge&logo=&logoColor=white
[Phoenix-url]: https://www.phoenixframework.org/

50
assets/build.js Normal file
View File

@@ -0,0 +1,50 @@
const esbuild = require('esbuild')
const args = process.argv.slice(2)
const watch = args.includes('--watch')
const deploy = args.includes('--deploy')
const loader = {
// Add loaders for images/fonts/etc, e.g. { '.svg': 'file' }
}
const plugins = [
// Add and configure plugins here
]
let opts = {
entryPoints: ['js/app.js'],
bundle: true,
target: 'es2016',
outdir: '../priv/static/assets',
logLevel: 'info',
loader,
plugins
}
if (watch) {
opts = {
...opts,
watch,
sourcemap: 'inline'
}
}
if (deploy) {
opts = {
...opts,
minify: true
}
}
const promise = esbuild.build(opts)
if (watch) {
promise.then(_result => {
process.stdin.on('close', () => {
process.exit(0)
})
process.stdin.resume()
})
}

430
assets/css/app.css Normal file
View File

@@ -0,0 +1,430 @@
@import url("flatpickr/dist/flatpickr.min.css");
@import url("animate.css/animate.min.css");
@tailwind base;
@tailwind components;
@tailwind utilities;
* {
font-family: 'Roboto', sans-serif;
}
[x-cloak] { display: none !important; }
/* Alerts and form errors used by phx.new */
.alert {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
}
.alert-info {
color: #31708f;
background-color: #d9edf7;
border-color: #bce8f1;
}
.alert-warning {
color: #8a6d3b;
background-color: #fcf8e3;
border-color: #faebcc;
}
.alert-danger {
color: #a94442;
background-color: #f2dede;
border-color: #ebccd1;
}
.alert p {
margin-bottom: 0;
}
.alert:empty {
display: none;
}
.invalid-feedback {
color: #a94442;
display: block;
margin-top: 2px;
}
/* LiveView specific classes for your customization */
.phx-no-feedback.invalid-feedback,
.phx-no-feedback .invalid-feedback {
display: none;
}
.phx-click-loading {
opacity: 0.5;
transition: opacity 1s ease-out;
}
.phx-disconnected{
cursor: wait;
}
.phx-disconnected *{
pointer-events: none;
}
.phx-modal {
opacity: 1!important;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.phx-modal-content {
background-color: #fefefe;
margin: 15vh auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.phx-modal-close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.phx-modal-close:hover,
.phx-modal-close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
/**
Forms
**/
.input:focus~.label,
.input:active~.label,
.input.filled~.label {
@apply text-sm transition-all duration-100 -top-1.5 text-primary-500;
}
.input:focus~.icon,
.input:active~.icon,
.input.filled~.icon {
@apply transition-all duration-100 left-3 top-6 h-5;
}
.date-placeholder-hidden::-webkit-datetime-edit {
display: none;
}
.date-placeholder-hidden::-webkit-inner-spin-button,
.date-placeholder-hidden::-webkit-calendar-picker-indicator {
display: none;
-webkit-appearance: none;
}
/**
Custom fonts
**/
/* roboto-100 - latin */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 100;
src: url('/fonts/Roboto/roboto-v29-latin-100.eot'); /* IE9 Compat Modes */
src: local(''),
url('/fonts/Roboto/roboto-v29-latin-100.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('/fonts/Roboto/roboto-v29-latin-100.woff2') format('woff2'), /* Super Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-100.woff') format('woff'), /* Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-100.ttf') format('truetype'), /* Safari, Android, iOS */
url('/fonts/Roboto/roboto-v29-latin-100.svg#Roboto') format('svg'); /* Legacy iOS */
}
/* roboto-100italic - latin */
@font-face {
font-family: 'Roboto';
font-style: italic;
font-weight: 100;
src: url('/fonts/Roboto/roboto-v29-latin-100italic.eot'); /* IE9 Compat Modes */
src: local(''),
url('/fonts/Roboto/roboto-v29-latin-100italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('/fonts/Roboto/roboto-v29-latin-100italic.woff2') format('woff2'), /* Super Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-100italic.woff') format('woff'), /* Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-100italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('/fonts/Roboto/roboto-v29-latin-100italic.svg#Roboto') format('svg'); /* Legacy iOS */
}
/* roboto-300italic - latin */
@font-face {
font-family: 'Roboto';
font-style: italic;
font-weight: 300;
src: url('/fonts/Roboto/roboto-v29-latin-300italic.eot'); /* IE9 Compat Modes */
src: local(''),
url('/fonts/Roboto/roboto-v29-latin-300italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('/fonts/Roboto/roboto-v29-latin-300italic.woff2') format('woff2'), /* Super Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-300italic.woff') format('woff'), /* Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-300italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('/fonts/Roboto/roboto-v29-latin-300italic.svg#Roboto') format('svg'); /* Legacy iOS */
}
/* roboto-300 - latin */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 300;
src: url('/fonts/Roboto/roboto-v29-latin-300.eot'); /* IE9 Compat Modes */
src: local(''),
url('/fonts/Roboto/roboto-v29-latin-300.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('/fonts/Roboto/roboto-v29-latin-300.woff2') format('woff2'), /* Super Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-300.woff') format('woff'), /* Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-300.ttf') format('truetype'), /* Safari, Android, iOS */
url('/fonts/Roboto/roboto-v29-latin-300.svg#Roboto') format('svg'); /* Legacy iOS */
}
/* roboto-regular - latin */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
src: url('/fonts/Roboto/roboto-v29-latin-regular.eot'); /* IE9 Compat Modes */
src: local(''),
url('/fonts/Roboto/roboto-v29-latin-regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('/fonts/Roboto/roboto-v29-latin-regular.woff2') format('woff2'), /* Super Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-regular.woff') format('woff'), /* Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-regular.ttf') format('truetype'), /* Safari, Android, iOS */
url('/fonts/Roboto/roboto-v29-latin-regular.svg#Roboto') format('svg'); /* Legacy iOS */
}
/* roboto-italic - latin */
@font-face {
font-family: 'Roboto';
font-style: italic;
font-weight: 400;
src: url('/fonts/Roboto/roboto-v29-latin-italic.eot'); /* IE9 Compat Modes */
src: local(''),
url('/fonts/Roboto/roboto-v29-latin-italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('/fonts/Roboto/roboto-v29-latin-italic.woff2') format('woff2'), /* Super Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-italic.woff') format('woff'), /* Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('/fonts/Roboto/roboto-v29-latin-italic.svg#Roboto') format('svg'); /* Legacy iOS */
}
/* roboto-500 - latin */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 500;
src: url('/fonts/Roboto/roboto-v29-latin-500.eot'); /* IE9 Compat Modes */
src: local(''),
url('/fonts/Roboto/roboto-v29-latin-500.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('/fonts/Roboto/roboto-v29-latin-500.woff2') format('woff2'), /* Super Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-500.woff') format('woff'), /* Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-500.ttf') format('truetype'), /* Safari, Android, iOS */
url('/fonts/Roboto/roboto-v29-latin-500.svg#Roboto') format('svg'); /* Legacy iOS */
}
/* roboto-500italic - latin */
@font-face {
font-family: 'Roboto';
font-style: italic;
font-weight: 500;
src: url('/fonts/Roboto/roboto-v29-latin-500italic.eot'); /* IE9 Compat Modes */
src: local(''),
url('/fonts/Roboto/roboto-v29-latin-500italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('/fonts/Roboto/roboto-v29-latin-500italic.woff2') format('woff2'), /* Super Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-500italic.woff') format('woff'), /* Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-500italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('/fonts/Roboto/roboto-v29-latin-500italic.svg#Roboto') format('svg'); /* Legacy iOS */
}
/* roboto-700 - latin */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 700;
src: url('/fonts/Roboto/roboto-v29-latin-700.eot'); /* IE9 Compat Modes */
src: local(''),
url('/fonts/Roboto/roboto-v29-latin-700.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('/fonts/Roboto/roboto-v29-latin-700.woff2') format('woff2'), /* Super Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-700.woff') format('woff'), /* Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-700.ttf') format('truetype'), /* Safari, Android, iOS */
url('/fonts/Roboto/roboto-v29-latin-700.svg#Roboto') format('svg'); /* Legacy iOS */
}
/* roboto-700italic - latin */
@font-face {
font-family: 'Roboto';
font-style: italic;
font-weight: 700;
src: url('/fonts/Roboto/roboto-v29-latin-700italic.eot'); /* IE9 Compat Modes */
src: local(''),
url('/fonts/Roboto/roboto-v29-latin-700italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('/fonts/Roboto/roboto-v29-latin-700italic.woff2') format('woff2'), /* Super Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-700italic.woff') format('woff'), /* Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-700italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('/fonts/Roboto/roboto-v29-latin-700italic.svg#Roboto') format('svg'); /* Legacy iOS */
}
/* roboto-900 - latin */
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 900;
src: url('/fonts/Roboto/roboto-v29-latin-900.eot'); /* IE9 Compat Modes */
src: local(''),
url('/fonts/Roboto/roboto-v29-latin-900.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('/fonts/Roboto/roboto-v29-latin-900.woff2') format('woff2'), /* Super Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-900.woff') format('woff'), /* Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-900.ttf') format('truetype'), /* Safari, Android, iOS */
url('/fonts/Roboto/roboto-v29-latin-900.svg#Roboto') format('svg'); /* Legacy iOS */
}
/* roboto-900italic - latin */
@font-face {
font-family: 'Roboto';
font-style: italic;
font-weight: 900;
src: url('/fonts/Roboto/roboto-v29-latin-900italic.eot'); /* IE9 Compat Modes */
src: local(''),
url('/fonts/Roboto/roboto-v29-latin-900italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('/fonts/Roboto/roboto-v29-latin-900italic.woff2') format('woff2'), /* Super Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-900italic.woff') format('woff'), /* Modern Browsers */
url('/fonts/Roboto/roboto-v29-latin-900italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('/fonts/Roboto/roboto-v29-latin-900italic.svg#Roboto') format('svg'); /* Legacy iOS */
}
.bg-gradient-animate {
background: linear-gradient(-45deg, #b80fef, #8611ed, #14bfdb, #14bfdb);
background-size: 400% 400%;
animation: gradient 15s ease infinite;
}
@keyframes gradient {
0% {
background-position: 0% 50%;
}
50% {
background-position: 100% 50%;
}
100% {
background-position: 0% 50%;
}
}
.arrow_box {
position: relative;
background: #fff;
border: 2px solid #e1e1e1;
}
.arrow_box.arrow_right:after, .arrow_box.arrow_right:before {
left: 100%;
top: 50%;
border: solid transparent;
content: "";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.arrow_box.arrow_right:after {
border-color: rgba(255, 255, 255, 0);
border-left-color: #fff;
border-width: 15px;
margin-top: -15px;
}
.arrow_box.arrow_right:before {
border-color: rgba(225, 225, 225, 0);
border-left-color: #e1e1e1;
border-width: 18px;
margin-top: -18px;
}
.arrow_box.arrow_left:after, .arrow_box.arrow_left:before {
right: 100%;
top: 50%;
border: solid transparent;
content: "";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.arrow_box.arrow_left:after {
border-color: rgba(255, 255, 255, 0);
border-right-color: #fff;
border-width: 15px;
margin-top: -15px;
}
.arrow_box.arrow_left:before {
border-color: rgba(225, 225, 225, 0);
border-right-color: #e1e1e1;
border-width: 18px;
margin-top: -18px;
}
:root {
--animate-duration: 0.3s;
}
/* Presenter fix for Safari */
@media not all and (min-resolution:.001dpcm)
{ @supports (-webkit-appearance:none) and (stroke-color:transparent) {
#post-list.showed {
@apply w-4/12;
}
}}
.react-animation {
opacity: 0;
}
.react-animation:nth-child(odd) {
animation: react 2s linear;
}
.react-animation:nth-child(even) {
animation: react2 2s linear;
}
@keyframes react {
0% {
transform: translateY(0%);
opacity: 0;
}
20% {
transform: translateY(-70%);
opacity: 1;
}
100% {
transform: translateY(-300%);
opacity: 0;
}
}
@keyframes react2 {
0% {
transform: translateY(0%);
opacity: 0;
}
40% {
transform: translateY(-70%);
opacity: 1;
}
100% {
transform: translateY(-500%);
opacity: 0;
}
}
.strikethrough {
position: relative;
}
.strikethrough:before {
position: absolute;
content: "";
left: 0;
top: 50%;
right: 0;
border-top: 3px solid;
@apply border-supporting-red-600;
-webkit-transform:rotate(-20deg);
-moz-transform:rotate(-20deg);
-ms-transform:rotate(-20deg);
-o-transform:rotate(-20deg);
transform:rotate(-20deg);
}

44
assets/css/custom.scss Normal file
View File

@@ -0,0 +1,44 @@
@use "sass:math";
@import "../node_modules/tiny-slider/src/tiny-slider.scss";
$particleSize: 20vmin;
$animationDuration: 6s;
$amount: 20;
.background span {
width: $particleSize;
height: $particleSize;
border-radius: $particleSize;
backface-visibility: hidden;
opacity: 0.5;
position: absolute;
animation-name: move;
animation-duration: $animationDuration;
animation-timing-function: linear;
animation-iteration-count: infinite;
$colors: (
#14bfdb,
#8611ed,
#b80fef
);
@for $i from 1 through $amount {
&:nth-child(#{$i}) {
color: nth($colors, random(length($colors)));
top: random(100) * 1%;
left: random(100) * 1%;
animation-duration: math.div(random($animationDuration * 10), 10) * 1s + 10s;
animation-delay: math.div(random($animationDuration + 10s) * 10, 10) * -1s;
transform-origin: (random(50) ) * 1vw (random(50)) * 1vh;
$blurRadius: (random() + 0.9) * $particleSize * 0.9;
$x: if(random() > 0.5, -1, 1);
box-shadow: ($particleSize * 2 * $x) 0 $blurRadius currentColor;
}
}
}
@keyframes move {
100% {
transform: translate3d(0, 0, 1px) rotate(360deg);
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

View File

@@ -0,0 +1,32 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
width="749.000000pt" height="705.000000pt" viewBox="0 0 749.000000 705.000000"
preserveAspectRatio="xMidYMid meet">
<g transform="translate(0.000000,705.000000) scale(0.100000,-0.100000)"
fill="#fff" stroke="none">
<path d="M6065 7026 c-42 -19 -62 -44 -86 -112 -18 -49 -23 -94 -29 -264 -5
-113 -11 -218 -14 -235 -74 -422 -125 -616 -244 -940 -37 -100 -69 -180 -81
-203 -5 -9 -37 -72 -70 -140 -34 -68 -70 -135 -80 -150 -55 -80 -85 -148 -117
-257 -27 -97 -17 -98 70 -7 111 116 280 337 356 463 14 23 36 58 49 78 56 85
183 349 244 511 48 125 124 371 134 433 6 43 22 47 43 13 19 -32 134 -198 176
-256 32 -43 47 -64 167 -225 161 -216 323 -452 370 -540 28 -52 55 -122 133
-345 92 -264 142 -380 180 -411 23 -19 92 6 135 50 81 81 90 301 22 561 -23
91 -107 274 -167 365 -113 173 -193 282 -422 575 -68 86 -213 281 -249 334
-99 144 -119 184 -165 328 -80 249 -136 341 -227 372 -56 19 -88 20 -128 2z"/>
<path d="M6175 5393 c-24 -6 -120 -72 -158 -108 -16 -15 -33 -38 -38 -52 -12
-32 3 -83 32 -109 37 -34 57 -85 53 -139 -25 -374 -130 -834 -274 -1200 -17
-44 -40 -102 -50 -130 -60 -159 -216 -486 -337 -700 -90 -162 -88 -158 -149
-255 -152 -242 -284 -431 -413 -590 -524 -645 -1064 -1095 -1676 -1394 -393
-193 -728 -296 -1140 -352 -183 -25 -539 -25 -690 0 -326 52 -614 176 -825
355 -30 25 -63 53 -74 61 -10 8 -52 53 -93 100 -76 86 -99 127 -238 428 -21
45 -41 82 -45 82 -4 0 -15 -9 -26 -21 -39 -43 -26 -325 21 -460 9 -23 44 -86
79 -139 204 -306 614 -575 1046 -685 202 -52 269 -59 540 -60 258 0 325 6 535
46 712 138 1528 571 2245 1193 114 99 412 392 504 495 52 59 249 306 306 384
19 27 44 60 56 75 29 37 218 320 238 357 9 17 35 59 57 95 181 286 415 784
530 1125 11 33 25 69 30 80 5 11 19 52 30 90 101 336 133 479 181 810 6 44 12
157 12 250 1 185 -9 232 -62 304 -41 56 -130 83 -207 64z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@@ -0,0 +1,32 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"
"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">
<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
width="749.000000pt" height="705.000000pt" viewBox="0 0 749.000000 705.000000"
preserveAspectRatio="xMidYMid meet">
<g transform="translate(0.000000,705.000000) scale(0.100000,-0.100000)"
fill="#000000" stroke="none">
<path d="M6065 7026 c-42 -19 -62 -44 -86 -112 -18 -49 -23 -94 -29 -264 -5
-113 -11 -218 -14 -235 -74 -422 -125 -616 -244 -940 -37 -100 -69 -180 -81
-203 -5 -9 -37 -72 -70 -140 -34 -68 -70 -135 -80 -150 -55 -80 -85 -148 -117
-257 -27 -97 -17 -98 70 -7 111 116 280 337 356 463 14 23 36 58 49 78 56 85
183 349 244 511 48 125 124 371 134 433 6 43 22 47 43 13 19 -32 134 -198 176
-256 32 -43 47 -64 167 -225 161 -216 323 -452 370 -540 28 -52 55 -122 133
-345 92 -264 142 -380 180 -411 23 -19 92 6 135 50 81 81 90 301 22 561 -23
91 -107 274 -167 365 -113 173 -193 282 -422 575 -68 86 -213 281 -249 334
-99 144 -119 184 -165 328 -80 249 -136 341 -227 372 -56 19 -88 20 -128 2z"/>
<path d="M6175 5393 c-24 -6 -120 -72 -158 -108 -16 -15 -33 -38 -38 -52 -12
-32 3 -83 32 -109 37 -34 57 -85 53 -139 -25 -374 -130 -834 -274 -1200 -17
-44 -40 -102 -50 -130 -60 -159 -216 -486 -337 -700 -90 -162 -88 -158 -149
-255 -152 -242 -284 -431 -413 -590 -524 -645 -1064 -1095 -1676 -1394 -393
-193 -728 -296 -1140 -352 -183 -25 -539 -25 -690 0 -326 52 -614 176 -825
355 -30 25 -63 53 -74 61 -10 8 -52 53 -93 100 -76 86 -99 127 -238 428 -21
45 -41 82 -45 82 -4 0 -15 -9 -26 -21 -39 -43 -26 -325 21 -460 9 -23 44 -86
79 -139 204 -306 614 -575 1046 -685 202 -52 269 -59 540 -60 258 0 325 6 535
46 712 138 1528 571 2245 1193 114 99 412 392 504 495 52 59 249 306 306 384
19 27 44 60 56 75 29 37 218 320 238 357 9 17 35 59 57 95 181 286 415 784
530 1125 11 33 25 69 30 80 5 11 19 52 30 90 101 336 133 479 181 810 6 44 12
157 12 250 1 185 -9 232 -62 304 -41 56 -130 83 -207 64z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="white" class="ionicon" viewBox="0 0 512 512"><title>Chatbubble Ellipses</title><path d="M87.48 380c1.2-4.38-1.43-10.47-3.94-14.86a42.63 42.63 0 00-2.54-3.8 199.81 199.81 0 01-33-110C47.64 139.09 140.72 48 255.82 48 356.2 48 440 117.54 459.57 209.85a199 199 0 014.43 41.64c0 112.41-89.49 204.93-204.59 204.93-18.31 0-43-4.6-56.47-8.37s-26.92-8.77-30.39-10.11a31.14 31.14 0 00-11.13-2.07 30.7 30.7 0 00-12.08 2.43L81.5 462.78a15.92 15.92 0 01-4.66 1.22 9.61 9.61 0 01-9.58-9.74 15.85 15.85 0 01.6-3.29z" fill="none" stroke="white" stroke-linecap="round" stroke-miterlimit="10" stroke-width="32"/><circle cx="160" cy="256" r="32"/><circle cx="256" cy="256" r="32"/><circle cx="352" cy="256" r="32"/></svg>

After

Width:  |  Height:  |  Size: 748 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" fill="white" viewBox="0 0 512 512"><title>Create</title><path d="M384 224v184a40 40 0 01-40 40H104a40 40 0 01-40-40V168a40 40 0 0140-40h167.48" fill="none" stroke="white" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/><path d="M459.94 53.25a16.06 16.06 0 00-23.22-.56L424.35 65a8 8 0 000 11.31l11.34 11.32a8 8 0 0011.34 0l12.06-12c6.1-6.09 6.67-16.01.85-22.38zM399.34 90L218.82 270.2a9 9 0 00-2.31 3.93L208.16 299a3.91 3.91 0 004.86 4.86l24.85-8.35a9 9 0 003.93-2.31L422 112.66a9 9 0 000-12.66l-9.95-10a9 9 0 00-12.71 0z"/></svg>

After

Width:  |  Height:  |  Size: 604 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" fill="#fff" viewBox="0 0 512 512"><title>Ellipsis Horizontal</title><circle cx="256" cy="256" r="48"/><circle cx="416" cy="256" r="48"/><circle cx="96" cy="256" r="48"/></svg>

After

Width:  |  Height:  |  Size: 231 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512"><title>Ellipsis Horizontal</title><circle cx="256" cy="256" r="48"/><circle cx="416" cy="256" r="48"/><circle cx="96" cy="256" r="48"/></svg>

After

Width:  |  Height:  |  Size: 219 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.4 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512"><title>Exit</title><path d="M320 176v-40a40 40 0 00-40-40H88a40 40 0 00-40 40v240a40 40 0 0040 40h192a40 40 0 0040-40v-40M384 176l80 80-80 80M191 256h273" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="32"/></svg>

After

Width:  |  Height:  |  Size: 339 B

View File

@@ -0,0 +1,3 @@
<svg width="33" height="33" viewBox="0 0 33 33" xmlns="http://www.w3.org/2000/svg">
<path fill="#6b7280" d="M15.251 4.9995C15.6755 5.10585 16.0403 5.37646 16.2653 5.7518C16.4902 6.12714 16.5569 6.57647 16.4505 7.00095L15.7245 9.9H20.5755L21.4995 6.19905C21.5509 5.98753 21.6437 5.78827 21.7724 5.61274C21.9011 5.43722 22.0633 5.2889 22.2496 5.17633C22.4359 5.06376 22.6427 4.98917 22.8579 4.95686C23.0732 4.92454 23.2927 4.93513 23.5039 4.98803C23.715 5.04092 23.9136 5.13507 24.0882 5.26506C24.2628 5.39504 24.41 5.55829 24.5212 5.7454C24.6324 5.9325 24.7056 6.13977 24.7363 6.35525C24.7671 6.57074 24.755 6.79018 24.7005 7.00095L23.9745 9.9H28.05C28.4877 9.9 28.9073 10.0738 29.2168 10.3833C29.5262 10.6927 29.7 11.1124 29.7 11.55C29.7 11.9876 29.5262 12.4073 29.2168 12.7167C28.9073 13.0262 28.4877 13.2 28.05 13.2H23.1495L21.4995 19.8H24.75C25.1877 19.8 25.6073 19.9738 25.9168 20.2833C26.2262 20.5927 26.4 21.0124 26.4 21.45C26.4 21.8876 26.2262 22.3073 25.9168 22.6167C25.6073 22.9262 25.1877 23.1 24.75 23.1H20.6745L19.7505 26.7993C19.7011 27.0127 19.6096 27.2141 19.4814 27.3918C19.3533 27.5695 19.1911 27.7198 19.0042 27.8341C18.8173 27.9485 18.6096 28.0244 18.393 28.0576C18.1765 28.0908 17.9555 28.0805 17.743 28.0273C17.5305 27.9742 17.3307 27.8793 17.1552 27.7481C16.9798 27.617 16.8322 27.4522 16.7211 27.2634C16.61 27.0746 16.5376 26.8655 16.5082 26.6485C16.4787 26.4314 16.4928 26.2106 16.5495 25.999L17.2755 23.1H12.4245L11.5005 26.7993C11.4511 27.0127 11.3596 27.2141 11.2315 27.3918C11.1033 27.5695 10.9411 27.7198 10.7542 27.8341C10.5673 27.9485 10.3596 28.0244 10.143 28.0576C9.9265 28.0908 9.70553 28.0805 9.49301 28.0273C9.28049 27.9742 9.08067 27.8793 8.90522 27.7481C8.72977 27.617 8.5822 27.4522 8.4711 27.2634C8.36001 27.0746 8.28763 26.8655 8.25817 26.6485C8.22872 26.4314 8.24278 26.2106 8.29955 25.999L9.02555 23.1H4.95005C4.51244 23.1 4.09276 22.9262 3.78332 22.6167C3.47389 22.3073 3.30005 21.8876 3.30005 21.45C3.30005 21.0124 3.47389 20.5927 3.78332 20.2833C4.09276 19.9738 4.51244 19.8 4.95005 19.8H9.85055L11.5005 13.2H8.25005C7.81244 13.2 7.39276 13.0262 7.08332 12.7167C6.77389 12.4073 6.60005 11.9876 6.60005 11.55C6.60005 11.1124 6.77389 10.6927 7.08332 10.3833C7.39276 10.0738 7.81244 9.9 8.25005 9.9H12.3255L13.2495 6.19905C13.3559 5.77458 13.6265 5.40973 14.0018 5.18477C14.3772 4.95982 14.8265 4.89317 15.251 4.9995V4.9995ZM14.8995 13.2L13.2495 19.8H18.0972L19.7472 13.2H14.9012H14.8995Z"/>
</svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" viewBox="0 0 512 512"><title>Menu</title><path fill="none" stroke="white" stroke-linecap="round" stroke-miterlimit="10" stroke-width="32" d="M80 160h352M80 256h352M80 352h352"/></svg>

After

Width:  |  Height:  |  Size: 239 B

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 26 33" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;">
<use xlink:href="#_Image1" x="0" y="0" width="26px" height="33px"/>
<defs>
<image id="_Image1" width="26px" height="33px" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABoAAAAhCAYAAADH97ugAAAACXBIWXMAAA7EAAAOxAGVKw4bAAADfElEQVRIid2WXUxbZRjHf+d9UaAFWqCMUYHNAoqiMzG6GA2Lzq8b0imZ4ucSdeqFm8kki1+RLerUzehmJNF5MT+SsWzzI0GZmMwE4kSrcbBJGHSsgKwFlgHDTbYB53290NY0oy0t3Y3/5Ny8z3neX56P85zHAHDhXgy8LaRYrkyVwzwlpBhWpmoCnvfROApguHAvNoRxODXtEmtVTaUoKHJgGEbCEKU0A71D7NtzAK31aaV0hY/GQVy4915tWWn6evw6mfK0duoSY4V24Z5w4c4VQorlVTWV4vIrnPPNWJiWLqtg6bIKhDCygDeFMlVOQZEjqZCgnMV5GEIA3CWAedUkqv67dpGIx29m2mR/4y8JMeMCNWxv5ukVm2jZ99vFA01PzfDRli8BqH9t98UBnZ08z2f1TQwNngSg/ecevv28jempmTmDUiIZTo2dYd3D7+DtHGDEP4bWOsy+5r7NSClwFudx7Q2lbGuoRabI+EFSCgZ6hxg+PhrR2TQVg30jOBZmQ4zOjZi6TJuFXS2bWFRaEPWC628u59PvNiJl9CpEteZflsuu1jfIXWCb1V5WUcwnzRuxZqZHhcQEAeQ7czBNNavNYk2dE2ROoNETE5waPT2r7WjX4AVNkjCo98ggAKlpl7K69h6+6djGysduR0rB5JlzoZaPpYhdF1RJeSFrXqnhwafuZmFhLgCbdzzLk+uradzZQk7e7PWLG+TIt7Pu1YcuOC+9qpDnXn9kThCIc9bNR/8/UNQadXi8lJQXkmmz4GntZMmNZbT/1M3ZySkAbNlWJsb/Cr1/063XRPyuokb03oYG1t6/BdNUbHhmOyeHx3nhiXoOth2h+3A/fd4Abd8f4sXV79PV7uP8uanEIgIYCYzx1vqPw86y7FYysixUr7qN4/0n+HH/IdbW1US9J2aNXn73cQ62ddN/NBA6S0tPJd2SGss1TFEjsudmkpFl4YOvXmLVnXXIFIkj30bVA5WhQStTZMShGyYXbr21bmdSl8egah/dqstS7tUu3FoIKUb+ODYcVxrmqj6vH/Xv5BfKVM1Nuw/Q4fEmFdL8RRsdHm9wugcMF+4FQhjHMIyMW+64DmcSlvw+r59ff+hCSBGMqMEAcOEuAn4XUtiSsbVqpVAq9J8aA5ZIgHF6/szmyg+11nattEMrbddKk/DzDyMAfA1U+2j0/w2ivPyYTjWO+wAAAABJRU5ErkJggg=="/>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 1.8 KiB

View File

@@ -0,0 +1,11 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<g clip-path="url(#clip0_255_3833)">
<path d="M11.9777 2.37778C6.6772 2.37778 2.19995 6.85502 2.19995 12.1556C2.19995 17.4561 6.6772 21.9333 11.9777 21.9333C17.2783 21.9333 21.7555 17.4561 21.7555 12.1556C21.7555 6.85502 17.2783 2.37778 11.9777 2.37778ZM11.9777 7.26667C13.6664 7.26667 14.9111 8.5104 14.9111 10.2C14.9111 11.8896 13.6664 13.1333 11.9777 13.1333C10.2901 13.1333 9.0444 11.8896 9.0444 10.2C9.0444 8.5104 10.2901 7.26667 11.9777 7.26667ZM6.9852 16.8215C7.86226 15.5308 9.32502 14.6704 11 14.6704H12.9555C14.6314 14.6704 16.0932 15.5308 16.9703 16.8215C15.7207 18.1591 13.948 19 11.9777 19C10.0075 19 8.2348 18.1591 6.9852 16.8215Z" fill="white"/>
<circle cx="19.3111" cy="4.82221" r="4.4" fill="#22C55E"/>
</g>
<defs>
<clipPath id="clip0_255_3833">
<rect width="23.4667" height="23.4667" fill="white" transform="translate(0.244385 0.422211)"/>
</clipPath>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 981 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" fill="#fff" viewBox="0 0 512 512"><title>Reload</title><path d="M400 148l-21.12-24.57A191.43 191.43 0 00240 64C134 64 48 150 48 256s86 192 192 192a192.09 192.09 0 00181.07-128" fill="none" stroke="#fff" stroke-linecap="round" stroke-miterlimit="10" stroke-width="32"/><path d="M464 97.42V208a16 16 0 01-16 16H337.42c-14.26 0-21.4-17.23-11.32-27.31L436.69 86.1C446.77 76 464 83.16 464 97.42z"/></svg>

After

Width:  |  Height:  |  Size: 455 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" class="ionicon" fill="#fff" viewBox="0 0 512 512"><title>Send</title><path d="M476.59 227.05l-.16-.07L49.35 49.84A23.56 23.56 0 0027.14 52 24.65 24.65 0 0016 72.59v113.29a24 24 0 0019.52 23.57l232.93 43.07a4 4 0 010 7.86L35.53 303.45A24 24 0 0016 327v113.31A23.57 23.57 0 0026.59 460a23.94 23.94 0 0013.22 4 24.55 24.55 0 009.52-1.93L476.4 285.94l.19-.09a32 32 0 000-58.8z"/></svg>

After

Width:  |  Height:  |  Size: 421 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="#92400E" class="ionicon" viewBox="0 0 512 512"><title>Star</title><path d="M394 480a16 16 0 01-9.39-3L256 383.76 127.39 477a16 16 0 01-24.55-18.08L153 310.35 23 221.2a16 16 0 019-29.2h160.38l48.4-148.95a16 16 0 0130.44 0l48.4 149H480a16 16 0 019.05 29.2L359 310.35l50.13 148.53A16 16 0 01394 480z"/></svg>

After

Width:  |  Height:  |  Size: 351 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="#1186D5" class="ionicon" viewBox="0 0 512 512"><title>Time</title><path d="M256 48C141.13 48 48 141.13 48 256s93.13 208 208 208 208-93.13 208-208S370.87 48 256 48zm96 240h-96a16 16 0 01-16-16V128a16 16 0 0132 0v128h80a16 16 0 010 32z"/></svg>

After

Width:  |  Height:  |  Size: 288 B

View File

@@ -0,0 +1,3 @@
<svg width="24" height="24" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
<path d="M7.5 6.5C7.5 8.981 9.519 11 12 11C14.481 11 16.5 8.981 16.5 6.5C16.5 4.019 14.481 2 12 2C9.519 2 7.5 4.019 7.5 6.5ZM20 21H21V20C21 16.141 17.859 13 14 13H10C6.14 13 3 16.141 3 20V21H20Z" fill="#079669"/>
</svg>

After

Width:  |  Height:  |  Size: 304 B

View File

@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 155 54" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linecap:round;">
<g transform="matrix(0.98,0,0,1,39.42,36.92)">
<g transform="matrix(36,0,0,36,0,0)">
<path d="M0.037,-0.276C0.037,-0.333 0.049,-0.383 0.072,-0.426C0.094,-0.468 0.126,-0.502 0.167,-0.525C0.208,-0.548 0.254,-0.56 0.307,-0.56C0.374,-0.56 0.429,-0.544 0.473,-0.513C0.516,-0.481 0.546,-0.436 0.561,-0.377L0.438,-0.377C0.428,-0.404 0.412,-0.426 0.39,-0.441C0.368,-0.456 0.34,-0.464 0.307,-0.464C0.26,-0.464 0.223,-0.448 0.196,-0.415C0.168,-0.382 0.154,-0.335 0.154,-0.276C0.154,-0.217 0.168,-0.17 0.196,-0.137C0.223,-0.104 0.26,-0.087 0.307,-0.087C0.373,-0.087 0.417,-0.116 0.438,-0.174L0.561,-0.174C0.545,-0.118 0.515,-0.074 0.471,-0.041C0.427,-0.008 0.372,0.009 0.307,0.009C0.254,0.009 0.208,-0.003 0.167,-0.027C0.126,-0.05 0.094,-0.084 0.072,-0.127C0.049,-0.169 0.037,-0.219 0.037,-0.276Z" style="fill:rgb(53,53,53);fill-rule:nonzero;"/>
</g>
<g transform="matrix(36,0,0,36,21.6,0)">
<rect x="0.075" y="-0.74" width="0.114" height="0.74" style="fill:rgb(53,53,53);fill-rule:nonzero;"/>
</g>
<g transform="matrix(36,0,0,36,31.104,0)">
<path d="M0.037,-0.278C0.037,-0.333 0.049,-0.382 0.072,-0.425C0.094,-0.468 0.126,-0.501 0.166,-0.525C0.205,-0.548 0.249,-0.56 0.297,-0.56C0.34,-0.56 0.378,-0.552 0.411,-0.535C0.443,-0.518 0.469,-0.496 0.488,-0.471L0.488,-0.551L0.603,-0.551L0.603,-0L0.488,-0L0.488,-0.082C0.469,-0.056 0.442,-0.034 0.409,-0.017C0.376,0 0.338,0.009 0.295,0.009C0.248,0.009 0.204,-0.003 0.165,-0.028C0.126,-0.052 0.094,-0.086 0.072,-0.13C0.049,-0.173 0.037,-0.223 0.037,-0.278ZM0.488,-0.276C0.488,-0.314 0.48,-0.347 0.465,-0.375C0.449,-0.403 0.428,-0.424 0.403,-0.439C0.378,-0.454 0.35,-0.461 0.321,-0.461C0.292,-0.461 0.264,-0.454 0.239,-0.44C0.214,-0.425 0.193,-0.404 0.178,-0.377C0.162,-0.349 0.154,-0.316 0.154,-0.278C0.154,-0.24 0.162,-0.207 0.178,-0.178C0.193,-0.149 0.214,-0.128 0.24,-0.113C0.265,-0.097 0.292,-0.09 0.321,-0.09C0.35,-0.09 0.378,-0.097 0.403,-0.112C0.428,-0.127 0.449,-0.148 0.465,-0.177C0.48,-0.205 0.488,-0.238 0.488,-0.276Z" style="fill:rgb(53,53,53);fill-rule:nonzero;"/>
</g>
<g transform="matrix(36,0,0,36,55.512,0)">
<path d="M0.189,-0.47C0.208,-0.495 0.235,-0.517 0.268,-0.534C0.301,-0.551 0.339,-0.56 0.381,-0.56C0.429,-0.56 0.473,-0.548 0.513,-0.525C0.552,-0.501 0.583,-0.468 0.606,-0.425C0.629,-0.382 0.64,-0.333 0.64,-0.278C0.64,-0.223 0.629,-0.173 0.606,-0.13C0.583,-0.086 0.552,-0.052 0.513,-0.028C0.473,-0.003 0.429,0.009 0.381,0.009C0.339,0.009 0.302,0.001 0.269,-0.017C0.236,-0.034 0.21,-0.055 0.189,-0.08L0.189,0.262L0.075,0.262L0.075,-0.551L0.189,-0.551L0.189,-0.47ZM0.524,-0.278C0.524,-0.316 0.516,-0.349 0.501,-0.377C0.485,-0.404 0.464,-0.425 0.439,-0.44C0.413,-0.454 0.385,-0.461 0.356,-0.461C0.327,-0.461 0.3,-0.454 0.275,-0.439C0.249,-0.424 0.228,-0.403 0.213,-0.375C0.197,-0.347 0.189,-0.314 0.189,-0.276C0.189,-0.238 0.197,-0.205 0.213,-0.177C0.228,-0.148 0.249,-0.127 0.275,-0.112C0.3,-0.097 0.327,-0.09 0.356,-0.09C0.385,-0.09 0.413,-0.097 0.439,-0.113C0.464,-0.128 0.485,-0.149 0.501,-0.178C0.516,-0.207 0.524,-0.24 0.524,-0.278Z" style="fill:rgb(53,53,53);fill-rule:nonzero;"/>
</g>
<g transform="matrix(36,0,0,36,79.92,0)">
<path d="M0.58,-0.289C0.58,-0.268 0.579,-0.25 0.576,-0.233L0.155,-0.233C0.158,-0.189 0.175,-0.154 0.204,-0.127C0.233,-0.1 0.269,-0.087 0.312,-0.087C0.373,-0.087 0.417,-0.113 0.442,-0.164L0.565,-0.164C0.548,-0.113 0.518,-0.072 0.475,-0.04C0.431,-0.007 0.377,0.009 0.312,0.009C0.259,0.009 0.212,-0.003 0.171,-0.027C0.129,-0.05 0.096,-0.084 0.073,-0.127C0.049,-0.169 0.037,-0.219 0.037,-0.276C0.037,-0.333 0.049,-0.383 0.072,-0.426C0.094,-0.468 0.127,-0.502 0.169,-0.525C0.21,-0.548 0.258,-0.56 0.312,-0.56C0.364,-0.56 0.41,-0.549 0.451,-0.526C0.492,-0.503 0.523,-0.471 0.546,-0.431C0.569,-0.389 0.58,-0.342 0.58,-0.289ZM0.461,-0.325C0.46,-0.367 0.445,-0.401 0.416,-0.426C0.387,-0.451 0.35,-0.464 0.307,-0.464C0.268,-0.464 0.234,-0.452 0.206,-0.427C0.178,-0.401 0.161,-0.368 0.156,-0.325L0.461,-0.325Z" style="fill:rgb(53,53,53);fill-rule:nonzero;"/>
</g>
<g transform="matrix(36,0,0,36,102.132,0)">
<path d="M0.189,-0.471C0.206,-0.499 0.228,-0.521 0.256,-0.537C0.283,-0.552 0.316,-0.56 0.354,-0.56L0.354,-0.442L0.325,-0.442C0.28,-0.442 0.247,-0.431 0.224,-0.408C0.201,-0.385 0.189,-0.346 0.189,-0.29L0.189,-0L0.075,-0L0.075,-0.551L0.189,-0.551L0.189,-0.471Z" style="fill:rgb(53,53,53);fill-rule:nonzero;"/>
</g>
</g>
<g id="Logo">
<path d="M6.8,33.5C6.273,34.098 5.513,34.441 4.715,34.441C3.785,34.441 2.915,33.974 2.4,33.2C1.013,31.038 0.188,28.562 0,26C-0.186,24.019 -0.017,22.021 0.5,20.1C0.9,18.7 1.9,17.9 3.2,18.2C4.22,18.433 4.949,19.348 4.949,20.394C4.949,20.669 4.899,20.943 4.8,21.2C4.234,23.436 4.269,25.782 4.9,28C7.8,24.2 10.5,20.7 13.2,17.1C14.7,15.1 16.2,13.1 17.7,11.2C18.562,10.149 20.124,9.971 21.2,10.8C21.87,11.14 22.295,11.831 22.295,12.583C22.295,13.067 22.119,13.536 21.8,13.9L6.8,33.5Z" style="fill:rgb(20,191,219);fill-rule:nonzero;"/>
<path d="M10.4,35.7L26.7,14.8" style="fill:none;fill-rule:nonzero;stroke:rgb(41,172,237);stroke-width:4px;"/>
<path d="M17.2,37L29.7,21.2" style="fill:none;fill-rule:nonzero;stroke:rgb(134,17,237);stroke-width:4px;"/>
<path d="M25.2,36.6L31.5,28.2" style="fill:none;fill-rule:nonzero;stroke:rgb(184,15,239);stroke-width:4px;"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 5.7 KiB

View File

@@ -0,0 +1 @@
<svg id="Calque_1" data-name="Calque 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 154.1 53.4"><defs><style>.cls-1{isolation:isolate;}.cls-2{fill:#fff;}.cls-3{fill:#14bfdb;}.cls-4,.cls-5,.cls-6{fill:none;stroke-linecap:round;stroke-miterlimit:10;stroke-width:4px;}.cls-4{stroke:#29aced;}.cls-5{stroke:#8611ed;}.cls-6{stroke:#b80fef;}</style></defs><g class="cls-1"><path class="cls-2" d="M41.94,21.6A8.79,8.79,0,0,1,45.32,18a9.59,9.59,0,0,1,5-1.26,9.56,9.56,0,0,1,5.84,1.71,8.4,8.4,0,0,1,3.13,4.88H54.9A4.73,4.73,0,0,0,53.2,21a5,5,0,0,0-2.93-.82A4.82,4.82,0,0,0,46.33,22a7.62,7.62,0,0,0-1.47,5,7.71,7.71,0,0,0,1.47,5,4.81,4.81,0,0,0,3.94,1.8,4.49,4.49,0,0,0,4.63-3.13h4.34a8.83,8.83,0,0,1-3.18,4.8,9.24,9.24,0,0,1-5.79,1.78,9.5,9.5,0,0,1-5-1.27,9,9,0,0,1-3.38-3.6A11.48,11.48,0,0,1,40.72,27,11.44,11.44,0,0,1,41.94,21.6Z"/><path class="cls-2" d="M67.3,10.28V36.92h-4V10.28Z"/><path class="cls-2" d="M72.48,21.62A9,9,0,0,1,75.8,18a8.79,8.79,0,0,1,4.65-1.28,8.42,8.42,0,0,1,4,.92A8.26,8.26,0,0,1,87.2,20V17.08h4.06V36.92H87.2V34a8.24,8.24,0,0,1-2.8,2.34,8.92,8.92,0,0,1-8.62-.38,9.26,9.26,0,0,1-3.3-3.67,11.4,11.4,0,0,1-1.22-5.35A11.07,11.07,0,0,1,72.48,21.62Zm13.89,1.8a5.84,5.84,0,0,0-2.18-2.3,5.58,5.58,0,0,0-2.9-.8,5.65,5.65,0,0,0-2.89.78,5.75,5.75,0,0,0-2.18,2.27,7.18,7.18,0,0,0-.83,3.54,7.53,7.53,0,0,0,.83,3.6,6,6,0,0,0,2.19,2.36,5.62,5.62,0,0,0,5.78,0,5.9,5.9,0,0,0,2.18-2.32A7.46,7.46,0,0,0,87.2,27,7.34,7.34,0,0,0,86.37,23.42Z"/><path class="cls-2" d="M103.38,17.7a8.35,8.35,0,0,1,4-.94A8.78,8.78,0,0,1,112,18a8.89,8.89,0,0,1,3.31,3.58,11.3,11.3,0,0,1,1.2,5.29,11.64,11.64,0,0,1-1.2,5.35A9.14,9.14,0,0,1,112,35.93a8.54,8.54,0,0,1-4.64,1.31,8.32,8.32,0,0,1-4-.91A9,9,0,0,1,100.59,34V46.35h-4V17.08h4V20A8.13,8.13,0,0,1,103.38,17.7Zm8.22,5.67a5.77,5.77,0,0,0-5.11-3.05,5.64,5.64,0,0,0-2.88.8,5.79,5.79,0,0,0-2.19,2.3,7.34,7.34,0,0,0-.83,3.56,7.46,7.46,0,0,0,.83,3.59,5.85,5.85,0,0,0,2.19,2.32,5.66,5.66,0,0,0,5.8,0,6,6,0,0,0,2.19-2.36,7.53,7.53,0,0,0,.83-3.6A7.18,7.18,0,0,0,111.6,23.37Z"/><path class="cls-2" d="M138.23,28.53H123.35a5.54,5.54,0,0,0,1.73,3.82,5.42,5.42,0,0,0,3.82,1.44A4.69,4.69,0,0,0,133.49,31h4.35a8.93,8.93,0,0,1-3.2,4.48,9.28,9.28,0,0,1-5.74,1.74,9.81,9.81,0,0,1-5-1.27,9.11,9.11,0,0,1-3.47-3.6A11.26,11.26,0,0,1,119.18,27a11.44,11.44,0,0,1,1.22-5.38A8.65,8.65,0,0,1,123.83,18a10,10,0,0,1,5.07-1.26A9.83,9.83,0,0,1,133.81,18a8.62,8.62,0,0,1,3.36,3.44,10.56,10.56,0,0,1,1.2,5.1A13.58,13.58,0,0,1,138.23,28.53Zm-4.06-3.31a4.75,4.75,0,0,0-1.6-3.64,5.61,5.61,0,0,0-3.85-1.36,5.12,5.12,0,0,0-3.57,1.35,5.61,5.61,0,0,0-1.76,3.65Z"/><path class="cls-2" d="M148.71,17.61a6.8,6.8,0,0,1,3.48-.85V21h-1a4.85,4.85,0,0,0-3.58,1.22c-.82.82-1.22,2.23-1.22,4.25V36.92h-4V17.08h4V20A6.38,6.38,0,0,1,148.71,17.61Z"/></g><g id="Logo"><path class="cls-3" d="M6.8,33.5a2.78,2.78,0,0,1-4.4-.3A15.42,15.42,0,0,1,0,26a16.69,16.69,0,0,1,.5-5.9c.4-1.4,1.4-2.2,2.7-1.9a2.25,2.25,0,0,1,1.6,3A13.1,13.1,0,0,0,4.9,28c2.9-3.8,5.6-7.3,8.3-10.9,1.5-2,3-4,4.5-5.9a2.53,2.53,0,0,1,3.5-.4,2,2,0,0,1,.6,3.1Z"/><line class="cls-4" x1="10.4" y1="35.7" x2="26.7" y2="14.8"/><line class="cls-5" x1="17.2" y1="37" x2="29.7" y2="21.2"/><line class="cls-6" x1="25.2" y1="36.6" x2="31.5" y2="28.2"/></g></svg>

After

Width:  |  Height:  |  Size: 3.1 KiB

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 24.2.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="Calque_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
viewBox="0 0 33.9 29" style="enable-background:new 0 0 33.9 29;" xml:space="preserve">
<style type="text/css">
.st0{fill:#FFFFFF;}
.st1{fill:none;stroke:#FFFFFF;stroke-width:4;stroke-linecap:round;stroke-miterlimit:10;}
</style>
<g id="Logo">
<path class="st0" d="M6.8,23.3c-1,1.2-2.8,1.3-3.9,0.2c-0.2-0.2-0.3-0.3-0.5-0.5C1,20.9,0.2,18.4,0,15.8c-0.2-2,0-3.9,0.5-5.9
c0.4-1.4,1.4-2.2,2.7-1.9c1.2,0.3,2,1.5,1.7,2.7c0,0.1-0.1,0.2-0.1,0.3c-0.6,2.2-0.5,4.6,0.1,6.8c2.9-3.8,5.6-7.3,8.3-10.9
c1.5-2,3-4,4.5-5.9c0.9-1.1,2.4-1.2,3.5-0.4c1,0.5,1.4,1.7,0.9,2.7c-0.1,0.1-0.2,0.3-0.3,0.4L6.8,23.3z"/>
<line class="st1" x1="10.4" y1="25.5" x2="26.7" y2="4.6"/>
<line class="st1" x1="17.2" y1="26.8" x2="29.7" y2="11"/>
<line class="st1" x1="25.2" y1="26.4" x2="31.5" y2="18"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
assets/images/logo.svg Normal file
View File

@@ -0,0 +1 @@
<svg id="Calque_1" data-name="Calque 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 33.91 28.98"><defs><style>.cls-1{fill:#14bfdb;}.cls-2,.cls-3,.cls-4{fill:none;stroke-linecap:round;stroke-miterlimit:10;stroke-width:4px;}.cls-2{stroke:#29aced;}.cls-3{stroke:#8611ed;}.cls-4{stroke:#b80fef;}</style></defs><g id="Logo"><path class="cls-1" d="M6.8,23.35a2.78,2.78,0,0,1-4.4-.3A15.42,15.42,0,0,1,0,15.85,16.69,16.69,0,0,1,.5,10c.4-1.4,1.4-2.2,2.7-1.9a2.25,2.25,0,0,1,1.6,3,13.1,13.1,0,0,0,.1,6.8c2.9-3.8,5.6-7.3,8.3-10.9,1.5-2,3-4,4.5-5.9a2.53,2.53,0,0,1,3.5-.4,2,2,0,0,1,.6,3.1Z"/><line class="cls-2" x1="10.4" y1="25.55" x2="26.7" y2="4.65"/><line class="cls-3" x1="17.2" y1="26.85" x2="29.7" y2="11.05"/><line class="cls-4" x1="25.2" y1="26.45" x2="31.5" y2="18.05"/></g></svg>

After

Width:  |  Height:  |  Size: 782 B

BIN
assets/images/mobile.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 504 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 432 KiB

472
assets/js/app.js Normal file
View File

@@ -0,0 +1,472 @@
// If you want to use Phoenix channels, run `mix help phx.gen.channel`
// to get started and then uncomment the line below.
// import "./user_socket.js"
// You can include dependencies in two ways.
//
// The simplest option is to put them in assets/vendor and
// import them using relative paths:
//
// import "./vendor/some-package.js"
//
// Alternatively, you can `npm install some-package` and import
// them using a path starting with the package name:
//
// import "some-package"
//
// Include phoenix_html to handle method=PUT/DELETE in forms and buttons.
import "phoenix_html"
// Establish Phoenix Socket and LiveView configuration.
import {Socket, Presence} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
import topbar from "../vendor/topbar"
import Alpine from 'alpinejs'
import flatpickr from "flatpickr"
import moment from "moment-timezone"
import QRCodeStyling from "qr-code-styling"
import { Presenter } from "./presenter"
import { Manager } from "./manager"
window.moment = moment
window.moment.locale('fr', {
months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
monthsParseExact : true,
weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
weekdaysMin : 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'),
weekdaysParseExact : true,
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY HH:mm',
LLLL : 'dddd D MMMM YYYY HH:mm'
},
calendar : {
sameDay : '[Aujourdhui à] LT',
nextDay : '[Demain à] LT',
nextWeek : 'dddd [à] LT',
lastDay : '[Hier à] LT',
lastWeek : 'dddd [dernier à] LT',
sameElse : 'L'
},
relativeTime : {
future : 'dans %s',
past : 'il y a %s',
s : 'quelques secondes',
m : 'une minute',
mm : '%d minutes',
h : 'une heure',
hh : '%d heures',
d : 'un jour',
dd : '%d jours',
M : 'un mois',
MM : '%d mois',
y : 'un an',
yy : '%d ans'
},
dayOfMonthOrdinalParse : /\d{1,2}(er|e)/,
ordinal : function (number) {
return number + (number === 1 ? 'er' : 'e');
},
meridiemParse : /PD|MD/,
isPM : function (input) {
return input.charAt(0) === 'M';
},
// In case the meridiem units are not separated around 12, then implement
// this function (look at locale/id.js for an example).
// meridiemHour : function (hour, meridiem) {
// return /* 0-23 hour, given meridiem token and hour 1-12 */ ;
// },
meridiem : function (hours, minutes, isLower) {
return hours < 12 ? 'PD' : 'MD';
},
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // Used to determine first week of the year.
}
});
window.moment.locale(navigator.languages[0].split('-')[0])
window.Alpine = Alpine
Alpine.start()
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let Hooks = {}
Hooks.Scroll = {
mounted() {
if (this.el.dataset.postsNb > 4) window.scrollTo({top: document.querySelector(this.el.dataset.target).scrollHeight, behavior: 'smooth'});
this.handleEvent("scroll", () => {
let t = document.querySelector(this.el.dataset.target)
if (this.el.childElementCount > 4 && (window.scrollY + window.innerHeight >= t.offsetHeight - 100)) {
window.scrollTo({top: t.scrollHeight, behavior: 'smooth'});
}
})
}
}
Hooks.ScrollIntoDiv = {
mounted() {
let t = document.querySelector(this.el.dataset.target)
if (this.el.dataset.postsNb > 4) t.scrollTo({top: t.scrollHeight, behavior: 'smooth'});
this.handleEvent("scroll", () => {
let t = document.querySelector(this.el.dataset.target);
if (this.el.childElementCount > 4 && (t.scrollHeight - t.scrollTop < t.clientHeight + 100)) {
t.scrollTo({top: t.scrollHeight, behavior: 'smooth'});
}
})
}
}
Hooks.PostForm = {
onPress(e, submitBtn, TA) {
if (e.key == "Enter" && !e.shiftKey) {
e.preventDefault()
submitBtn.click()
} else {
if (TA.value.length > 2) {
submitBtn.classList.remove("opacity-50")
submitBtn.classList.add("opacity-100")
} else {
submitBtn.classList.add("opacity-50")
submitBtn.classList.remove("opacity-100")
}
}
},
onSubmit(e, TA) {
e.preventDefault()
document.getElementById("hiddenSubmit").click()
TA.value = ""
},
mounted() {
const submitBtn = document.getElementById("submitBtn")
const TA = document.getElementById("postFormTA")
submitBtn.addEventListener("click", (e) => this.onSubmit(e, TA))
TA.addEventListener("keydown", (e) => this.onPress(e, submitBtn, TA))
},
updated() {
const submitBtn = document.getElementById("submitBtn")
const TA = document.getElementById("postFormTA")
if (TA.value.length > 2) {
submitBtn.classList.remove("opacity-50")
submitBtn.classList.add("opacity-100")
} else {
submitBtn.classList.add("opacity-50")
submitBtn.classList.remove("opacity-100")
}
},
destroyed() {
const submitBtn = document.getElementById("submitBtn")
const TA = document.getElementById("postFormTA")
TA.removeEventListener("keydown", (e) => this.onPress(e, submitBtn, TA))
submitBtn.removeEventListener("click", (e) => this.onSubmit(e, TA))
}
}
Hooks.CalendarLocalDate = {
mounted() {
this.el.innerHTML = moment.utc(this.el.dataset.date).local().calendar()
},
updated() {
this.el.innerHTML = moment.utc(this.el.dataset.date).local().calendar()
}
}
Hooks.Pickr = {
mounted() {
const getDefaultDate = (dateStart, dateEnd, mode) => {
if (mode == "range") {
return moment.utc(dateStart).format('Y-MM-DD HH:mm') + " - " + moment.utc(dateEnd).format('Y-MM-DD HH:mm')
} else {
return moment.utc(dateStart).format('Y-MM-DD HH:mm')
}
};
this.pickr = flatpickr(this.el, {
wrap: true,
inline: false,
enableTime: true,
enable: JSON.parse(this.el.dataset.enable),
time_24hr: true,
formatDate: (date, format, locale) => {
return moment(date).utc().format('Y-MM-DD HH:mm');
},
parseDate: (datestr, format) => {
return moment.utc(datestr).local().toDate();
},
locale: {
firstDayOfWeek: 1,
rangeSeparator: ' - '
},
mode: this.el.dataset.mode == "range" ? "range" : "single",
minuteIncrement: 1,
dateFormat: "Y-m-d H:i",
defaultDate: getDefaultDate(this.el.dataset.defaultDateStart, this.el.dataset.defaultDateEnd, this.el.dataset.mode)
})
},
updated() {
},
destroyed() {
this.pickr.destroy()
}
}
Hooks.Presenter = {
mounted() {
this.presenter = new Presenter(this)
this.presenter.init()
}
}
Hooks.Manager = {
mounted() {
this.manager = new Manager(this)
this.manager.init()
},
updated() {
this.manager.update()
}
}
Hooks.OpenPresenter = {
open(e) {
e.preventDefault()
window.open(this.el.dataset.url, 'newwindow',
'width=' + window.screen.width + ',height=' + window.screen.height)
},
mounted() {
this.el.addEventListener("click", e => this.open(e))
},
updated() {
this.el.removeEventListener("click", e => this.open(e))
this.el.addEventListener("click", e => this.open(e))
},
destroyed() {
this.el.removeEventListener("click", e => this.open(e))
}
}
Hooks.GlobalReacts = {
mounted() {
this.handleEvent('global-react', data => {
var img = document.createElement("img");
img.src = "/images/icons/" + data.type + ".svg"
img.className = "react-animation absolute transform opacity-0" + this.el.className
this.el.appendChild(img)
})
this.handleEvent('reset-global-react', data => {
this.el.innerHTML = ""
})
}
}
Hooks.JoinEvent = {
mounted() {
const loading = document.getElementById("loading")
const submit = document.getElementById("submit")
const input = document.getElementById("input")
submit.addEventListener("click", (e) => {
if (input.value.length > 0) {
submit.style.display = "none"
loading.style.display = "block"
}
})
},
destroyed() {
const loading = document.getElementById("loading")
const submit = document.getElementById("submit")
const input = document.getElementById("input")
submit.removeEventListener("click", (e) => {
if (input.value.length > 0) {
submit.style.display = "none"
loading.style.display = "block"
}
})
}
}
Hooks.WelcomeEarly = {
mounted() {
if (localStorage.getItem("welcome-early") !== "false") {
this.el.style.display = "block"
this.el.children[0].addEventListener("click", (e) => {
e.preventDefault()
localStorage.setItem("welcome-early", "false")
this.el.style.display = "none"
})
}
},
destroyed() {
this.el.children[0].removeEventListener("click", (e) => {
e.preventDefault()
localStorage.setItem("welcome-early", "false")
this.el.style.display = "none"
})
}
}
Hooks.DefaultValue = {
mounted() {
this.el.value = moment(this.el.dataset.defaultValue ? this.el.dataset.defaultValue : undefined).utc().format();
}
}
Hooks.ClickFeedback = {
clicked(e) {
this.el.className = "animate__animated animate__rubberBand animate__faster";
setTimeout(() => {
this.el.className = "";
} , 500);
},
mounted() {
this.el.addEventListener("click", (e) => this.clicked(e))
},
destroy() {
this.el.removeEventListener("click", (e) => this.clicked(e))
}
}
Hooks.QRCode = {
draw() {
var url = this.el.dataset.code ? window.location.protocol + "//" + window.location.host + "/e/" + this.el.dataset.code : window.location.href;
this.el.style.width = document.documentElement.clientWidth * .27 + "px"
this.el.style.height = document.documentElement.clientWidth * .27 + "px"
if (this.qrCode == null) {
this.qrCode = new QRCodeStyling({
width: this.el.dataset.dynamic ? document.documentElement.clientWidth * .25 : 240,
height: this.el.dataset.dynamic ? document.documentElement.clientWidth * .25 : 240,
margin: 0,
image:
"/images/logo.png",
data: url,
cornersSquareOptions: {
type: "square"
},
dotsOptions: {
type: "square",
gradient: {
type: "linear",
rotation: Math.PI * 0.2,
colorStops: [{
offset: 0,
color: '#14bfdb'
}, {
offset: 1,
color: '#b80fef'
}]}
},
imageOptions: {
crossOrigin: "anonymous",
imageSize: 0.6,
margin: 10
}
})
this.qrCode.append(this.el)
} else {
this.qrCode.update({
width: this.el.dataset.dynamic ? document.documentElement.clientWidth * .25 : 240,
height: this.el.dataset.dynamic ? document.documentElement.clientWidth * .25 : 240
})
}
},
mounted() {
window.addEventListener("resize", this.draw.bind(this));
this.draw()
if (this.el.dataset.getUrl) {
setTimeout(() => {
var dataURL = this.qrCode._canvas.toDataURL()
document.getElementById("qr-url").value = dataURL
}, 500);
}
},
updated() {
},
destroyed() {
}
}
let Uploaders = {}
Uploaders.S3 = function(entries, onViewError){
entries.forEach(entry => {
let formData = new FormData()
let {url, fields} = entry.meta
Object.entries(fields).forEach(([key, val]) => formData.append(key, val))
formData.append("file", entry.file)
let xhr = new XMLHttpRequest()
onViewError(() => xhr.abort())
xhr.onload = () => xhr.status === 204 ? entry.progress(100) : entry.error()
xhr.onerror = () => entry.error()
xhr.upload.addEventListener("progress", (event) => {
if(event.lengthComputable){
let percent = Math.round((event.loaded / event.total) * 100)
if(percent < 100){ entry.progress(percent) }
}
})
xhr.open("POST", url, true)
xhr.send(formData)
})
}
let liveSocket = new LiveSocket("/live", Socket, {
uploaders: Uploaders,
params: {_csrf_token: csrfToken, tz: Intl.DateTimeFormat().resolvedOptions().timeZone},
hooks: Hooks,
dom: {
onBeforeElUpdated(from, to){
if(from._x_dataStack){
window.Alpine.clone(from, to)
window.Alpine.initTree(to)
}
}
},})
// Show progress bar on live navigation and form submits
let topBarScheduled = undefined
topbar.config({barColors: {0: "#fff"}, shadowColor: "rgba(0, 0, 0, .3)"})
window.addEventListener("phx:page-loading-start", info => {
if(!topBarScheduled) {
topBarScheduled = setTimeout(() => topbar.show(), 500)
}
})
window.addEventListener("phx:page-loading-stop", info => {
clearTimeout(topBarScheduled)
topBarScheduled = undefined
topbar.hide()
})
const renderOnlineUsers = function(presences) {
let onlineUsers = Presence.list(presences, (_id, {metas: [user, ...rest]}) => {
return onlineUserTemplate(user);
}).join("")
document.querySelector("body").innerHTML = onlineUsers;
}
const onlineUserTemplate = function(user) {
return `
<div id="online-user">
<strong class="text-secondary">aaa</strong>
</div>
`
}
let presences = {};
liveSocket.on("presence_state", state => {
presences = Presence.syncState(presences, state)
renderOnlineUsers(presences)
})
// connect if there are any LiveViews on the page
liveSocket.connect()
// expose liveSocket on window for web console debug logs and latency simulation:
// >> liveSocket.enableDebug()
// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session
// >> liveSocket.disableLatencySim()
window.liveSocket = liveSocket

78
assets/js/manager.js Normal file
View File

@@ -0,0 +1,78 @@
import { tns } from "tiny-slider"
export class Manager {
constructor(context) {
this.context = context
this.currentPage = parseInt(context.el.dataset.currentPage)
this.maxPage = parseInt(context.el.dataset.maxPage)
}
init() {
this.context.handleEvent('page-manage', data => {
var el = document.getElementById("slide-preview-" + data.current_page)
if (el) {
setTimeout(() => {
document.getElementById("slide-preview-" + data.current_page).scrollIntoView({
block: 'center',
behavior: 'smooth'
});
}, data.timeout ? data.timeout : 0)
}
})
window.addEventListener('keydown', (e) => {
if (e.target.tagName.toLowerCase() != "input") {
e.preventDefault()
switch (e.key) {
case 'ArrowUp':
this.prevPage()
break
case 'ArrowLeft':
this.prevPage()
break
case 'ArrowRight':
this.nextPage()
break
case 'ArrowDown':
this.nextPage()
break
}
}
});
}
update() {
this.currentPage = parseInt(this.context.el.dataset.currentPage)
var el = document.getElementById("slide-preview-" + this.currentPage)
if (el) {
document.getElementById("slide-preview-" + this.currentPage).scrollIntoView({
block: 'center',
behavior: 'smooth'
});
}
}
nextPage() {
if(this.currentPage == this.maxPage - 1)
return;
this.currentPage += 1;
this.context.pushEventTo(this.context.el, "current-page", {"page": this.currentPage.toString()});
}
prevPage() {
if(this.currentPage == 0)
return;
this.currentPage -= 1;
this.context.pushEventTo(this.context.el, "current-page", {"page": this.currentPage.toString()});
}
}

105
assets/js/presenter.js Normal file
View File

@@ -0,0 +1,105 @@
import { tns } from "tiny-slider"
export class Presenter {
constructor(context) {
this.context = context
this.currentPage = parseInt(context.el.dataset.currentPage)
this.maxPage = parseInt(context.el.dataset.maxPage)
this.hash = context.el.dataset.hash
}
init() {
this.slider = tns({
container: '#slider',
items: 1,
mode: 'gallery',
slideBy: 'page',
center: true,
autoplay: false,
controls: false,
swipeAngle: false,
startIndex: this.currentPage,
loop: false,
nav: false
});
this.context.handleEvent('page', data => {
//set current page
this.currentPage = parseInt(data.current_page)
this.slider.goTo(data.current_page)
})
this.context.handleEvent('chat-visible', data => {
if (data.value) {
document.getElementById("post-list").classList.remove("animate__animated", "animate__fadeOutLeft")
document.getElementById("post-list").classList.add("animate__animated", "animate__fadeInLeft")
} else {
document.getElementById("post-list").classList.remove("animate__animated", "animate__fadeInLeft")
document.getElementById("post-list").classList.add("animate__animated", "animate__fadeOutLeft")
}
})
this.context.handleEvent('poll-visible', data => {
if (data.value) {
document.getElementById("poll").classList.remove("animate__animated", "animate__fadeOut")
document.getElementById("poll").classList.add("animate__animated", "animate__fadeIn")
} else {
document.getElementById("poll").classList.remove("animate__animated", "animate__fadeIn")
document.getElementById("poll").classList.add("animate__animated", "animate__fadeOut")
}
})
this.context.handleEvent('join-screen-visible', data => {
if (data.value) {
document.getElementById("joinScreen").classList.remove("animate__animated", "animate__fadeOut")
document.getElementById("joinScreen").classList.add("animate__animated", "animate__fadeIn")
} else {
document.getElementById("joinScreen").classList.remove("animate__animated", "animate__fadeIn")
document.getElementById("joinScreen").classList.add("animate__animated", "animate__fadeOut")
}
})
window.addEventListener('keyup', (e) => {
if (e.target.tagName.toLowerCase() != "input") {
e.preventDefault()
switch (e.key) {
case 'f': // F
this.fullscreen()
break
}
}
});
}
fullscreen() {
var docEl = document.getElementById("presenter")
try {
docEl.webkitRequestFullscreen()
.then(function() {
})
.catch(function(error) {
});
} catch (e) {
docEl.requestFullscreen()
.then(function() {
})
.catch(function(error) {
});
docEl.mozRequestFullScreen()
.then(function() {
})
.catch(function(error) {
});
}
}
}

25
assets/package.json Normal file
View File

@@ -0,0 +1,25 @@
{
"scripts": {
"deploy": "NODE_ENV=production tailwindcss --postcss --minify --input=css/app.css --output=../priv/static/assets/app.css"
},
"devDependencies": {
"alpinejs": "^3.4.2",
"autoprefixer": "^10.3.7",
"cpx": "^1.5.0",
"esbuild": "^0.14.14",
"flatpickr": "^4.6.9",
"postcss": "^8.3.9",
"postcss-import": "^14.0.2",
"tailwindcss": "^2.2.16"
},
"dependencies": {
"animate.css": "^4.1.1",
"moment": "^2.29.1",
"moment-timezone": "^0.5.34",
"phoenix": "file:../deps/phoenix",
"phoenix_html": "file:../deps/phoenix_html",
"phoenix_live_view": "file:../deps/phoenix_live_view",
"qr-code-styling": "^1.6.0-rc.1",
"tiny-slider": "^2.9.4"
}
}

7
assets/postcss.config.js Normal file
View File

@@ -0,0 +1,7 @@
module.exports = {
plugins: {
"postcss-import": {},
tailwindcss: {},
autoprefixer: {},
}
}

135
assets/tailwind.config.js Normal file
View File

@@ -0,0 +1,135 @@
const { colors: defaultColors } = require('tailwindcss/defaultTheme')
const colors = {
...defaultColors,
...{
"water-blue": {
"50": "#E3F2FD",
"100": "#C2E3FA",
"200": "#84C8F6",
"300": "#3DA7F0",
"400": "#1395EC",
"500": "#1186D5",
"600": "#0D65A1",
"700": "#0A5689",
"800": "#0A4B76",
"900": "#073250",
},
"electric-purple": {
"50": "#F2E0FF",
"100": "#E3BDFF",
"200": "#C77AFF",
"300": "#A62EFF",
"400": "#9200FF",
"500": "#A327FF",
"600": "#6400AD",
"700": "#550094",
"800": "#490080",
"900": "#320057",
},
"wedgewood": {
"50": "#F0F4F8",
"100": "#D9E3ED",
"200": "#B9CCDF",
"300": "#97B3CE",
"400": "#7499BE",
"500": "#507DAA",
"600": "#3F6388",
"700": "#314D68",
"800": "#253B50",
"900": "#1A2938",
},
"rose-madder": {
"50": "#FCEDEE",
"100": "#F9D5D7",
"200": "#F3ABB0",
"300": "#ED8188",
"400": "#E75761",
"500": "#E12D39",
"600": "#B4242E",
"700": "#871B22",
"800": "#5A1217",
"900": "#2D090B",
},
"school-bus-yellow": {
"50": "#FFFBEB",
"100": "#FEF3C7",
"200": "#FDE68A",
"300": "#FCD34D",
"400": "#FBBF24",
"500": "#F59E0B",
"600": "#D97706",
"700": "#B45309",
"800": "#92400E",
"900": "#78350F",
},
"green-teal": {
"50": "#ECFDF5",
"100": "#D1FAE5",
"200": "#A7F3D0",
"300": "#6EE7B7",
"400": "#34D399",
"500": "#10B981",
"600": "#059669",
"700": "#047857",
"800": "#065F46",
"900": "#064E3B",
},
},
}
module.exports = {
mode: 'jit',
purge: {
content: [
'./js/**/*.js',
'../lib/*_web/**/*.*ex'
],
safelist: [
'-top-1.5',
'top-1',
'left-3',
'top-6',
'h-5',
'left-2.5',
'top-3',
'h-7'
]
},
darkMode: false, // or 'media' or 'class'
theme: {
extend: {
backgroundSize: {
'size-200': '200% 200%',
},
backgroundPosition: {
'pos-0': '0% 0%',
'pos-100': '100% 100%',
},
colors: {
primary: colors["water-blue"],
secondary: colors["electric-purple"],
neutral: colors["wedgewood"],
"supporting-red": colors["rose-madder"],
"supporting-yellow": colors["school-bus-yellow"],
"supporting-green": colors["green-teal"]
}
},
fontFamily: {
sans: ['Roboto', 'sans-serif'],
serif: ['Merriweather', 'serif'],
},
boxShadow: {
"base": "0px 1px 3px 0px rgba(0,0,0,0.1), 0px 1px 2px 0px rgba(0,0,0,0.06)",
"lg": "0px 4px 6px 0px rgba(0,0,0,0.05), 0px 10px 15px 0px rgba(0,0,0,0.1)",
"md": "0px 4px 6px 0px rgba(0,0,0,0.1), 0px 2px 4px 0px rgba(0,0,0,0.06)",
"xl": "0px 10px 10px 0px rgba(0,0,0,0.04), 0px 20px 25px 0px rgba(0,0,0,0.1)",
"2xl": "0px 25px 50px 0px rgba(0,0,0,0.25)",
"inner": "inset 0px 2px 4px 0px rgba(0,0,0,0.06)"
}
},
variants: {
extend: {},
},
plugins: [],
}

157
assets/vendor/topbar.js vendored Normal file
View File

@@ -0,0 +1,157 @@
/**
* @license MIT
* topbar 1.0.0, 2021-01-06
* http://buunguyen.github.io/topbar
* Copyright (c) 2021 Buu Nguyen
*/
(function (window, document) {
"use strict";
// https://gist.github.com/paulirish/1579671
(function () {
var lastTime = 0;
var vendors = ["ms", "moz", "webkit", "o"];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame =
window[vendors[x] + "RequestAnimationFrame"];
window.cancelAnimationFrame =
window[vendors[x] + "CancelAnimationFrame"] ||
window[vendors[x] + "CancelRequestAnimationFrame"];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function () {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
})();
var canvas,
progressTimerId,
fadeTimerId,
currentProgress,
showing,
addEvent = function (elem, type, handler) {
if (elem.addEventListener) elem.addEventListener(type, handler, false);
else if (elem.attachEvent) elem.attachEvent("on" + type, handler);
else elem["on" + type] = handler;
},
options = {
autoRun: true,
barThickness: 3,
barColors: {
0: "rgba(26, 188, 156, .9)",
".25": "rgba(52, 152, 219, .9)",
".50": "rgba(241, 196, 15, .9)",
".75": "rgba(230, 126, 34, .9)",
"1.0": "rgba(211, 84, 0, .9)",
},
shadowBlur: 10,
shadowColor: "rgba(0, 0, 0, .6)",
className: null,
},
repaint = function () {
canvas.width = window.innerWidth;
canvas.height = options.barThickness * 5; // need space for shadow
var ctx = canvas.getContext("2d");
ctx.shadowBlur = options.shadowBlur;
ctx.shadowColor = options.shadowColor;
var lineGradient = ctx.createLinearGradient(0, 0, canvas.width, 0);
for (var stop in options.barColors)
lineGradient.addColorStop(stop, options.barColors[stop]);
ctx.lineWidth = options.barThickness;
ctx.beginPath();
ctx.moveTo(0, options.barThickness / 2);
ctx.lineTo(
Math.ceil(currentProgress * canvas.width),
options.barThickness / 2
);
ctx.strokeStyle = lineGradient;
ctx.stroke();
},
createCanvas = function () {
canvas = document.createElement("canvas");
var style = canvas.style;
style.position = "fixed";
style.top = style.left = style.right = style.margin = style.padding = 0;
style.zIndex = 100001;
style.display = "none";
if (options.className) canvas.classList.add(options.className);
document.body.appendChild(canvas);
addEvent(window, "resize", repaint);
},
topbar = {
config: function (opts) {
for (var key in opts)
if (options.hasOwnProperty(key)) options[key] = opts[key];
},
show: function () {
if (showing) return;
showing = true;
if (fadeTimerId !== null) window.cancelAnimationFrame(fadeTimerId);
if (!canvas) createCanvas();
canvas.style.opacity = 1;
canvas.style.display = "block";
topbar.progress(0);
if (options.autoRun) {
(function loop() {
progressTimerId = window.requestAnimationFrame(loop);
topbar.progress(
"+" + 0.05 * Math.pow(1 - Math.sqrt(currentProgress), 2)
);
})();
}
},
progress: function (to) {
if (typeof to === "undefined") return currentProgress;
if (typeof to === "string") {
to =
(to.indexOf("+") >= 0 || to.indexOf("-") >= 0
? currentProgress
: 0) + parseFloat(to);
}
currentProgress = to > 1 ? 1 : to;
repaint();
return currentProgress;
},
hide: function () {
if (!showing) return;
showing = false;
if (progressTimerId != null) {
window.cancelAnimationFrame(progressTimerId);
progressTimerId = null;
}
(function loop() {
if (topbar.progress("+.1") >= 1) {
canvas.style.opacity -= 0.05;
if (canvas.style.opacity <= 0.05) {
canvas.style.display = "none";
fadeTimerId = null;
return;
}
}
fadeTimerId = window.requestAnimationFrame(loop);
})();
},
};
if (typeof module === "object" && typeof module.exports === "object") {
module.exports = topbar;
} else if (typeof define === "function" && define.amd) {
define(function () {
return topbar;
});
} else {
this.topbar = topbar;
}
}.call(this, window, document));

2123
assets/yarn.lock Normal file

File diff suppressed because it is too large Load Diff

16
build.sh Normal file
View File

@@ -0,0 +1,16 @@
#!/usr/bin/env bash
# exit on error
set -o errexit
# Initial setup
mix deps.get --only prod
MIX_ENV=prod mix compile
# Compile assets
mix assets.deploy
# Build the release and overwrite the existing release directory
MIX_ENV=prod mix release --overwrite
# for auto DB migration upon deploy
MIX_ENV=prod mix ecto.migrate

71
config/config.exs Normal file
View File

@@ -0,0 +1,71 @@
# This file is responsible for configuring your application
# and its dependencies with the aid of the Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
# General application configuration
import Config
config :claper,
ecto_repos: [Claper.Repo]
# Configures the endpoint
config :claper, ClaperWeb.Endpoint,
url: [host: "localhost"],
render_errors: [view: ClaperWeb.ErrorView, accepts: ~w(html json), layout: false],
pubsub_server: Claper.PubSub,
live_view: [signing_salt: "DN0vwriJgVkHG0kn3hF5JKho/DE66onv"]
config :claper, ClaperWeb.Gettext,
default_locale: "en",
locales: ~w(fr en)
# Configures the mailer
#
# By default it uses the "Local" adapter which stores the emails
# locally. You can see the emails in your browser, at "/dev/mailbox".
#
# For production it's recommended to configure a different adapter
# at the `config/runtime.exs`.
config :claper, Claper.Mailer, adapter: Swoosh.Adapters.Local
# Swoosh API client is needed for adapters other than SMTP.
config :swoosh, :api_client, false
config :dart_sass,
version: "1.49.7",
default: [
args: ~w(css/custom.scss ../priv/static/assets/custom.css),
cd: Path.expand("../assets", __DIR__)
]
# Configure esbuild (the version is required)
config :esbuild,
version: "0.12.18",
default: [
args:
~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*),
cd: Path.expand("../assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
config :porcelain, driver: Porcelain.Driver.Basic
config :ex_aws,
access_key_id: [{:system, "AWS_ACCESS_KEY_ID"}, :instance_role],
secret_access_key: [{:system, "AWS_SECRET_ACCESS_KEY"}, :instance_role],
region: {:system, "AWS_REGION"},
normalize_path: false
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{config_env()}.exs"

87
config/dev.exs Normal file
View File

@@ -0,0 +1,87 @@
import Config
# Configure your database
config :claper, Claper.Repo,
username: "claper",
password: "claper",
database: "postgres",
hostname: "localhost",
show_sensitive_data_on_connection_error: true,
pool_size: 10
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with esbuild to bundle .js and .css sources.
config :claper, ClaperWeb.Endpoint,
# Binding to loopback ipv4 address prevents access from other machines.
# Change to `ip: {0, 0, 0, 0}` to allow access from other machines.
http: [ip: {0, 0, 0, 0}, port: 4000],
check_origin: false,
code_reloader: true,
debug_errors: true,
secret_key_base: "sm/ICUyPRRbxOU0s0NN/KFY8ze7XRALuvFLoyidy8l1ZBeWl8p/zFhfdI5II+Jdk",
watchers: [
# Start the esbuild watcher by calling Esbuild.install_and_run(:default, args)
esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]},
sass: {
DartSass,
:install_and_run,
[:default, ~w(--embed-source-map --source-map-urls=absolute --watch)]
},
npx: [
"tailwindcss",
"--input=css/app.css",
"--output=../priv/static/assets/app.css",
"--postcss",
"--watch",
cd: Path.expand("../assets", __DIR__)
]
]
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# Mix task:
#
# mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.pem"
# ],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Watch static and templates for browser reloading.
config :claper, ClaperWeb.Endpoint,
live_reload: [
patterns: [
~r"priv/static/[^uploads].*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/claper_web/(live|views)/.*(ex)$",
~r"lib/claper_web/templates/.*(eex)$"
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime

65
config/prod.exs Normal file
View File

@@ -0,0 +1,65 @@
import Config
# For production, don't forget to configure the url host
# to something meaningful, Phoenix uses this information
# when generating URLs.
#
# Note we also include the path to a cache manifest
# containing the digested version of static files. This
# manifest is generated by the `mix phx.digest` task,
# which you should run after static files are built and
# before starting your production server.
config :claper, ClaperWeb.Endpoint,
cache_static_manifest: "priv/static/cache_manifest.json",
server: true
# Do not print debug messages in production
config :logger, level: :info
config :libcluster,
topologies: [
default: [
strategy: Cluster.Strategy.Kubernetes,
config: [
mode: :dns,
kubernetes_node_basename: "claper",
kubernetes_selector: "app=claper",
kubernetes_namespace: "default",
polling_interval: 10_000
]
]
]
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :claper, ClaperWeb.Endpoint,
# ...,
# url: [host: "example.com", port: 443],
# https: [
# ...,
# port: 443,
# cipher_suite: :strong,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")
# ]
#
# The `cipher_suite` is set to `:strong` to support only the
# latest and more secure SSL ciphers. This means old browsers
# and clients may not be supported. You can set it to
# `:compatible` for wider support.
#
# `:keyfile` and `:certfile` expect an absolute path to the key
# and cert in disk or a relative path inside priv, for example
# "priv/ssl/server.key". For all supported SSL configuration
# options, see https://hexdocs.pm/plug/Plug.SSL.html#configure/1
#
# We also recommend setting `force_ssl` in your endpoint, ensuring
# no data is ever sent via http, always redirecting to https:
#
# config :claper, ClaperWeb.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.

86
config/runtime.exs Normal file
View File

@@ -0,0 +1,86 @@
import Config
# config/runtime.exs is executed for all environments, including
# during releases. It is executed after compilation and before the
# system starts, so it is typically used to load production configuration
# and secrets from environment variables or elsewhere. Do not define
# any compile-time configuration in here, as it won't be applied.
# The block below contains prod specific runtime configuration.
if config_env() == :prod do
database_url =
System.get_env("DATABASE_URL") ||
raise """
environment variable DATABASE_URL is missing.
For example: ecto://USER:PASS@HOST/DATABASE
"""
config :claper, Claper.Repo,
url: database_url,
ssl: System.get_env("DB_SSL") == "true" || false,
ssl_opts: [
verify: :verify_none
],
prepare: :unnamed,
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
queue_target: String.to_integer(System.get_env("QUEUE_TARGET") || "5000")
# The secret key base is used to sign/encrypt cookies and other secrets.
# A default value is used in config/dev.exs and config/test.exs but you
# want to use a different value for prod and you most likely don't want
# to check this value into version control, so we use an environment
# variable instead.
secret_key_base =
System.get_env("SECRET_KEY_BASE") ||
raise """
environment variable SECRET_KEY_BASE is missing.
You can generate one by calling: mix phx.gen.secret
"""
config :claper, ClaperWeb.Endpoint,
url: [
host: System.get_env("ENDPOINT_HOST"),
port: 80
],
http: [
# Enable IPv6 and bind on all interfaces.
# Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
# See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html
# for details about using IPv6 vs IPv4 and loopback vs public addresses.
ip: {0, 0, 0, 0, 0, 0, 0, 0},
port: String.to_integer(System.get_env("PORT") || "4000")
],
secret_key_base: secret_key_base
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start each relevant endpoint:
#
# config :claper, ClaperWeb.Endpoint, server: true
#
# Then you can assemble a release by calling `mix release`.
# See `mix help release` for more information.
# ## Configuring the mailer
#
# In production you need to configure the mailer to use a different adapter.
# Also, you may need to configure the Swoosh API client of your choice if you
# are not using SMTP. Here is an example of the configuration:
#
# config :claper, Claper.Mailer,
# adapter: Swoosh.Adapters.Mailgun,
# api_key: System.get_env("MAILGUN_API_KEY"),
# domain: System.get_env("MAILGUN_DOMAIN")
#
# For this example you need include a HTTP client required by Swoosh API client.
# Swoosh supports Hackney and Finch out of the box:
#
#config :claper, Claper.Mailer,
# adapter: Swoosh.Adapters.Postmark,
# api_key: System.get_env("SWOOSH_API_KEY")
config :swoosh, :api_client, Swoosh.ApiClient.Finch
#
# See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details.
end

30
config/test.exs Normal file
View File

@@ -0,0 +1,30 @@
import Config
# Configure your database
#
# The MIX_TEST_PARTITION environment variable can be used
# to provide built-in test partitioning in CI environment.
# Run `mix help test` for more information.
config :claper, Claper.Repo,
username: "claper",
password: "claper",
database: "claper_test#{System.get_env("MIX_TEST_PARTITION")}",
hostname: "localhost",
pool: Ecto.Adapters.SQL.Sandbox,
pool_size: 10
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :claper, ClaperWeb.Endpoint,
http: [ip: {127, 0, 0, 1}, port: 4002],
secret_key_base: "YnJKcv692Yso3lHGqaJ6kJxKBDh0BUL+mJhguLm5rzoJ+xCEuN7MdrguMSnHKoz4",
server: false
# In test we don't send emails.
config :claper, Claper.Mailer, adapter: Swoosh.Adapters.Test
# Print only warnings and errors during test
config :logger, level: :warn
# Initialize plugs at runtime for faster test compilation
config :phoenix, :plug_init_mode, :runtime

2
elixir_buildpack.config Normal file
View File

@@ -0,0 +1,2 @@
elixir_version=1.13.2
erlang_version=24.0

9
lib/claper.ex Normal file
View File

@@ -0,0 +1,9 @@
defmodule Claper do
@moduledoc """
Claper keeps the contexts that define your domain
and business logic.
Contexts are also responsible for managing your data, regardless
if it comes from the database, an external API or others.
"""
end

267
lib/claper/accounts.ex Normal file
View File

@@ -0,0 +1,267 @@
defmodule Claper.Accounts do
@moduledoc """
The Accounts context.
"""
import Ecto.Query, warn: false
alias Claper.Repo
alias Claper.Accounts.{User, UserToken, UserNotifier}
## Database getters
@doc """
Gets a user by email.
## Examples
iex> get_user_by_email("foo@example.com")
%User{}
iex> get_user_by_email("unknown@example.com")
nil
"""
def get_user_by_email(email) when is_binary(email) do
Repo.get_by(User, email: email)
end
@doc """
Gets a single user.
Raises `Ecto.NoResultsError` if the User does not exist.
## Examples
iex> get_user!(123)
%User{}
iex> get_user!(456)
** (Ecto.NoResultsError)
"""
def get_user!(id), do: Repo.get!(User, id)
## User registration
@doc """
Registers a user.
## Examples
iex> register_user(%{field: value})
{:ok, %User{}}
iex> register_user(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def register_user(attrs) do
%User{}
|> User.registration_changeset(attrs)
|> Repo.insert(returning: [:uuid])
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking user changes.
## Examples
iex> change_user_registration(user)
%Ecto.Changeset{data: %User{}}
"""
def change_user_registration(%User{} = user, attrs \\ %{}) do
User.registration_changeset(user, attrs, hash_password: false)
end
## Settings
@doc """
Returns an `%Ecto.Changeset{}` for changing the user email.
## Examples
iex> change_user_email(user)
%Ecto.Changeset{data: %User{}}
"""
def change_user_email(user, attrs \\ %{}) do
User.email_changeset(user, attrs)
end
@doc """
Emulates that the email will change without actually changing
it in the database.
## Examples
iex> apply_user_email(user, "valid password", %{email: ...})
{:ok, %User{}}
iex> apply_user_email(user, "invalid password", %{email: ...})
{:error, %Ecto.Changeset{}}
"""
def apply_user_email(user, attrs) do
user
|> User.email_changeset(attrs)
|> Ecto.Changeset.apply_action(:update)
end
@doc """
Updates the user email using the given token.
If the token matches, the user email is updated and the token is deleted.
The confirmed_at date is also updated to the current time.
"""
def update_user_email(user, token) do
context = "change:#{user.email}"
with {:ok, query} <- UserToken.verify_change_email_token_query(token, context),
%UserToken{sent_to: email} <- Repo.one(query),
{:ok, _} <- Repo.transaction(user_email_multi(user, email, context)) do
:ok
else
_ -> :error
end
end
defp user_email_multi(user, email, context) do
changeset = user |> User.email_changeset(%{email: email}) |> User.confirm_changeset()
Ecto.Multi.new()
|> Ecto.Multi.update(:user, changeset)
|> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, [context]))
end
@doc """
Delivers the update email instructions to the given user.
## Examples
iex> deliver_update_email_instructions(user, current_email, &Routes.user_update_email_url(conn, :edit, &1))
{:ok, %{to: ..., body: ...}}
"""
def deliver_magic_link(email, magic_link_url_fun)
when is_function(magic_link_url_fun, 1) do
{encoded_token, user_token} = UserToken.build_magic_token(email, "magic")
Repo.insert!(user_token)
UserNotifier.deliver_magic_link(email, magic_link_url_fun.(encoded_token))
end
def deliver_update_email_instructions(%User{} = user, current_email, update_email_url_fun)
when is_function(update_email_url_fun, 1) do
{encoded_token, user_token} = UserToken.build_email_token(user, "change:#{current_email}")
Repo.insert!(user_token)
UserNotifier.deliver_update_email_instructions(user, update_email_url_fun.(encoded_token))
end
## Session
@doc """
Generates a session token.
"""
def generate_user_session_token(user) do
{token, user_token} = UserToken.build_session_token(user)
Repo.insert!(user_token)
token
end
@doc """
Gets the user with the given signed token.
"""
def get_user_by_session_token(token) do
{:ok, query} = UserToken.verify_session_token_query(token)
Repo.one(query)
end
def magic_token_valid?(email) do
query = UserToken.user_magic_and_contexts_expiry_query(email)
Repo.exists?(query)
end
@doc """
Deletes the signed token with the given context.
"""
def delete_session_token(token) do
Repo.delete_all(UserToken.token_and_context_query(token, "session"))
:ok
end
## Confirmation
@doc """
Delivers the confirmation email instructions to the given user.
## Examples
iex> deliver_user_confirmation_instructions(user, &Routes.user_confirmation_url(conn, :edit, &1))
{:ok, %{to: ..., body: ...}}
iex> deliver_user_confirmation_instructions(confirmed_user, &Routes.user_confirmation_url(conn, :edit, &1))
{:error, :already_confirmed}
"""
def deliver_user_confirmation_instructions(%User{} = user, confirmation_url_fun)
when is_function(confirmation_url_fun, 1) do
if user.confirmed_at do
{:error, :already_confirmed}
else
{encoded_token, user_token} = UserToken.build_email_token(user, "confirm")
Repo.insert!(user_token)
UserNotifier.deliver_confirmation_instructions(user, confirmation_url_fun.(encoded_token))
end
end
@doc """
Confirms a user by the given token.
If the token matches, the user account is marked as confirmed
and the token is deleted.
"""
def confirm_user(token) do
with {:ok, query} <- UserToken.verify_email_token_query(token, "confirm"),
%User{} = user <- Repo.one(query),
{:ok, %{user: user}} <- Repo.transaction(confirm_user_multi(user)) do
{:ok, user}
else
_ -> :error
end
end
defp confirm_user_multi(user) do
Ecto.Multi.new()
|> Ecto.Multi.update(:user, User.confirm_changeset(user))
|> Ecto.Multi.delete_all(:tokens, UserToken.user_and_contexts_query(user, ["confirm"]))
end
def confirm_magic(token) do
with {:ok, query} <- UserToken.verify_magic_token_query(token, "magic"),
%UserToken{} = token <- Repo.one(query),
{:ok, %{user: user}} <- Repo.transaction(confirm_magic_multi(token)) do
{:ok, user}
else
_ -> :error
end
end
defp confirm_magic_multi(%UserToken{} = token) do
Ecto.Multi.new()
|> Ecto.Multi.run(:run, fn repo, _changes ->
user = repo.get_by(User, email: token.sent_to)
if (is_nil(user)) do
UserNotifier.deliver_welcome(token.sent_to)
end
{:ok, user || %User{email: token.sent_to}}
end)
|> Ecto.Multi.insert_or_update(:user, fn %{run: user} -> User.confirm_changeset(user) end)
|> Ecto.Multi.delete_all(
:tokens,
UserToken.user_magic_and_contexts_query(token.sent_to, ["magic"])
)
end
end

View File

@@ -0,0 +1,55 @@
defmodule Claper.Accounts.User do
use Ecto.Schema
import Ecto.Changeset
schema "users" do
field :uuid, :binary_id
field :email, :string
field :is_admin, :boolean
field :confirmed_at, :naive_datetime
has_many :events, Claper.Events.Event
timestamps()
end
def registration_changeset(user, attrs, _opts \\ []) do
user
|> cast(attrs, [:email])
|> validate_email()
end
defp validate_email(changeset) do
changeset
|> validate_required([:email])
|> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces")
|> validate_length(:email, max: 160)
|> unsafe_validate_unique(:email, Claper.Repo)
|> unique_constraint(:email)
end
@doc """
A user changeset for changing the email.
It requires the email to change otherwise an error is added.
"""
def email_changeset(user, attrs) do
user
|> cast(attrs, [:email])
|> validate_email()
|> case do
%{changes: %{email: _}} = changeset -> changeset
%{} = changeset -> add_error(changeset, :email, "did not change")
end
end
@doc """
Confirms the account by setting `confirmed_at`.
"""
def confirm_changeset(user) do
now = NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
change(user, confirmed_at: now)
end
end

View File

@@ -0,0 +1,83 @@
defmodule Claper.Accounts.UserNotifier do
import Swoosh.Email
alias Claper.Mailer
# Delivers the email using the application mailer.
defp deliver(recipient, subject, body) do
email =
new()
|> to(recipient)
|> from({"MyApp", "contact@example.com"})
|> subject(subject)
|> text_body(body)
with {:ok, _metadata} <- Mailer.deliver(email) do
{:ok, email}
end
end
def deliver_magic_link(email, url) do
email = ClaperWeb.Notifiers.UserNotifier.magic(email, url)
with {:ok, _metadata} <- Mailer.deliver(email) do
{:ok, email}
end
end
def deliver_welcome(email) do
email = ClaperWeb.Notifiers.UserNotifier.welcome(email)
with {:ok, _metadata} <- Mailer.deliver(email) do
{:ok, email}
end
end
@doc """
Deliver instructions to confirm account.
"""
def deliver_confirmation_instructions(user, url) do
deliver(user.email, "Confirmation instructions", """
==============================
Hi #{user.email},
You can confirm your account by visiting the URL below:
#{url}
If you didn't create an account with us, please ignore this.
==============================
""")
end
@doc """
Deliver instructions to reset a user password.
"""
def deliver_reset_password_instructions(user, url) do
deliver(user.email, "Reset password instructions", """
==============================
Hi #{user.email},
You can reset your password by visiting the URL below:
#{url}
If you didn't request this change, please ignore this.
==============================
""")
end
@doc """
Deliver instructions to update a user email.
"""
def deliver_update_email_instructions(user, url) do
email = ClaperWeb.Notifiers.UserNotifier.update_email(user, url)
with {:ok, _metadata} <- Mailer.deliver(email) do
{:ok, email}
end
end
end

View File

@@ -0,0 +1,220 @@
defmodule Claper.Accounts.UserToken do
use Ecto.Schema
import Ecto.Query
@hash_algorithm :sha256
@rand_size 32
# It is very important to keep the reset password token expiry short,
# since someone with access to the email may take over the account.
@confirm_validity_in_days 7
@change_email_validity_in_days 7
@session_validity_in_days 60
@confirm_magic_in_minutes 5
schema "users_tokens" do
field :uuid, :binary_id
field :token, :binary
field :context, :string
field :sent_to, :string
belongs_to :user, Claper.Accounts.User
timestamps(updated_at: false)
end
@doc """
Generates a token that will be stored in a signed place,
such as session or cookie. As they are signed, those
tokens do not need to be hashed.
The reason why we store session tokens in the database, even
though Phoenix already provides a session cookie, is because
Phoenix' default session cookies are not persisted, they are
simply signed and potentially encrypted. This means they are
valid indefinitely, unless you change the signing/encryption
salt.
Therefore, storing them allows individual user
sessions to be expired. The token system can also be extended
to store additional data, such as the device used for logging in.
You could then use this information to display all valid sessions
and devices in the UI and allow users to explicitly expire any
session they deem invalid.
"""
def build_session_token(user) do
token = :crypto.strong_rand_bytes(@rand_size)
{token, %Claper.Accounts.UserToken{token: token, context: "session", user_id: user.id}}
end
def build_magic_token(email, context) do
token = :crypto.strong_rand_bytes(@rand_size)
hashed_token = :crypto.hash(@hash_algorithm, token)
{Base.url_encode64(token, padding: false),
%Claper.Accounts.UserToken{
token: hashed_token,
context: context,
sent_to: email
}}
end
@doc """
Checks if the token is valid and returns its underlying lookup query.
The query returns the user found by the token, if any.
The token is valid if it matches the value in the database and it has
not expired (after @session_validity_in_days).
"""
def verify_session_token_query(token) do
query =
from token in token_and_context_query(token, "session"),
join: user in assoc(token, :user),
where: token.inserted_at > ago(@session_validity_in_days, "day"),
select: user
{:ok, query}
end
@doc """
Builds a token and its hash to be delivered to the user's email.
The non-hashed token is sent to the user email while the
hashed part is stored in the database. The original token cannot be reconstructed,
which means anyone with read-only access to the database cannot directly use
the token in the application to gain access. Furthermore, if the user changes
their email in the system, the tokens sent to the previous email are no longer
valid.
Users can easily adapt the existing code to provide other types of delivery methods,
for example, by phone numbers.
"""
def build_email_token(user, context) do
build_hashed_token(user, context, user.email)
end
defp build_hashed_token(user, context, sent_to) do
token = :crypto.strong_rand_bytes(@rand_size)
hashed_token = :crypto.hash(@hash_algorithm, token)
{Base.url_encode64(token, padding: false),
%Claper.Accounts.UserToken{
token: hashed_token,
context: context,
sent_to: sent_to,
user_id: user.id
}}
end
@doc """
Checks if the token is valid and returns its underlying lookup query.
The query returns the user found by the token, if any.
The given token is valid if it matches its hashed counterpart in the
database and the user email has not changed. This function also checks
if the token is being used within a certain period, depending on the
context. The default contexts supported by this function are either
"confirm", for account confirmation emails, and "reset_password",
for resetting the password. For verifying requests to change the email,
see `verify_change_email_token_query/2`.
"""
def verify_email_token_query(token, context) do
case Base.url_decode64(token, padding: false) do
{:ok, decoded_token} ->
hashed_token = :crypto.hash(@hash_algorithm, decoded_token)
days = days_for_context(context)
query =
from token in token_and_context_query(hashed_token, context),
join: user in assoc(token, :user),
where: token.inserted_at > ago(^days, "day") and token.sent_to == user.email,
select: user
{:ok, query}
:error ->
:error
end
end
def verify_magic_token_query(token, context) do
case Base.url_decode64(token, padding: false) do
{:ok, decoded_token} ->
hashed_token = :crypto.hash(@hash_algorithm, decoded_token)
minutes = minutes_for_context(context)
query =
from token in token_and_context_query(hashed_token, context),
where: token.inserted_at > ago(^minutes, "minute"),
select: token
{:ok, query}
:error ->
:error
end
end
defp minutes_for_context("magic"), do: @confirm_magic_in_minutes
defp days_for_context("confirm"), do: @confirm_validity_in_days
@doc """
Checks if the token is valid and returns its underlying lookup query.
The query returns the user found by the token, if any.
This is used to validate requests to change the user
email. It is different from `verify_email_token_query/2` precisely because
`verify_email_token_query/2` validates the email has not changed, which is
the starting point by this function.
The given token is valid if it matches its hashed counterpart in the
database and if it has not expired (after @change_email_validity_in_days).
The context must always start with "change:".
"""
def verify_change_email_token_query(token, "change:" <> _ = context) do
case Base.url_decode64(token, padding: false) do
{:ok, decoded_token} ->
hashed_token = :crypto.hash(@hash_algorithm, decoded_token)
query =
from token in token_and_context_query(hashed_token, context),
where: token.inserted_at > ago(@change_email_validity_in_days, "day")
{:ok, query}
:error ->
:error
end
end
@doc """
Returns the token struct for the given token value and context.
"""
def token_and_context_query(token, context) do
from Claper.Accounts.UserToken, where: [token: ^token, context: ^context]
end
@doc """
Gets all tokens for the given user for the given contexts.
"""
def user_and_contexts_query(user, :all) do
from t in Claper.Accounts.UserToken, where: t.user_id == ^user.id
end
def user_and_contexts_query(user, [_ | _] = contexts) do
from t in Claper.Accounts.UserToken, where: t.user_id == ^user.id and t.context in ^contexts
end
def user_magic_and_contexts_query(email, [_ | _] = contexts) do
from t in Claper.Accounts.UserToken, where: t.sent_to == ^email and t.context in ^contexts
end
def user_magic_and_contexts_expiry_query(email) do
from t in Claper.Accounts.UserToken,
where:
t.sent_to == ^email and t.context == "magic" and
t.inserted_at > ago(@confirm_magic_in_minutes, "minute")
end
end

43
lib/claper/application.ex Normal file
View File

@@ -0,0 +1,43 @@
defmodule Claper.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
@impl true
def start(_type, _args) do
topologies = Application.get_env(:libcluster, :topologies) || []
children = [
{Cluster.Supervisor, [topologies, [name: Claper.ClusterSupervisor]]},
# Start the Ecto repository
Claper.Repo,
# Start the Telemetry supervisor
ClaperWeb.Telemetry,
# Start the PubSub system
{Phoenix.PubSub, name: Claper.PubSub},
# Start the Endpoint (http/https)
ClaperWeb.Presence,
ClaperWeb.Endpoint,
# Start a worker by calling: Claper.Worker.start_link(arg)
# {Claper.Worker, arg}
{Finch, name: Swoosh.Finch},
{Task.Supervisor, name: Claper.TaskSupervisor}
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Claper.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
@impl true
def config_change(changed, _new, removed) do
ClaperWeb.Endpoint.config_change(changed, removed)
:ok
end
end

267
lib/claper/events.ex Normal file
View File

@@ -0,0 +1,267 @@
defmodule Claper.Events do
@moduledoc """
The Events context.
"""
import Ecto.Query, warn: false
alias Claper.Repo
alias Claper.Events.{Event, ActivityLeader}
@doc """
Returns the list of events.
## Examples
iex> list_events()
[%Event{}, ...]
"""
def list_events(user_id, preload \\ []) do
from(e in Event, where: e.user_id == ^user_id, order_by: [desc: e.expired_at])
|> Repo.all()
|> Repo.preload(preload)
end
def list_managed_events_by(email, preload \\ []) do
from(a in ActivityLeader,
join: u in Claper.Accounts.User,
on: u.email == a.email,
join: e in Event,
on: e.id == a.event_id,
where: a.email == ^email,
order_by: [desc: e.expired_at],
select: e
)
|> Repo.all()
|> Repo.preload(preload)
end
def count_events_month(user_id) do
# minus 30 days, calculated as seconds
seconds = -30 * 24 * 3600
last_month = DateTime.utc_now() |> DateTime.add(seconds, :second)
from(e in Event,
where:
e.user_id == ^user_id and e.inserted_at <= ^DateTime.utc_now() and
e.inserted_at >= ^last_month,
order_by: [desc: e.id]
)
|> Repo.aggregate(:count, :id)
end
@doc """
Gets a single event.
Raises `Ecto.NoResultsError` if the Event does not exist.
## Examples
iex> get_event!(123)
%Event{}
iex> get_event!(456)
** (Ecto.NoResultsError)
"""
def get_event!(id, preload \\ []),
do: Repo.get_by!(Event, uuid: id) |> Repo.preload(preload)
def get_managed_event!(current_user, id, preload \\ []) do
event = Repo.get_by!(Event, uuid: id)
is_leader = Claper.Events.is_leaded_by(current_user.email, event) || event.user_id == current_user.id
if is_leader do
event |> Repo.preload(preload)
else
raise Ecto.NoResultsError
end
end
def get_user_event!(user_id, id, preload \\ []),
do: Repo.get_by!(Event, uuid: id, user_id: user_id) |> Repo.preload(preload)
def get_event_with_code!(code, preload \\ []) do
now = NaiveDateTime.utc_now()
from(e in Event, where: e.code == ^code and e.expired_at > ^now)
|> Repo.one!()
|> Repo.preload(preload)
end
def get_event_with_code(code, preload \\ []) do
now = DateTime.utc_now()
from(e in Event, where: e.code == ^code and e.expired_at > ^now)
|> Repo.one()
|> Repo.preload(preload)
end
def get_different_event_with_code(nil, _event_id), do: nil
def get_different_event_with_code(code, event_id) do
now = DateTime.utc_now()
from(e in Event, where: e.code == ^code and e.id != ^event_id and e.expired_at > ^now)
|> Repo.one()
end
def is_leaded_by(email, event) do
from(a in ActivityLeader,
join: u in Claper.Accounts.User,
on: u.email == a.email,
join: e in Event,
on: e.id == a.event_id,
where: a.email == ^email and e.id == ^event.id,
order_by: [desc: e.expired_at]
)
|> Repo.exists?()
end
@doc """
Creates a event.
## Examples
iex> create_event(%{field: value})
{:ok, %Event{}}
iex> create_event(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_event(attrs) do
%Event{}
|> Event.create_changeset(attrs)
|> validate_unique_event()
|> case do
{:ok, event} ->
Repo.insert(event, returning: [:uuid])
{:error, changeset} ->
{:error, %{changeset | action: :insert}}
end
end
defp validate_unique_event(%Ecto.Changeset{changes: %{code: code} = _changes} = event) do
case get_event_with_code(code) do
%Event{} -> {:error, Ecto.Changeset.add_error(event, :code, "Already exists")}
nil -> {:ok, event}
end
end
defp validate_unique_event(%Ecto.Changeset{data: event} = changeset) do
case get_different_event_with_code(event.code, event.id) do
%Event{} -> {:error, Ecto.Changeset.add_error(changeset, :code, "Already exists")}
nil -> {:ok, changeset}
end
end
@doc """
Updates a event.
## Examples
iex> update_event(event, %{field: new_value})
{:ok, %Event{}}
iex> update_event(event, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_event(%Event{} = event, attrs) do
event
|> Event.update_changeset(attrs)
|> validate_unique_event()
|> case do
{:ok, event} ->
Repo.update(event, returning: [:uuid])
{:error, changeset} ->
{:error, %{changeset | action: :update}}
end
end
@doc """
Deletes a event.
## Examples
iex> delete_event(event)
{:ok, %Event{}}
iex> delete_event(event)
{:error, %Ecto.Changeset{}}
"""
def delete_event(%Event{} = event) do
Repo.delete(event)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking event changes.
## Examples
iex> change_event(event)
%Ecto.Changeset{data: %Event{}}
"""
def change_event(%Event{} = event, attrs \\ %{}) do
Event.changeset(event, attrs)
end
alias Claper.Events.ActivityLeader
@doc """
Returns the list of activity_leaders.
## Examples
iex> list_activity_leaders()
[%ActivityLeader{}, ...]
"""
def list_activity_leaders do
Repo.all(ActivityLeader)
end
@doc """
Gets a single activity_leader.
Raises `Ecto.NoResultsError` if the Activity leader does not exist.
## Examples
iex> get_activity_leader!(123)
%ActivityLeader{}
iex> get_activity_leader!(456)
** (Ecto.NoResultsError)
"""
def get_activity_leader!(id), do: Repo.get!(ActivityLeader, id)
def get_activity_leaders_for_event(event_id) do
from(a in ActivityLeader,
left_join: u in Claper.Accounts.User,
on: u.email == a.email,
where: a.event_id == ^event_id,
select: %{a | user_id: u.id}
)
|> Repo.all()
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking activity_leader changes.
## Examples
iex> change_activity_leader(activity_leader)
%Ecto.Changeset{data: %ActivityLeader{}}
"""
def change_activity_leader(%ActivityLeader{} = activity_leader, attrs \\ %{}) do
ActivityLeader.changeset(activity_leader, attrs)
end
end

View File

@@ -0,0 +1,43 @@
defmodule Claper.Events.ActivityLeader do
use Ecto.Schema
import Ecto.Changeset
schema "activity_leaders" do
field :temp_id, :string, virtual: true
field :delete, :boolean, virtual: true
field :user_id, :integer, virtual: true
field :email, :string
belongs_to :event, Claper.Events.Event
timestamps()
end
@doc false
def changeset(leader, attrs) do
leader
|> Map.put(:temp_id, leader.temp_id || attrs["temp_id"])
|> cast(attrs, [
:email,
:event_id,
:delete
])
|> validate_required([:email])
|> validate_format(:email, ~r/^[^\s]+@[^\s]+$/, message: "must have the @ sign and no spaces")
|> validate_length(:email, min: 6, max: 160)
|> unique_constraint(:email)
|> unsafe_validate_unique([:event_id, :email], Claper.Repo)
|> maybe_mark_for_deletion
end
defp maybe_mark_for_deletion(%{data: %{id: nil}} = changeset), do: changeset
defp maybe_mark_for_deletion(changeset) do
if get_change(changeset, :delete) do
%{changeset | action: :delete}
else
changeset
end
end
end

108
lib/claper/events/event.ex Normal file
View File

@@ -0,0 +1,108 @@
defmodule Claper.Events.Event do
use Ecto.Schema
import Ecto.Changeset
schema "events" do
field :uuid, :binary_id
field :name, :string
field :code, :string
field :audience_peak, :integer, default: 1
field :started_at, :naive_datetime
field :expired_at, :naive_datetime
field :date_range, :string, virtual: true
has_many :posts, Claper.Posts.Post
has_many :leaders, Claper.Events.ActivityLeader, on_replace: :delete
has_one :presentation_file, Claper.Presentations.PresentationFile
belongs_to :user, Claper.Accounts.User
timestamps()
end
@doc false
def changeset(event, attrs) do
event
|> cast(attrs, [
:name,
:code,
:started_at,
:expired_at,
:date_range,
:audience_peak
])
|> cast_assoc(:presentation_file)
|> cast_assoc(:leaders)
|> validate_required([:code])
|> validate_date_range
end
def create_changeset(event, attrs) do
event
|> cast(attrs, [:name, :code, :user_id, :started_at, :expired_at, :date_range])
|> cast_assoc(:presentation_file)
|> cast_assoc(:leaders)
|> validate_required([:code, :started_at, :expired_at])
|> downcase_code
end
def downcase_code(changeset) do
update_change(
changeset,
:code,
&(&1 |> String.downcase() |> String.split(~r"[^\w\d]", trim: true) |> List.first())
)
end
defp validate_date_range(changeset) do
date_range = get_change(changeset, :date_range)
if date_range != nil do
splited = date_range |> String.split(" - ")
if splited |> Enum.count() == 2 do
changeset
|> put_change(:started_at, Enum.at(splited, 0))
|> put_change(:expired_at, Enum.at(splited, 1))
else
add_error(changeset, :date_range, "invalid date range")
end
else
start_date = get_change(changeset, :started_at)
end_date = get_change(changeset, :expired_at)
if start_date != nil && end_date != nil do
changeset
|> put_change(:date_range, "#{start_date} - #{end_date}")
else
changeset
end
end
end
def update_changeset(event, attrs) do
event
|> cast(attrs, [:name, :code, :started_at, :expired_at, :date_range, :audience_peak])
|> cast_assoc(:presentation_file)
|> cast_assoc(:leaders)
|> validate_required([:code, :started_at, :expired_at])
|> downcase_code
end
def restart_changeset(event) do
expiry =
NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second) |> NaiveDateTime.add(48 * 3600)
change(event, expired_at: expiry)
end
def subscribe(event_id) do
Phoenix.PubSub.subscribe(Claper.PubSub, "event:#{event_id}")
end
def started?(event) do
NaiveDateTime.compare(NaiveDateTime.utc_now(), event.started_at) == :gt
end
end

3
lib/claper/mailer.ex Normal file
View File

@@ -0,0 +1,3 @@
defmodule Claper.Mailer do
use Swoosh.Mailer, otp_app: :claper
end

320
lib/claper/polls.ex Normal file
View File

@@ -0,0 +1,320 @@
defmodule Claper.Polls do
@moduledoc """
The Polls context.
"""
import Ecto.Query, warn: false
alias Claper.Repo
alias Claper.Polls.Poll
alias Claper.Polls.PollOpt
alias Claper.Polls.PollVote
@doc """
Returns the list of polls.
## Examples
iex> list_polls()
[%Poll{}, ...]
"""
def list_polls(presentation_file_id) do
from(p in Poll,
where: p.presentation_file_id == ^presentation_file_id,
order_by: [asc: p.id, asc: p.position]
)
|> Repo.all()
|> Repo.preload([:poll_opts])
end
def list_polls_at_position(presentation_file_id, position) do
from(p in Poll,
where: p.presentation_file_id == ^presentation_file_id and p.position == ^position,
order_by: [asc: p.id]
)
|> Repo.all()
|> Repo.preload([:poll_opts])
end
@doc """
Gets a single poll.
Raises `Ecto.NoResultsError` if the Poll does not exist.
## Examples
iex> get_poll!(123)
%Poll{}
iex> get_poll!(456)
** (Ecto.NoResultsError)
"""
def get_poll!(id),
do:
Repo.get!(Poll, id)
|> Repo.preload(
poll_opts:
from(
o in PollOpt,
order_by: [asc: o.id]
)
)
|> set_percentages()
def get_poll_current_position(presentation_file_id, position) do
from(p in Poll,
where:
p.position == ^position and p.presentation_file_id == ^presentation_file_id and
p.enabled == true
)
|> Repo.one()
|> Repo.preload(
poll_opts:
from(
o in PollOpt,
order_by: [asc: o.id]
)
)
|> set_percentages()
end
def set_percentages(%Poll{poll_opts: poll_opts} = poll) when is_list(poll_opts) do
total = Enum.map(poll.poll_opts, fn e -> e.vote_count end) |> Enum.sum()
%{
poll
| poll_opts:
poll.poll_opts
|> Enum.map(fn o -> %{o | percentage: calculate_percentage(o, total)} end)
}
end
def set_percentages(poll), do: poll
defp calculate_percentage(opt, total) do
if total > 0,
do: Float.round(opt.vote_count / total * 100) |> :erlang.float_to_binary(decimals: 0),
else: 0
end
@doc """
Creates a poll.
## Examples
iex> create_poll(%{field: value})
{:ok, %Poll{}}
iex> create_poll(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_poll(attrs \\ %{}) do
%Poll{}
|> Poll.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a poll.
## Examples
iex> update_poll(poll, %{field: new_value})
{:ok, %Poll{}}
iex> update_poll(poll, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_poll(event_uuid, %Poll{} = poll, attrs) do
poll
|> Poll.changeset(attrs)
|> Repo.update()
|> case do
{:ok, poll} ->
broadcast({:ok, poll, event_uuid}, :poll_updated)
{:error, changeset} ->
{:error, %{changeset | action: :update}}
end
end
@doc """
Deletes a poll.
## Examples
iex> delete_poll(poll)
{:ok, %Poll{}}
iex> delete_poll(poll)
{:error, %Ecto.Changeset{}}
"""
def delete_poll(event_uuid, %Poll{} = poll) do
{:ok, poll} = Repo.delete(poll)
broadcast({:ok, poll, event_uuid}, :poll_deleted)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking poll changes.
## Examples
iex> change_poll(poll)
%Ecto.Changeset{data: %Poll{}}
"""
def change_poll(%Poll{} = poll, attrs \\ %{}) do
Poll.changeset(poll, attrs)
end
@doc """
Add an empty poll opt to a poll changeset.
"""
def add_poll_opt(changeset) do
changeset
|> Ecto.Changeset.put_assoc(
:poll_opts,
Ecto.Changeset.get_field(changeset, :poll_opts) ++ [%PollOpt{}]
)
end
@doc """
Remove a poll opt from a poll changeset.
"""
def remove_poll_opt(changeset, poll_opt) do
changeset
|> Ecto.Changeset.put_assoc(
:poll_opts,
Ecto.Changeset.get_field(changeset, :poll_opts) -- [poll_opt]
)
end
def vote(user_id, event_uuid, %PollOpt{} = poll_opt, poll_id) when is_number(user_id) do
case Ecto.Multi.new()
|> Ecto.Multi.update(
:poll_opt,
PollOpt.changeset(poll_opt, %{"vote_count" => poll_opt.vote_count + 1})
)
|> Ecto.Multi.insert(:poll_vote, %PollVote{
user_id: user_id,
poll_opt_id: poll_opt.id,
poll_id: poll_id
})
|> Repo.transaction() do
{:ok, %{poll_opt: opt}} ->
opt =
Repo.preload(opt,
poll: [
poll_opts:
from(
o in PollOpt,
order_by: [asc: o.id]
)
]
)
broadcast({:ok, opt.poll |> set_percentages, event_uuid}, :poll_updated)
end
end
def vote(attendee_identifier, event_uuid, %PollOpt{} = poll_opt, poll_id) do
case Ecto.Multi.new()
|> Ecto.Multi.update(
:poll_opt,
PollOpt.changeset(poll_opt, %{"vote_count" => poll_opt.vote_count + 1})
)
|> Ecto.Multi.insert(:poll_vote, %PollVote{
attendee_identifier: attendee_identifier,
poll_opt_id: poll_opt.id,
poll_id: poll_id
})
|> Repo.transaction() do
{:ok, %{poll_opt: opt}} ->
opt =
Repo.preload(opt,
poll: [
poll_opts:
from(
o in PollOpt,
order_by: [asc: o.id]
)
]
)
broadcast({:ok, opt.poll |> set_percentages, event_uuid}, :poll_updated)
end
end
def set_default(id, presentation_file_id, position) do
from(p in Poll,
where:
p.presentation_file_id == ^presentation_file_id and p.position == ^position and
p.id != ^id
)
|> Repo.update_all(set: [enabled: false])
from(p in Poll,
where:
p.presentation_file_id == ^presentation_file_id and p.position == ^position and
p.id == ^id
)
|> Repo.update_all(set: [enabled: true])
end
defp broadcast({:error, _reason} = error, _poll), do: error
defp broadcast({:ok, poll, event_uuid}, event) do
Phoenix.PubSub.broadcast(
Claper.PubSub,
"event:#{event_uuid}",
{event, poll}
)
{:ok, poll}
end
@doc """
Gets a single poll_vote.
Raises `Ecto.NoResultsError` if the Poll vote does not exist.
## Examples
iex> get_poll_vote!(123)
%PollVote{}
iex> get_poll_vote!(456)
** (Ecto.NoResultsError)
"""
def get_poll_vote(user_id, poll_id) when is_number(user_id),
do: Repo.get_by(PollVote, poll_id: poll_id, user_id: user_id)
def get_poll_vote(attendee_identifier, poll_id),
do: Repo.get_by(PollVote, poll_id: poll_id, attendee_identifier: attendee_identifier)
@doc """
Creates a poll_vote.
## Examples
iex> create_poll_vote(%{field: value})
{:ok, %PollVote{}}
iex> create_poll_vote(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_poll_vote(attrs \\ %{}) do
%PollVote{}
|> PollVote.changeset(attrs)
|> Repo.insert()
end
end

26
lib/claper/polls/poll.ex Normal file
View File

@@ -0,0 +1,26 @@
defmodule Claper.Polls.Poll do
use Ecto.Schema
import Ecto.Changeset
@derive {Jason.Encoder, only: [:title, :position]}
schema "polls" do
field :title, :string
field :position, :integer
field :total, :integer, virtual: true
field :enabled, :boolean
belongs_to :presentation_file, Claper.Presentations.PresentationFile
has_many :poll_opts, Claper.Polls.PollOpt, on_replace: :delete
has_many :poll_votes, Claper.Polls.PollVote, on_replace: :delete
timestamps()
end
@doc false
def changeset(poll, attrs) do
poll
|> cast(attrs, [:title, :presentation_file_id, :position, :enabled, :total])
|> cast_assoc(:poll_opts, required: true)
|> validate_required([:title, :presentation_file_id, :position])
end
end

View File

@@ -0,0 +1,23 @@
defmodule Claper.Polls.PollOpt do
use Ecto.Schema
import Ecto.Changeset
@derive {Jason.Encoder, only: [:content, :vote_count]}
schema "poll_opts" do
field :content, :string
field :vote_count, :integer
field :percentage, :float, virtual: true
belongs_to :poll, Claper.Polls.Poll
has_many :poll_votes, Claper.Polls.PollVote, on_replace: :delete
timestamps()
end
@doc false
def changeset(poll_opt, attrs) do
poll_opt
|> cast(attrs, [:content, :vote_count, :poll_id])
|> validate_required([:content])
end
end

View File

@@ -0,0 +1,21 @@
defmodule Claper.Polls.PollVote do
use Ecto.Schema
import Ecto.Changeset
schema "poll_votes" do
field :attendee_identifier, :string
belongs_to :poll, Claper.Polls.Poll
belongs_to :poll_opt, Claper.Polls.PollOpt
belongs_to :user, Claper.Accounts.User
timestamps()
end
@doc false
def changeset(poll_vote, attrs) do
poll_vote
|> cast(attrs, [:attendee_identifier, :user_id, :poll_opt_id, :poll_id])
|> validate_required([:poll_opt_id, :poll_id])
end
end

233
lib/claper/posts.ex Normal file
View File

@@ -0,0 +1,233 @@
defmodule Claper.Posts do
@moduledoc """
The Posts context.
"""
import Ecto.Query, warn: false
alias Claper.Repo
alias Claper.Posts.Post
@doc """
Get event posts
"""
def list_posts(event_id, preload \\ []) do
from(p in Post,
join: e in Claper.Events.Event,
on: p.event_id == e.id,
select: p,
where: e.uuid == ^event_id,
order_by: [asc: p.id]
)
|> Repo.all()
|> Repo.preload(preload)
end
def reacted_posts(event_id, user_id, icon) when is_number(user_id) do
from(reaction in Claper.Posts.Reaction,
join: post in Claper.Posts.Post,
where:
reaction.icon == ^icon and reaction.post_id == post.id and reaction.user_id == ^user_id and
post.event_id == ^event_id,
distinct: true,
select: reaction.post_id
)
|> Repo.all()
end
def reacted_posts(event_id, attendee_identifier, icon) do
from(reaction in Claper.Posts.Reaction,
join: post in Claper.Posts.Post,
where:
reaction.icon == ^icon and reaction.post_id == post.id and
reaction.attendee_identifier == ^attendee_identifier and post.event_id == ^event_id,
distinct: true,
select: reaction.post_id
)
|> Repo.all()
end
@doc """
Gets a single post.
Raises `Ecto.NoResultsError` if the Post does not exist.
## Examples
iex> get_post!(123)
%Post{}
iex> get_post!(456)
** (Ecto.NoResultsError)
"""
def get_post!(id, preload \\ []), do: Repo.get_by!(Post, uuid: id) |> Repo.preload(preload)
@doc """
Creates a post.
## Examples
iex> create_post(%{field: value})
{:ok, %Post{}}
iex> create_post(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_post(event, attrs) do
%Post{}
|> Map.put(:event, event)
|> Post.changeset(attrs)
|> Repo.insert(returning: [:uuid])
|> broadcast(:post_created)
end
@doc """
Updates a post.
## Examples
iex> update_post(post, %{field: new_value})
{:ok, %Post{}}
iex> update_post(post, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_post(%Post{} = post, attrs) do
post
|> Post.changeset(attrs)
|> Repo.update()
|> broadcast(:post_updated)
end
@doc """
Deletes a post.
## Examples
iex> delete_post(post)
{:ok, %Post{}}
iex> delete_post(post)
{:error, %Ecto.Changeset{}}
"""
def delete_post(%Post{} = post) do
post
|> Repo.delete()
|> broadcast(:post_deleted)
end
def delete_all_posts(:attendee_identifier, attendee_identifier, event) do
posts =
from(post in Claper.Posts.Post,
where: post.attendee_identifier == ^attendee_identifier and post.event_id == ^event.id
)
|> Repo.all()
for post <- posts do
delete_post(%{post | event: event})
end
end
def delete_all_posts(:user_id, user_id, event) do
posts =
from(post in Claper.Posts.Post,
where: post.user_id == ^user_id and post.event_id == ^event.id
)
|> Repo.all()
for post <- posts do
delete_post(%{post | event: event})
end
end
alias Claper.Posts.{Reaction, Post}
@doc """
Gets a single reaction.
Raises `Ecto.NoResultsError` if the Reaction does not exist.
## Examples
iex> get_reaction!(123)
%Reaction{}
iex> get_reaction!(456)
** (Ecto.NoResultsError)
"""
def get_reaction!(id), do: Repo.get!(Reaction, id)
@doc """
Creates a reaction.
## Examples
iex> create_reaction(%{field: value})
{:ok, %Reaction{}}
iex> create_reaction(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_reaction(%{post: nil} = attrs), do: create_reaction(%{attrs | post: %Post{}})
def create_reaction(%{post: post} = attrs) do
case %Reaction{}
|> Map.put(:post_id, post.id)
|> Reaction.changeset(attrs)
|> Repo.insert() do
{:ok, reaction} ->
broadcast({:ok, post}, :reaction_added)
{:ok, reaction}
{:error, changeset} ->
{:error, changeset}
end
end
@doc """
Deletes a reaction.
## Examples
iex> delete_reaction(reaction)
{:ok, %Reaction{}}
iex> delete_reaction(reaction)
{:error, %Ecto.Changeset{}}
"""
def delete_reaction(%{user_id: user_id, post: post, icon: icon} = _params)
when is_integer(user_id) do
with reaction <- Repo.get_by!(Reaction, post_id: post.id, user_id: user_id, icon: icon) do
Repo.delete(reaction)
broadcast({:ok, post}, :reaction_removed)
end
end
def delete_reaction(
%{attendee_identifier: attendee_identifier, post: post, icon: icon} = _params
) do
with reaction <-
Repo.get_by!(Reaction,
post_id: post.id,
attendee_identifier: attendee_identifier,
icon: icon
) do
Repo.delete(reaction)
broadcast({:ok, post}, :reaction_removed)
end
end
defp broadcast({:error, _reason} = error, _event), do: error
defp broadcast({:ok, post}, event) do
Phoenix.PubSub.broadcast(Claper.PubSub, "event:#{post.event.uuid}", {event, post})
{:ok, post}
end
end

30
lib/claper/posts/post.ex Normal file
View File

@@ -0,0 +1,30 @@
defmodule Claper.Posts.Post do
use Ecto.Schema
import Ecto.Changeset
schema "posts" do
field :body, :string
field :uuid, :binary_id
field :like_count, :integer, default: 0
field :love_count, :integer, default: 0
field :lol_count, :integer, default: 0
field :name, :string
field :attendee_identifier, :string
field :position, :integer, default: 0
belongs_to :event, Claper.Events.Event
belongs_to :user, Claper.Accounts.User
has_many :reactions, Claper.Posts.Reaction
timestamps()
end
@doc false
def changeset(post, attrs) do
post
|> cast(attrs, [:body, :attendee_identifier, :user_id, :like_count, :love_count, :lol_count, :position])
|> validate_required([:body, :position])
|> validate_length(:body, min: 2, max: 250)
end
end

View File

@@ -0,0 +1,21 @@
defmodule Claper.Posts.Reaction do
use Ecto.Schema
import Ecto.Changeset
schema "reactions" do
field :icon, :string
field :attendee_identifier, :string
belongs_to :post, Claper.Posts.Post
belongs_to :user, Claper.Accounts.User
timestamps()
end
@doc false
def changeset(reaction, attrs) do
reaction
|> cast(attrs, [:icon, :attendee_identifier, :user_id, :post_id])
|> validate_required([:icon, :post_id])
end
end

121
lib/claper/presentations.ex Normal file
View File

@@ -0,0 +1,121 @@
defmodule Claper.Presentations do
@moduledoc """
The Presentations context.
"""
import Ecto.Query, warn: false
alias Claper.Repo
alias Claper.Presentations.PresentationFile
@doc """
Gets a single presentation_files.
Raises `Ecto.NoResultsError` if the Presentation files does not exist.
## Examples
iex> get_presentation_file!(123)
%PresentationFile{}
iex> get_presentation_file!(456)
** (Ecto.NoResultsError)
"""
def get_presentation_file!(id, preload \\ []),
do: Repo.get!(PresentationFile, id) |> Repo.preload(preload)
def get_presentation_file_by_hash!(hash) when is_binary(hash),
do: Repo.get_by(PresentationFile, hash: hash) |> Repo.preload([:event])
@doc """
Creates a presentation_files.
## Examples
iex> create_presentation_file(%{field: value})
{:ok, %PresentationFile{}}
iex> create_presentation_file(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_presentation_file(attrs \\ %{}) do
%PresentationFile{}
|> PresentationFile.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a presentation_files.
## Examples
iex> update_presentation_file(presentation_files, %{field: new_value})
{:ok, %PresentationFile{}}
iex> update_presentation_file(presentation_files, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_presentation_file(%PresentationFile{} = presentation_file, attrs) do
presentation_file
|> PresentationFile.changeset(attrs)
|> Repo.update()
end
def subscribe(presentation_file_id) do
Phoenix.PubSub.subscribe(Claper.PubSub, "presentation:#{presentation_file_id}")
end
alias Claper.Presentations.PresentationState
@doc """
Creates a presentation_state.
## Examples
iex> create_presentation_state(%{field: value})
{:ok, %PresentationState{}}
iex> create_presentation_state(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_presentation_state(attrs \\ %{}) do
%PresentationState{}
|> PresentationState.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a presentation_state.
## Examples
iex> update_presentation_state(presentation_state, %{field: new_value})
{:ok, %PresentationState{}}
iex> update_presentation_state(presentation_state, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_presentation_state(%PresentationState{} = presentation_state, attrs) do
presentation_state
|> PresentationState.changeset(attrs)
|> Repo.update()
|> broadcast(:state_updated)
end
defp broadcast({:error, _reason} = error, _state), do: error
defp broadcast({:ok, state}, event) do
Phoenix.PubSub.broadcast(
Claper.PubSub,
"presentation:#{state.presentation_file_id}",
{event, state}
)
{:ok, state}
end
end

View File

@@ -0,0 +1,23 @@
defmodule Claper.Presentations.PresentationFile do
use Ecto.Schema
import Ecto.Changeset
schema "presentation_files" do
field :hash, :string
field :length, :integer
field :status, :string
belongs_to :event, Claper.Events.Event
has_many :polls, Claper.Polls.Poll
has_one :presentation_state, Claper.Presentations.PresentationState, on_replace: :delete
timestamps()
end
@doc false
def changeset(presentation_file, attrs) do
presentation_file
|> cast(attrs, [:length, :status, :hash])
|> cast_assoc(:presentation_state)
end
end

View File

@@ -0,0 +1,23 @@
defmodule Claper.Presentations.PresentationState do
use Ecto.Schema
import Ecto.Changeset
schema "presentation_states" do
field :position, :integer
field :chat_visible, :boolean
field :poll_visible, :boolean
field :join_screen_visible, :boolean
field :banned, {:array, :string}, default: []
belongs_to :presentation_file, Claper.Presentations.PresentationFile
timestamps()
end
@doc false
def changeset(presentation_state, attrs) do
presentation_state
|> cast(attrs, [:position, :chat_visible, :poll_visible, :join_screen_visible, :banned])
|> validate_required([])
end
end

30
lib/claper/release.ex Normal file
View File

@@ -0,0 +1,30 @@
defmodule Claper.Release do
@moduledoc """
Used for executing DB release tasks when run in production without Mix
installed.
"""
@app :claper
def migrate do
load_app()
Application.ensure_all_started(:ssl)
for repo <- repos() do
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true))
end
end
def rollback(repo, version) do
load_app()
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version))
end
defp repos do
Application.fetch_env!(@app, :ecto_repos)
end
defp load_app do
Application.load(@app)
end
end

9
lib/claper/repo.ex Normal file
View File

@@ -0,0 +1,9 @@
defmodule Claper.Repo do
use Ecto.Repo,
otp_app: :claper,
adapter: Ecto.Adapters.Postgres
def init(_type, config) do
{:ok, Keyword.put(config, :url, System.get_env("DATABASE_URL"))}
end
end

9
lib/claper/schema.ex Normal file
View File

@@ -0,0 +1,9 @@
defmodule Claper.Schema do
defmacro __using__(_) do
quote do
use Ecto.Schema
@primary_key {:id, :binary_id, autogenerate: false}
@foreign_key_type :binary_id
end
end
end

27
lib/claper/stats.ex Normal file
View File

@@ -0,0 +1,27 @@
defmodule Claper.Stats do
@moduledoc """
The Stats context.
"""
import Ecto.Query, warn: false
alias Claper.Repo
def distinct_poster_count(event_id) do
from(posts in Claper.Posts.Post,
where: posts.event_id == ^event_id,
select: count(posts.user_id, :distinct) + count(posts.attendee_identifier, :distinct)
)
|> Repo.one()
end
def total_vote_count(presentation_file_id) do
from(p in Claper.Polls.Poll,
join: o in Claper.Polls.PollOpt,
on: o.poll_id == p.id,
where: p.presentation_file_id == ^presentation_file_id,
group_by: o.poll_id,
select: sum(o.vote_count)
)
|> Repo.all()
end
end

View File

@@ -0,0 +1,197 @@
defmodule Claper.Tasks.Converter do
@moduledoc """
This module is used to convert presentations from PDF or PPT to images.
We use a hash to identify the presentation. A new hash is generated when the conversion is finished and the presentation is being uploaded.
"""
alias ExAws.S3
alias Porcelain.Result
@doc """
Convert the presentation file to images.
We use original hash :erlang.phash2(code-name) where the files are uploaded to send it to another folder with a new hash. This last stored in db.
"""
def convert(user_id, file, hash, ext, presentation_file_id) do
presentation = Claper.Presentations.get_presentation_file!(presentation_file_id, [:event])
{:ok, presentation} =
Claper.Presentations.update_presentation_file(presentation, %{
"status" => "progress"
})
Phoenix.PubSub.broadcast(
Claper.PubSub,
"events:#{user_id}",
{:presentation_file_process_done, presentation}
)
path =
Path.join([
:code.priv_dir(:claper),
"static",
"uploads",
"#{hash}"
])
IO.puts("Starting conversion for #{hash}...")
file_to_pdf(String.to_atom(ext), path, file)
|> pdf_to_jpg(path, presentation, user_id)
|> jpg_upload(hash, path, presentation, user_id)
end
@doc """
Remove the presentation files directory
"""
def clear(hash) do
IO.puts("Clearing #{hash}...")
if System.get_env("PRESENTATION_STORAGE") == "local" do
File.rm_rf(Path.join([
:code.priv_dir(:claper),
"static",
"uploads",
"#{hash}"
]))
else
stream =
ExAws.S3.list_objects(System.get_env("AWS_PRES_BUCKET"), prefix: "presentations/#{hash}")
|> ExAws.stream!()
|> Stream.map(& &1.key)
ExAws.S3.delete_all_objects(System.get_env("AWS_PRES_BUCKET"), stream) |> ExAws.request()
end
end
defp file_to_pdf(:ppt, path, file) do
Porcelain.exec(
"libreoffice",
[
"--headless",
"--invisible",
"--convert-to",
"pdf",
"--outdir",
path,
"#{path}/#{file}"
]
)
end
defp file_to_pdf(:pptx, path, file) do
Porcelain.exec(
"libreoffice",
[
"--headless",
"--invisible",
"--convert-to",
"pdf",
"--outdir",
path,
"#{path}/#{file}"
]
)
end
defp file_to_pdf(_ext, _path, _file), do: %Result{status: 0}
defp pdf_to_jpg(%Result{status: 0}, path, _presentation, _user_id) do
Porcelain.exec(
"gs",
[
"-sDEVICE=png16m",
"-o#{path}/%d.jpg",
"-r300x300",
"-dNOPAUSE",
"-dBATCH",
"#{path}/original.pdf"
]
)
end
defp pdf_to_jpg(_result, path, presentation, user_id) do
failure(presentation, path, user_id)
end
defp jpg_upload(%Result{status: 0}, hash, path, presentation, user_id) do
files = Path.wildcard("#{path}/*.jpg")
# assign new hash to avoid cache issues
new_hash = :erlang.phash2("#{hash}-#{System.system_time(:second)}")
if System.get_env("PRESENTATION_STORAGE") == "local" do
File.rename(Path.join([
:code.priv_dir(:claper),
"static",
"uploads",
"#{hash}"
]), Path.join([
:code.priv_dir(:claper),
"static",
"uploads",
"#{new_hash}"
]))
else
for f <- files do
IO.puts("Uploads #{f} to presentations/#{new_hash}/#{Path.basename(f)}")
f
|> S3.Upload.stream_file()
|> S3.upload(
System.get_env("AWS_PRES_BUCKET"),
"presentations/#{new_hash}/#{Path.basename(f)}",
acl: "public-read"
)
|> ExAws.request()
end
end
if !is_nil(presentation.hash) do
clear(presentation.hash)
end
success(presentation, path, new_hash, length(files), user_id)
end
defp jpg_upload(_result, _hash, path, presentation, user_id) do
failure(presentation, path, user_id)
end
defp success(presentation, path, hash, length, user_id) do
with {:ok, presentation} <-
Claper.Presentations.update_presentation_file(presentation, %{
"hash" => "#{hash}",
"length" => length,
"status" => "done"
}) do
unless System.get_env("PRESENTATION_STORAGE") == "local", do: File.rm_rf!(path)
Phoenix.PubSub.broadcast(
Claper.PubSub,
"events:#{user_id}",
{:presentation_file_process_done, presentation}
)
end
end
defp failure(presentation, path, user_id) do
with {:ok, presentation} <-
Claper.Presentations.update_presentation_file(presentation, %{
"status" => "fail"
}) do
File.rm_rf!(path)
Phoenix.PubSub.broadcast(
Claper.PubSub,
"events:#{user_id}",
{:presentation_file_process_done, presentation}
)
end
end
end

114
lib/claper_web.ex Normal file
View File

@@ -0,0 +1,114 @@
defmodule ClaperWeb do
@moduledoc """
The entrypoint for defining your web interface, such
as controllers, views, channels and so on.
This can be used in your application as:
use ClaperWeb, :controller
use ClaperWeb, :view
The definitions below will be executed for every view,
controller, etc, so keep them short and clean, focused
on imports, uses and aliases.
Do NOT define functions inside the quoted expressions
below. Instead, define any helper function in modules
and import those modules here.
"""
def controller do
quote do
use Phoenix.Controller, namespace: ClaperWeb
import Plug.Conn
import ClaperWeb.Gettext
alias ClaperWeb.Router.Helpers, as: Routes
end
end
def view do
quote do
use Phoenix.View,
root: "lib/claper_web/templates",
namespace: ClaperWeb
# Import convenience functions from controllers
import Phoenix.Controller,
only: [get_flash: 1, get_flash: 2, view_module: 1, view_template: 1]
# Include shared imports and aliases for views
unquote(view_helpers())
end
end
def live_view do
quote do
use Phoenix.LiveView,
layout: {ClaperWeb.LayoutView, "live.html"}
unquote(view_helpers())
end
end
def live_component do
quote do
use Phoenix.LiveComponent
unquote(view_helpers())
end
end
def router do
quote do
use Phoenix.Router
import Plug.Conn
import Phoenix.Controller
import Phoenix.LiveView.Router
end
end
def view_component do
quote do
use Phoenix.HTML
use Phoenix.Component
import ClaperWeb.ErrorHelpers
alias Phoenix.LiveView.JS
end
end
def channel do
quote do
use Phoenix.Channel
import Phoenix.View
import ClaperWeb.Gettext
end
end
defp view_helpers do
quote do
# Use all HTML functionality (forms, tags, etc)
use Phoenix.HTML
# Import LiveView and .heex helpers (live_render, live_patch, <.form>, etc)
import Phoenix.LiveView.Helpers
import ClaperWeb.LiveHelpers
alias Phoenix.LiveView.JS
# Import basic rendering functionality (render, render_layout, etc)
import Phoenix.View
import ClaperWeb.ErrorHelpers
import ClaperWeb.Gettext
alias ClaperWeb.Router.Helpers, as: Routes
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end

View File

@@ -0,0 +1,10 @@
defmodule ClaperWeb.Presence do
@moduledoc """
Provides presence tracking to channels and processes.
See the [`Phoenix.Presence`](http://hexdocs.pm/phoenix/Phoenix.Presence.html)
docs for more details.
"""
use Phoenix.Presence, otp_app: :claper,
pubsub_server: Claper.PubSub
end

View File

@@ -0,0 +1,71 @@
defmodule ClaperWeb.EventController do
use ClaperWeb, :controller
def attendee_identifier(conn, _opts) do
conn |> set_token()
end
defp set_token(conn) do
if is_nil(get_session(conn, :attendee_identifier)) do
token = Base.url_encode64(:crypto.strong_rand_bytes(8))
conn
|> put_session(:attendee_identifier, token)
else
conn
end
end
def slide_generate(conn, %{"uuid" => uuid, "qr" => qr} = _opts) do
with event <- Claper.Events.get_event!(uuid) do
"data:image/png;base64," <> raw = qr
{:ok, data} = Base.decode64(raw)
dir = System.tmp_dir!()
tmp_file = Path.join(dir, "qr-#{uuid}.png")
File.write!(tmp_file, data, [:binary])
code = String.upcase(event.code)
{output, 0} =
System.cmd("convert", [
"-size",
"1920x1080",
"xc:black",
"-fill",
"white",
"-font",
"Roboto",
"-pointsize",
"45",
"-gravity",
"north",
"-annotate",
"+0+100",
"Scannez pour interagir en temps-réel",
"-gravity",
"center",
"-annotate",
"+0+200",
"Ou allez sur Claper.co et utilisez le code:",
"-pointsize",
"65",
"-gravity",
"center",
"-annotate",
"+0+350",
"##{code}",
tmp_file,
"-gravity",
"north",
"-geometry",
"+0+230",
"-composite",
"jpg:-"
])
conn
|> put_resp_content_type("image/png")
|> send_resp(200, output)
end
end
end

View File

@@ -0,0 +1,18 @@
defmodule ClaperWeb.PageController do
use ClaperWeb, :controller
def index(conn, _params) do
conn
|> render("index.html")
end
def tos(conn, _params) do
conn
|> render("tos.html")
end
def privacy(conn, _params) do
conn
|> render("privacy.html")
end
end

View File

@@ -0,0 +1,32 @@
defmodule ClaperWeb.PostController do
use ClaperWeb, :controller
def index(conn, %{"event_id" => event_id}) do
try do
with event <- Claper.Events.get_event!(event_id),
posts <- Claper.Posts.list_posts(event.uuid, [:user, :attendee]) do
render(conn, "index.json", posts: posts)
end
rescue
Ecto.NoResultsError -> conn
|> put_status(:not_found)
|> put_view(ClaperWeb.ErrorView)
|> render(:"404")
end
end
def create(conn, %{"event_id" => event_id, "body" => body}) do
try do
with event <- Claper.Events.get_event!(event_id) do
case Claper.Posts.create_post(event, %{body: body}) do
{:ok, post} -> render(conn, "post.json", post: post)
end
end
rescue
Ecto.NoResultsError -> conn
|> put_status(:not_found)
|> put_view(ClaperWeb.ErrorView)
|> render(:"404")
end
end
end

View File

@@ -0,0 +1,154 @@
defmodule ClaperWeb.UserAuth do
import Plug.Conn
import Phoenix.Controller
alias Claper.Accounts
alias ClaperWeb.Router.Helpers, as: Routes
# Make the remember me cookie valid for 60 days.
# If you want bump or reduce this value, also change
# the token expiry itself in UserToken.
@max_age 60 * 60 * 24 * 60
@remember_me_cookie "_claper_web_user_remember_me"
@remember_me_options [sign: true, max_age: @max_age, same_site: "Lax"]
@doc """
Logs the user in.
It renews the session ID and clears the whole session
to avoid fixation attacks. See the renew_session
function to customize this behaviour.
It also sets a `:live_socket_id` key in the session,
so LiveView sessions are identified and automatically
disconnected on log out. The line can be safely removed
if you are not using LiveView.
"""
def log_in_user(conn, user, params \\ %{}) do
token = Accounts.generate_user_session_token(user)
user_return_to = get_session(conn, :user_return_to)
conn
|> renew_session()
|> put_session(:user_token, token)
|> put_session(:live_socket_id, "users_sessions:#{Base.url_encode64(token)}")
|> maybe_write_remember_me_cookie(token, params)
|> redirect(to: user_return_to || signed_in_path(conn))
end
defp maybe_write_remember_me_cookie(conn, token, %{"remember_me" => "true"}) do
put_resp_cookie(conn, @remember_me_cookie, token, @remember_me_options)
end
defp maybe_write_remember_me_cookie(conn, _token, _params) do
conn
end
# This function renews the session ID and erases the whole
# session to avoid fixation attacks. If there is any data
# in the session you may want to preserve after log in/log out,
# you must explicitly fetch the session data before clearing
# and then immediately set it after clearing, for example:
#
# defp renew_session(conn) do
# preferred_locale = get_session(conn, :preferred_locale)
#
# conn
# |> configure_session(renew: true)
# |> clear_session()
# |> put_session(:preferred_locale, preferred_locale)
# end
#
defp renew_session(conn) do
conn
|> configure_session(renew: true)
|> clear_session()
end
@doc """
Logs the user out.
It clears all session data for safety. See renew_session.
"""
def log_out_user(conn) do
user_token = get_session(conn, :user_token)
user_token && Accounts.delete_session_token(user_token)
if live_socket_id = get_session(conn, :live_socket_id) do
ClaperWeb.Endpoint.broadcast(live_socket_id, "disconnect", %{})
end
conn
|> renew_session()
|> delete_resp_cookie(@remember_me_cookie)
|> redirect(to: "/")
end
@doc """
Authenticates the user by looking into the session
and remember me token.
"""
def fetch_current_user(conn, _opts) do
{user_token, conn} = ensure_user_token(conn)
user = user_token && Accounts.get_user_by_session_token(user_token)
conn |> put_session(:current_user, user) |> assign(:current_user, user)
end
defp ensure_user_token(conn) do
if user_token = get_session(conn, :user_token) do
{user_token, conn}
else
conn = fetch_cookies(conn, signed: [@remember_me_cookie])
if user_token = conn.cookies[@remember_me_cookie] do
{user_token, put_session(conn, :user_token, user_token)}
else
{nil, conn}
end
end
end
@doc """
Used for routes that require the user to not be authenticated.
"""
def redirect_if_user_is_authenticated(conn, _opts) do
if conn.assigns[:current_user] do
conn
|> redirect(to: signed_in_path(conn))
|> halt()
else
conn
end
end
@doc """
Used for routes that require the user to be authenticated.
If you want to enforce the user email is confirmed before
they use the application at all, here would be a good place.
"""
def require_authenticated_user(conn, _opts) do
if conn.assigns[:current_user] do
if conn.assigns[:current_user].confirmed_at do
conn
else
conn
|> redirect(to: Routes.user_registration_path(conn, :confirm))
end
else
conn
|> put_flash(:error, "You must log in to access this page.")
|> maybe_store_return_to()
|> redirect(to: Routes.user_session_path(conn, :new))
|> halt()
end
end
defp maybe_store_return_to(%{method: "GET"} = conn) do
put_session(conn, :user_return_to, current_path(conn))
end
defp maybe_store_return_to(conn), do: conn
defp signed_in_path(_conn), do: "/events"
end

View File

@@ -0,0 +1,80 @@
defmodule ClaperWeb.UserConfirmationController do
use ClaperWeb, :controller
alias Claper.Accounts
def new(conn, _params) do
render(conn, "new.html")
end
def create(conn, %{"user" => %{"email" => email}}) do
if user = Accounts.get_user_by_email(email) do
Accounts.deliver_user_confirmation_instructions(
user,
&Routes.user_confirmation_url(conn, :edit, &1)
)
end
# In order to prevent user enumeration attacks, regardless of the outcome, show an impartial success/error message.
conn
|> put_flash(
:info,
"If your email is in our system and it has not been confirmed yet, " <>
"you will receive an email with instructions shortly."
)
|> redirect(to: "/")
end
def edit(conn, %{"token" => token}) do
render(conn, "edit.html", token: token)
end
# Do not log in the user after confirmation to avoid a
# leaked token giving the user access to the account.
def update(conn, %{"token" => token}) do
case Accounts.confirm_user(token) do
{:ok, _} ->
conn
|> put_flash(:info, "User confirmed successfully.")
|> redirect(to: "/")
:error ->
# If there is a current user and the account was already confirmed,
# then odds are that the confirmation link was already visited, either
# by some automation or by the user themselves, so we redirect without
# a warning message.
case conn.assigns do
%{current_user: %{confirmed_at: confirmed_at}} when not is_nil(confirmed_at) ->
redirect(conn, to: "/")
%{} ->
conn
|> put_flash(:error, "User confirmation link is invalid or it has expired.")
|> redirect(to: "/")
end
end
end
def confirm_magic(conn, %{"token" => token} = _params) do
case Accounts.confirm_magic(token) do
{:ok, user} ->
conn
|> ClaperWeb.UserAuth.log_in_user(user, %{"remember_me" => "true"})
:error ->
# If there is a current user and the account was already confirmed,
# then odds are that the confirmation link was already visited, either
# by some automation or by the user themselves, so we redirect without
# a warning message.
case conn.assigns do
%{current_user: %{confirmed_at: confirmed_at}} when not is_nil(confirmed_at) ->
redirect(conn, to: "/")
%{} ->
conn
|> put_flash(:error, "Magic link is invalid or has expired.")
|> redirect(to: "/")
end
end
end
end

View File

@@ -0,0 +1,34 @@
defmodule ClaperWeb.UserRegistrationController do
use ClaperWeb, :controller
alias Claper.Accounts
alias Claper.Accounts.User
alias ClaperWeb.UserAuth
def new(conn, _params) do
changeset = Accounts.change_user_registration(%User{})
render(conn, "new.html", changeset: changeset)
end
def confirm(conn, _params) do
render(conn, "confirm.html")
end
def create(conn, %{"user" => user_params}) do
case Accounts.register_user(user_params) do
{:ok, user} ->
{:ok, _} =
Accounts.deliver_user_confirmation_instructions(
user,
&Routes.user_confirmation_url(conn, :edit, &1)
)
conn
|> put_flash(:info, "User created successfully.")
|> UserAuth.log_in_user(user)
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new.html", changeset: changeset)
end
end
end

View File

@@ -0,0 +1,23 @@
defmodule ClaperWeb.UserSessionController do
use ClaperWeb, :controller
alias Claper.Accounts
alias ClaperWeb.UserAuth
def new(conn, _params) do
conn
|> render("new.html", error_message: nil)
end
def create(conn, %{"user" => %{"email" => email}} = _user_params) do
Accounts.deliver_magic_link(email, &Routes.user_confirmation_url(conn, :confirm_magic, &1))
conn
|> redirect(to: Routes.user_registration_path(conn, :confirm, %{email: email}))
end
def delete(conn, _params) do
conn
|> UserAuth.log_out_user()
end
end

View File

@@ -0,0 +1,56 @@
defmodule ClaperWeb.UserSettingsController do
use ClaperWeb, :controller
alias Claper.Accounts
plug :assign_email_and_password_changesets
def edit(conn, _params) do
render(conn, "edit.html")
end
def update(conn, %{"action" => "update_email"} = params) do
%{"user" => user_params} = params
user = conn.assigns.current_user
case Accounts.apply_user_email(user, user_params) do
{:ok, applied_user} ->
Accounts.deliver_update_email_instructions(
applied_user,
user.email,
&Routes.user_settings_url(conn, :confirm_email, &1)
)
conn
|> put_flash(
:info,
"A link to confirm your email change has been sent to the new address."
)
|> redirect(to: Routes.user_settings_show_path(conn, :show))
{:error, changeset} ->
render(conn, "edit.html", email_changeset: changeset)
end
end
def confirm_email(conn, %{"token" => token}) do
case Accounts.update_user_email(conn.assigns.current_user, token) do
:ok ->
conn
|> put_flash(:info, "Email changed successfully.")
|> redirect(to: Routes.user_settings_show_path(conn, :show))
:error ->
conn
|> put_flash(:error, "Email change link is invalid or it has expired.")
|> redirect(to: Routes.user_settings_show_path(conn, :show))
end
end
defp assign_email_and_password_changesets(conn, _opts) do
user = conn.assigns.current_user
conn
|> assign(:email_changeset, Accounts.change_user_email(user))
end
end

View File

@@ -0,0 +1,51 @@
defmodule ClaperWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :claper
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_claper_key",
signing_salt: "Tg18Y2zU"
]
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :claper,
gzip: false,
only:
~w(assets fonts .well-known uploads images favicon.ico robots.txt loaderio-eb3b956a176cdd4f54eb8570ce8bbb06.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :claper
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug ClaperWeb.Router
end

24
lib/claper_web/gettext.ex Normal file
View File

@@ -0,0 +1,24 @@
defmodule ClaperWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import ClaperWeb.Gettext
# Simple translation
gettext("Here is the string to translate")
# Plural translation
ngettext("Here is the string to translate",
"Here are the strings to translate",
3)
# Domain-based translation
dgettext("errors", "Here is the error message to translate")
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :claper
end

View File

@@ -0,0 +1,12 @@
defmodule ClaperWeb.AttendeeLiveAuth do
import Phoenix.LiveView
def on_mount(:default, _params, session, socket) do
socket =
socket
|> assign(:attendee_identifier, session["attendee_identifier"])
|> assign(:current_user, session["current_user"])
{:cont, socket}
end
end

View File

@@ -0,0 +1,135 @@
defmodule ClaperWeb.EventLive.EventCardComponent do
use ClaperWeb, :live_component
def render(assigns) do
assigns =
assigns
|> assign_new(:is_leader, fn -> false end)
~H"""
<li class="w-full my-4">
<div class="block bg-white rounded-2xl shadow-base">
<div class="px-4 py-4 sm:px-6">
<div class="flex items-center justify-between">
<p class="text-lg font-medium text-primary-600 truncate">
<%= @event.name %>
</p>
<div class="ml-2 flex-shrink-0 flex">
<%= if NaiveDateTime.compare(@current_time, @event.started_at) == :gt and NaiveDateTime.compare(@current_time, @event.expired_at) == :lt do %>
<p class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-yellow-100 text-yellow-800">
<%= gettext "In progress" %>
</p>
<% end %>
<%= if NaiveDateTime.compare(@current_time, @event.started_at) == :lt do %>
<p class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-green-100 text-green-800">
<%= gettext "Incoming" %>
</p>
<% end %>
<%= if NaiveDateTime.compare(@current_time, @event.expired_at) == :gt do %>
<p class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-gray-100 text-gray-800">
<%= gettext "Finished" %>
</p>
<% end %>
</div>
</div>
<div class="mt-2 flex flex-col space-y-2 sm:space-y-0 justify-between sm:flex-row items-start">
<div class="text-sm font-medium uppercase text-gray-700 flex justify-center space-x-1 items-center">
<img src="/images/icons/hashtag.svg" class="h-5 w-5" />
<p>
<%= @event.code %>
</p>
</div>
<div class="flex items-center text-sm text-gray-500 space-x-1" phx-update="ignore">
<img src="/images/icons/calendar-clear-outline.svg" class="h-5 w-5" />
<%= if NaiveDateTime.compare(@current_time, @event.started_at) == :gt and NaiveDateTime.compare(@current_time, @event.expired_at) == :lt do %>
<p>
<%= gettext "Finish on" %> <span x-text={"moment.utc('#{@event.expired_at}').local().format('lll')"}></span>
</p>
<% end %>
<%= if NaiveDateTime.compare(@current_time, @event.started_at) == :lt do %>
<p>
<%= gettext "Starting on" %> <span x-text={"moment.utc('#{@event.started_at}').local().format('lll')"}></span>
</p>
<% end %>
<%= if NaiveDateTime.compare(@current_time, @event.expired_at) == :gt do %>
<p>
<%= gettext "Finished on" %> <span x-text={"moment.utc('#{@event.expired_at}').local().format('lll')"}></span>
</p>
<% end %>
</div>
</div>
<%= if @event.presentation_file.status == "fail" && @event.presentation_file.hash do %>
<p class="text-sm font-normal text-supporting-red-500 text-left pt-2"><%= gettext("Error when processing the new file") %></p>
<% end %>
<%= if NaiveDateTime.compare(@current_time, @event.expired_at) == :lt do %>
<%= if @event.presentation_file.status == "done" || (@event.presentation_file.status == "fail" && @event.presentation_file.hash) do %>
<div class="mt-2 flex flex-col space-y-2 sm:space-y-0 justify-between sm:flex-row items-center">
<div class="text-sm w-full space-y-2 sm:w-auto font-medium text-gray-700 sm:flex sm:justify-center sm:space-x-1 sm:space-y-0 sm:items-center" phx-update="ignore">
<a data-phx-link="patch" data-phx-link-state="push" href={Routes.event_manage_path(@socket, :show, @event.code)} class="flex w-full lg:w-auto px-6 text-white py-2 justify-center rounded-md tracking-wide font-bold focus:outline-none focus:shadow-outline hover:bg-primary-600 bg-primary-500 space-x-2">
<img src="/images/icons/easel.svg" class="h-5" />
<span><%= gettext "Present/Customize" %></span>
</a>
<a target="_blank" href={Routes.event_show_path(@socket, :show, @event.code)} class="flex w-full lg:w-auto px-6 text-primary-500 py-2 justify-center rounded-md tracking-wide focus:outline-none focus:shadow-outline bg-white items-center space-x-2">
<img src="/images/icons/eye.svg" class="h-5" />
<span><%= gettext "Join" %></span>
</a>
</div>
<div>
<%= if not @is_leader do %>
<a data-phx-link="patch" data-phx-link-state="push" href={Routes.event_index_path(@socket, :edit, @event.uuid)} class="flex w-full lg:w-auto text-white rounded-md tracking-wide focus:outline-none focus:shadow-outline text-primary-500 text-sm items-center">
<span><%= gettext "Edit" %></span>
</a>
<% end %>
</div>
</div>
<% end %>
<%= if @event.presentation_file.status == "fail" && is_nil(@event.presentation_file.hash) do %>
<div class="mt-2 flex flex-col space-y-2 sm:space-y-0 justify-between sm:flex-row items-center">
<span class="text-sm text-supporting-red-500"><%= gettext("Error when processing the file") %></span>
<div>
<%= if not @is_leader do %>
<a data-phx-link="patch" data-phx-link-state="push" href={Routes.event_index_path(@socket, :edit, @event.uuid)} class="flex w-full lg:w-auto text-white rounded-md tracking-wide focus:outline-none focus:shadow-outline text-primary-500 text-sm items-center">
<span><%= gettext "Edit" %></span>
</a>
<% end %>
</div>
</div>
<% end %>
<%= if @event.presentation_file.status == "progress" do %>
<div class="flex space-x-1 items-center">
<img src="/images/loading.gif" class="h-8" />
<span class="text-sm text-gray-500"><%= gettext("Processing your file...") %></span>
</div>
<% end %>
<% end %>
<%= if NaiveDateTime.compare(@current_time, @event.expired_at) == :gt do %>
<div class="mt-2 flex flex-col space-y-2 sm:space-y-0 justify-between sm:flex-row items-center">
<div class="text-sm w-full space-y-2 sm:w-auto font-medium text-gray-700 sm:flex sm:justify-center sm:space-x-1 sm:space-y-0 sm:items-center" phx-update="ignore">
<a data-phx-link="patch" data-phx-link-state="push" href={Routes.stat_index_path(@socket, :index, @event.uuid)} class="flex w-full lg:w-auto px-6 text-white py-2 justify-center rounded-md tracking-wide font-bold focus:outline-none focus:shadow-outline hover:bg-primary-600 bg-primary-500 space-x-2">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path d="M2 10a8 8 0 018-8v8h8a8 8 0 11-16 0z" />
<path d="M12 2.252A8.014 8.014 0 0117.748 8H12V2.252z" />
</svg>
<span><%= gettext "Report" %></span>
</a>
</div>
<div>
<%= if not @is_leader do %>
<%= link gettext("Delete"), to: "#", phx_click: "delete", phx_value_id: @event.uuid, data: [confirm: gettext("This will delete all data related to your event, this cannot be undone. Confirm ?")], class: "flex w-full lg:w-auto text-white rounded-md tracking-wide focus:outline-none focus:shadow-outline text-red-500 text-sm items-center" %>
<% end %>
</div>
</div>
<% end %>
</div>
</div>
</li>
"""
end
end

View File

@@ -0,0 +1,221 @@
defmodule ClaperWeb.EventLive.FormComponent do
use ClaperWeb, :live_component
alias Claper.Events
@impl true
def update(%{event: event} = assigns, socket) do
changeset = Events.change_event(event)
{:ok,
socket
|> assign(assigns)
|> assign(:changeset, changeset)
|> allow_upload(:presentation_file,
accept: ~w(.pdf .ppt .pptx),
auto_upload: true,
max_entries: 1,
max_file_size: 15_000_000
)}
end
@impl true
def handle_event("validate", %{"event" => event_params}, socket) do
changeset =
socket.assigns.event
|> Events.change_event(event_params)
|> Map.put(:action, :validate)
{:noreply, socket |> assign(:changeset, changeset)}
end
@impl true
def handle_event("validate-file", _params, socket) do
{:noreply, socket}
end
@impl true
def handle_event("remove-file", %{"ref" => ref}, socket) do
{:noreply, cancel_upload(socket, :presentation_file, ref)}
end
@impl true
def handle_event("save", %{"event" => event_params}, socket) do
save_event(socket, socket.assigns.action, event_params)
end
@impl true
def handle_event(
"add-leader",
_params,
socket
) do
existing_leaders =
Map.get(socket.assigns.changeset.changes, :leaders, socket.assigns.event.leaders)
leaders =
existing_leaders
|> Enum.concat([
Events.change_activity_leader(%Events.ActivityLeader{temp_id: get_temp_id()})
])
changeset =
socket.assigns.changeset
|> Ecto.Changeset.put_assoc(:leaders, leaders)
{:noreply, assign(socket, changeset: changeset)}
end
@impl true
def handle_event(
"remove-leader",
%{"remove" => remove_id},
socket
) do
leaders =
socket.assigns.changeset.changes.leaders
|> Enum.reject(fn %{data: leader} ->
leader.temp_id == remove_id
end)
IO.inspect(leaders)
changeset =
socket.assigns.changeset
|> Ecto.Changeset.put_assoc(:leaders, leaders)
{:noreply, assign(socket, changeset: changeset)}
end
defp get_temp_id, do: :crypto.strong_rand_bytes(5) |> Base.url_encode64() |> binary_part(0, 5)
defp save_file(socket, %{"code" => code, "name" => name} = event_params, after_save) do
hash = :erlang.phash2("#{code}-#{name}")
static_path =
Path.join([
:code.priv_dir(:claper),
"static",
"uploads",
"#{hash}"
])
case uploaded_entries(socket, :presentation_file) do
{[_ | _], []} ->
[dest | _] =
consume_uploaded_entries(socket, :presentation_file, fn %{path: path}, entry ->
[ext | _] = MIME.extensions(entry.client_type)
dest =
Path.join([
static_path,
"original.#{ext}"
])
# The `static/uploads` directory must exist for `File.cp!/2` to work.
File.mkdir_p!(static_path)
File.cp!(path, dest)
{:ok, Routes.static_path(socket, "/uploads/#{hash}/#{Path.basename(dest)}")}
end)
[ext | _] = MIME.extensions(MIME.from_path(dest))
if !Map.has_key?(socket.assigns.event.presentation_file, :id) do
after_save.(
socket,
Map.put(event_params, "presentation_file", %{
"status" => "progress",
"presentation_state" => %{}
}),
hash,
ext
)
else
after_save.(
socket,
event_params,
hash,
ext
)
end
_ ->
after_save.(socket, event_params, nil, nil)
end
end
defp save_event(socket, :edit, event_params) do
save_file(socket, event_params, &edit_event/4)
end
defp save_event(socket, :new, event_params) do
save_file(socket, event_params, &create_event/4)
end
defp create_event(socket, event_params, hash, ext) do
IO.inspect(
event_params
|> Map.put("user_id", socket.assigns.current_user.id)
)
case Events.create_event(
event_params
|> Map.put("user_id", socket.assigns.current_user.id)
) do
{:ok, event} ->
with e <- Events.get_event!(event.uuid, [:presentation_file]) do
Task.Supervisor.async_nolink(Claper.TaskSupervisor, fn ->
Claper.Tasks.Converter.convert(
socket.assigns.current_user.id,
"original.#{ext}",
hash,
ext,
e.presentation_file.id
)
end)
end
{:noreply,
socket
|> put_flash(:info, gettext("Created successfully"))
|> push_redirect(to: socket.assigns.return_to)}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
defp edit_event(socket, event_params, hash, ext) do
case Events.update_event(
socket.assigns.event,
event_params
) do
{:ok, _event} ->
if !is_nil(hash) && !is_nil(ext) do
Task.Supervisor.async_nolink(Claper.TaskSupervisor, fn ->
Claper.Tasks.Converter.convert(
socket.assigns.current_user.id,
"original.#{ext}",
hash,
ext,
socket.assigns.event.presentation_file.id
)
end)
end
{:noreply,
socket
|> put_flash(:info, gettext("Updated successfully"))
|> push_redirect(to: socket.assigns.return_to)}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :changeset, changeset)}
end
end
def error_to_string(:too_large), do: gettext("Your file is too large")
def error_to_string(:not_accepted), do: gettext("You have selected an incorrect file type")
def error_to_string(:external_client_failure), do: gettext("Upload failed")
end

View File

@@ -0,0 +1,227 @@
<div>
<div class="border-b border-gray-200 py-4 flex flex-col sm:flex-row sm:items-center justify-between">
<div class="flex-1 min-w-0">
<h1 class="text-2xl font-medium leading-6 text-gray-900 sm:truncate">
<%= @page_title %>
</h1>
</div>
<div class="flex mt-4 space-x-5 sm:mt-0">
<%= if @uploads.presentation_file.entries |> Enum.at(0, %{}) |> Map.get(:progress, 0) >= 100 || Map.has_key?(@event.presentation_file, :id) do %>
<button type="submit" form="event-form" phx_disable_with="Loading..." class="w-full lg:w-auto px-6 text-white py-2 rounded-md tracking-wide font-bold focus:outline-none focus:shadow-outline bg-gradient-to-tl from-primary-500 to-secondary-500 bg-size-200 bg-pos-0 hover:bg-pos-100 transition-all duration-500">
<%= case @action do
:edit -> gettext("Save")
:new -> gettext("Create")
end %>
</button>
<% else %>
<div class="opacity-25 cursor-default w-full lg:w-auto px-6 text-white py-2 rounded-md tracking-wide font-bold focus:outline-none focus:shadow-outline bg-gradient-to-tl from-primary-500 to-secondary-500 bg-size-200 bg-pos-0">
<%= case @action do
:edit -> gettext("Save")
:new -> gettext("Create")
end %>
</div>
<% end %>
<%= if @action == :edit && NaiveDateTime.compare(NaiveDateTime.utc_now(), @event.expired_at) == :lt do %>
<%= link gettext("Delete"), to: "#", phx_click: "delete", phx_value_id: @event.uuid, data: [confirm: gettext("Are you sure?")], class: "w-full lg:w-auto px-6 text-center text-white py-2 rounded-md tracking-wide font-bold focus:outline-none focus:shadow-outline bg-gradient-to-tl from-supporting-red-600 to-supporting-red-400 bg-size-200 bg-pos-0 hover:bg-pos-100 transition-all duration-500" %>
<% end %>
</div>
</div>
<%= if Map.get(@event, :presentation_file) == nil || Map.get(@event.presentation_file, :id) == nil do %>
<div class="mt-12 mb-3">
<label class="block text-sm font-medium text-gray-700 mb-2"><%= gettext "Select your presentation" %></label>
<div class="max-w-lg flex flex-col justify-center items-center px-6 pt-5 pb-6 border-2 bg-white shadow-base border-gray-300 border-dashed rounded-md">
<%= if @uploads.presentation_file.entries |> Enum.at(0, %{}) |> Map.get(:progress, 0) < 100 do %>
<div class="space-y-1 text-center" phx-drop-target={@uploads.presentation_file.ref}>
<svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48" aria-hidden="true">
<path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
</svg>
<div class="flex text-sm text-gray-600">
<label class="relative cursor-pointer bg-white rounded-md font-medium text-primary-600">
<form id="file-form" phx-change="validate-file" phx-submit="save-file" phx-target={@myself}>
<span><%= gettext "Upload a file" %></span>
<%= live_file_input @uploads.presentation_file, class: "sr-only" %>
</form>
</label>
<p class="pl-1"><%= gettext "or drag and drop" %></p>
</div>
<p class="text-xs text-gray-500"><%= gettext "PDF, PPT, PPTX up to 15MB" %></p>
<%= for entry <- @uploads.presentation_file.entries do %>
<progress id="file" max="100" value={entry.progress}><%= entry.progress %></progress>
<%= for err <- upload_errors(@uploads.presentation_file, entry) do %>
<p class="text-red-500 text-sm px-4 py-2 border border-red-600 rounded-md my-3"><%= error_to_string(err) %></p>
<% end %>
<% end %>
</div>
<% else %>
<%= for entry <- @uploads.presentation_file.entries do %>
<div class="flex space-x-1">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-6 w-6 text-supporting-green-500"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M5 13l4 4L19 7"
/>
</svg>
<p class="text-gray-700"><%= gettext "Presentation uploaded" %></p>
</div>
<p class="text-xs text-gray-400"><%= entry.client_name %></p>
<p>
<a href="#" phx-click="remove-file" phx-value-ref={entry.ref} phx-target={@myself} class="text-red-500 text-sm"><%= gettext "Remove" %></a>
</p>
<% end %>
<% end %>
</div>
</div>
<% else %>
<div class="mt-12 mb-3">
<label class="block text-sm font-medium text-gray-700 mb-2"><%= gettext "Select your presentation" %></label>
<div class="max-w-lg flex flex-col justify-center items-center px-6 pt-5 pb-6 border-2 bg-white shadow-base border-gray-300 border-dashed rounded-md">
<%= if @uploads.presentation_file.entries |> Enum.at(0, %{}) |> Map.get(:progress, 0) < 100 do %>
<div class="flex space-x-1">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-6 w-6 text-supporting-green-500"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M5 13l4 4L19 7"
/>
</svg>
<p class="text-gray-700"><%= gettext "Presentation attached" %></p>
</div>
<div class="flex flex-col space-y-3 items-center">
<label class="text-primary-500 text-sm">
<form id="file-form" phx-change="validate-file" phx-submit="save-file" phx-target={@myself}>
<span><%= gettext "Change file" %></span>
<%= live_file_input @uploads.presentation_file, class: "sr-only" %>
</form>
</label>
<p class="text-supporting-red-500 text-sm italic text-center hidden"><%= gettext "Changing your file will remove all interaction elements like polls associated." %></p>
</div>
<% else %>
<div class="flex space-x-1">
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-6 w-6 text-supporting-green-500"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M5 13l4 4L19 7"
/>
</svg>
<p class="text-gray-700"><%= gettext "Presentation replaced" %></p>
</div>
<%= for entry <- @uploads.presentation_file.entries do %>
<p class="text-xs text-gray-400"><%= entry.client_name %></p>
<p>
<a href="#" phx-click="remove-file" phx-value-ref={entry.ref} phx-target={@myself} class="text-red-500 text-sm"><%= gettext "Remove" %></a>
</p>
<% end %>
<% end %>
<%= for entry <- @uploads.presentation_file.entries do %>
<%= for err <- upload_errors(@uploads.presentation_file, entry) do %>
<p class="text-red-500 text-sm px-4 py-2 border border-red-600 rounded-md my-3"><%= error_to_string(err) %></p>
<% end %>
<% end %>
</div>
</div>
<% end %>
<.form
let={f}
for={@changeset}
id="event-form"
phx-target={@myself}
phx-change="validate"
phx-submit="save">
<div class="relative">
<div class="my-3">
<ClaperWeb.Component.Input.text form={f} key={:name} name={gettext "Name of your presentation"} autofocus="true" required="true" />
</div>
<div class="my-3">
<ClaperWeb.Component.Input.code readonly={NaiveDateTime.compare(NaiveDateTime.utc_now(), @event.expired_at) == :gt} form={f} key={:code} name={gettext "Code"} required="true" />
</div>
<div class="my-3">
<ClaperWeb.Component.Input.date_range readonly={NaiveDateTime.compare(NaiveDateTime.utc_now(), @event.expired_at) == :gt} form={f} key={:date_range} name={gettext "When your presentation will be available ?"} required="true" start_date_field={:started_at} end_date_field={:expired_at} from={Date.add(Date.utc_today(), -1)} to={Date.add(Date.utc_today(), 90)} />
</div>
<%= if @action == :edit do %>
<div phx-hook="QRCode" id="qr" data-code={@event.code} data-get-url="true" data-height="340" data-width="340" phx-update="ignore" class="rounded-lg mx-auto bg-white w-64 h-64 p-12 items-center justify-center mb-14 hidden"></div>
<% end %>
</div>
<div class="mt-20 mb-3">
<span class="text-lg block font-medium text-gray-700"><%= gettext("Facilitators can present and manage interactions") %></span>
<button type="button" phx-click="add-leader" phx-target={@myself} class="rounded-md bg-primary-500 hover:bg-primary-600 transition flex items-center mt-3 md:w-max text-white py-7 px-3 text-sm max-h-0">
<svg class="text-white h-6 transform" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"
aria-hidden="true">
<path fill-rule="evenodd"
d="M10 5a1 1 0 011 1v3h3a1 1 0 110 2h-3v3a1 1 0 11-2 0v-3H6a1 1 0 110-2h3V6a1 1 0 011-1z"
clip-rule="evenodd" />
<span><%= gettext "Add facilitator" %></span>
</svg>
</button>
</div>
<%= inputs_for f, :leaders, fn l -> %>
<div class="flex items-center space-x-4 mt-2" id={l.data.temp_id || l.id } >
<img class="h-10 w-10 rounded-full" src={"https://www.gravatar.com/avatar/#{:crypto.hash(:md5, (l.data.email || "") |> String.downcase() |> String.trim() ) |> Base.encode16() |> String.downcase()}"} alt="">
<%= if is_nil(l.data.temp_id) do %>
<div class="relative">
<ClaperWeb.Component.Input.text form={l} readonly={true} placeholder={gettext("User email address")} key={:email} name="" />
</div>
<label phx-click={JS.hide(to: "##{l.data.temp_id || l.id}")} class="cursor-pointer md:ml-3 rounded-md bg-supporting-red-500 hover:bg-supporting-red-600 transition flex items-center mt-2 md:w-max text-white py-7 px-3 text-sm max-h-0">
<span><%= gettext "Remove" %></span>
<%= checkbox l, :delete, class: "hidden" %>
</label>
<% else %>
<div class="relative">
<ClaperWeb.Component.Input.text form={l} placeholder={gettext("User email address")} key={:email} name="" />
</div>
<%= hidden_input l, :temp_id %>
<%= hidden_input l, :event_id, value: @event.id %>
<button type="button" phx-click="remove-leader" phx-value-remove={l.data.temp_id} phx-target={@myself} class="md:ml-3 rounded-md bg-supporting-red-500 hover:bg-supporting-red-600 transition flex items-center mt-2 md:w-max text-white py-7 px-3 text-sm max-h-0">
<span><%= gettext "Remove" %></span>
</button>
<% end %>
</div>
<% end %>
</.form>
</div>

View File

@@ -0,0 +1,94 @@
defmodule ClaperWeb.EventLive.Index do
use ClaperWeb, :live_view
alias Claper.Events
alias Claper.Events.Event
on_mount(ClaperWeb.UserLiveAuth)
@impl true
def mount(_params, session, socket) do
with %{"locale" => locale} <- session do
Gettext.put_locale(ClaperWeb.Gettext, locale)
end
if connected?(socket) do
Phoenix.PubSub.subscribe(Claper.PubSub, "events:#{socket.assigns.current_user.id}")
end
socket =
socket
|> assign(:events, list_events(socket))
|> assign(:managed_events, list_managed_events(socket))
{:ok, socket, temporary_assigns: [events: []]}
end
@impl true
def handle_params(params, _url, socket) do
{:noreply, apply_action(socket, socket.assigns.live_action, params)}
end
@impl true
def handle_info({:presentation_file_process_done, presentation}, socket) do
event = Claper.Events.get_event!(presentation.event.uuid, [:presentation_file])
{:noreply,
socket |> update(:events, fn events -> [event | events] end) |> put_flash(:info, nil)}
end
@impl true
def handle_event("delete", %{"id" => id}, socket) do
event = Events.get_event!(id, [:presentation_file])
{:ok, _} = Events.delete_event(event)
Task.Supervisor.async_nolink(Claper.TaskSupervisor, fn ->
Claper.Tasks.Converter.clear(event.presentation_file.hash)
end)
{:noreply, redirect(socket, to: Routes.event_index_path(socket, :index))}
end
defp apply_action(socket, :edit, %{"id" => id}) do
event =
Events.get_user_event!(socket.assigns.current_user.id, id, [:presentation_file, :leaders])
if event.presentation_file.status == "fail" && event.presentation_file.hash do
Claper.Presentations.update_presentation_file(event.presentation_file, %{
"status" => "done"
})
end
{:ok, socket |> assign(:event, event)}
socket
|> assign(:page_title, gettext("Edit"))
|> assign(:event, event)
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, gettext("Create"))
|> assign(:event, %Event{
started_at: NaiveDateTime.utc_now(),
expired_at: NaiveDateTime.utc_now() |> NaiveDateTime.add(3600 * 2, :second),
code: Enum.random(1000..9999),
leaders: []
})
end
defp apply_action(socket, :index, _params) do
socket
|> assign(:page_title, gettext("Dashboard"))
|> assign(:event, nil)
end
defp list_events(socket) do
Events.list_events(socket.assigns.current_user.id, [:presentation_file])
end
defp list_managed_events(socket) do
Events.list_managed_events_by(socket.assigns.current_user.email, [:presentation_file])
end
end

View File

@@ -0,0 +1,64 @@
<div class="mx-3 max-w-7xl sm:mx-auto">
<%= if @live_action in [:new, :edit] do %>
<.live_component module={ClaperWeb.EventLive.FormComponent} id="event-create" event={@event} page_title={@page_title} action={@live_action} return_to={Routes.event_index_path(@socket, :index)} current_user={@current_user} />
<% else %>
<div class="border-b border-gray-200 py-4 flex items-center justify-between">
<div class="flex-1 min-w-0">
<h1 class="text-2xl font-medium leading-6 text-gray-900 sm:truncate">
<%= gettext("My presentations") %>
</h1>
</div>
<div class="flex mt-0">
<a data-phx-link="patch" data-phx-link-state="push" href={Routes.event_index_path(@socket, :new)}
class="relative inline-flex items-center px-5 py-2 text-lg font-medium rounded-md text-white bg-gradient-to-tl from-primary-500 to-secondary-500 bg-size-200 bg-pos-0 hover:bg-pos-100 transition-all duration-500">
<svg class="-ml-1 mr-1 h-5 w-5" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"
aria-hidden="true">
<path fill-rule="evenodd"
d="M10 5a1 1 0 011 1v3h3a1 1 0 110 2h-3v3a1 1 0 11-2 0v-3H6a1 1 0 110-2h3V6a1 1 0 011-1z"
clip-rule="evenodd" />
</svg>
<span>
<%= gettext("Create") %>
</span>
</a>
</div>
</div>
<div class="mt-10 relative">
<ul role="event-list" class="divide-y divide-gray-200" phx-update="append" id="events">
<% current_time = NaiveDateTime.utc_now() %>
<%= for event <- @events do %>
<.live_component module={ClaperWeb.EventLive.EventCardComponent} id={"event-#{event.uuid}"} event={event} current_time={current_time} />
<% end %>
</ul>
<%= if Enum.count(@events) == 0 do %>
<div class="w-full text-2xl text-black opacity-25 text-center">
<img src="/images/icons/arrow.svg" class="h-20 float-right mr-16 -mt-5" />
<p class="pt-12 clear-both"> <%= gettext("Create your first presentation") %></p>
</div>
<% end %>
</div>
<%= if length(@managed_events) > 0 do %>
<div class="border-b border-gray-200 py-4 flex items-center justify-between mt-12">
<div class="flex-1 min-w-0">
<h1 class="text-2xl font-medium leading-6 text-gray-900 sm:truncate">
<%= gettext("Invited presentations") %>
</h1>
</div>
</div>
<div class="mt-10 relative">
<ul role="managed-event-list" class="divide-y divide-gray-200" phx-update="replace">
<% current_time = NaiveDateTime.utc_now() %>
<%= for event <- @managed_events do %>
<.live_component module={ClaperWeb.EventLive.EventCardComponent} id={"managed-event-#{event.uuid}"} is_leader={true} event={event} current_time={current_time} />
<% end %>
</ul>
</div>
<% end %>
<% end %>
</div>

View File

@@ -0,0 +1,45 @@
defmodule ClaperWeb.EventLive.Join do
use ClaperWeb, :live_view
on_mount(ClaperWeb.AttendeeLiveAuth)
@impl true
def mount(params, session, socket) do
with %{"locale" => locale} <- session do
Gettext.put_locale(ClaperWeb.Gettext, locale)
end
if params["disconnected_from"] do
try do
event = Claper.Events.get_event!(params["disconnected_from"])
{:ok, socket |> assign(:last_event, event)}
rescue
_ -> {:ok, socket |> assign(:last_event, nil)}
end
else
{:ok, socket |> assign(:last_event, nil)}
end
end
@impl true
def handle_params(params, _url, socket) do
{:noreply, apply_action(socket, socket.assigns.live_action, params)}
end
@impl true
def handle_event("join", %{"event" => %{"code" => code}}, socket) do
{:noreply,
socket |> push_redirect(to: Routes.event_show_path(socket, :show, String.downcase(code)))}
end
defp apply_action(socket, :join, _params) do
socket
|> redirect(to: "/")
end
defp apply_action(socket, :index, _params) do
socket
|> assign(:page_title, gettext("Join"))
|> assign(:event, nil)
end
end

View File

@@ -0,0 +1,70 @@
<style>
body {
background: linear-gradient(-45deg, #2C033A, #21033A, #053138, #053138);
background-size: 400% 400%;
animation: gradient 15s ease infinite;
}
</style>
<div class="lg:overflow-hidden">
<div x-data="{open: false}" class="w-full h-24 py-4 text-right md:px-5 relative z-20" phx-update="ignore">
<div x-show="open" x-transition class="absolute h-24 bg-white w-full top-0 md:hidden px-5 py-3 flex flex-col items-center justify-center space-y-2" @click.away="open = false">
<a href="https://get.claper.co/" class="text-sm font-semibold text-black"><%= gettext("About") %></a>
<%= if @current_user do %>
<%= live_patch gettext("Dashboard"), to: Routes.event_index_path(@socket, :index), class: "relative inline-flex items-center px-4 py-1 text-base font-sm rounded-md text-white bg-gradient-to-tl from-primary-500 to-secondary-500 bg-size-200 bg-pos-0 hover:bg-pos-100 transition-all duration-500" %>
<% else %>
<%= live_patch gettext("Login"), to: Routes.user_session_path(@socket, :new), class: "relative inline-flex items-center px-4 py-1 text-base font-sm rounded-md text-white bg-gradient-to-tl from-primary-500 to-secondary-500 bg-size-200 bg-pos-0 hover:bg-pos-100 transition-all duration-500" %>
<% end %>
</div>
<button @click="open = true" class="md:hidden">
<img src="/images/icons/menu-outline.svg" class="h-9" />
</button>
<div class="hidden md:block">
<a href="https://get.claper.co/" class="text-sm text-white font-semibold mr-3"><%= gettext("About") %></a>
<%= if @current_user do %>
<%= live_patch gettext("Dashboard"), to: Routes.event_index_path(@socket, :index), class: "relative inline-flex items-center px-4 py-1 text-base font-sm rounded-md text-white bg-gradient-to-tl from-primary-500 to-secondary-500 bg-size-200 bg-pos-0 hover:bg-pos-100 transition-all duration-500" %>
<% else %>
<%= live_patch gettext("Login"), to: Routes.user_session_path(@socket, :new), class: "relative inline-flex items-center px-4 py-1 text-base font-sm rounded-md text-white bg-gradient-to-tl from-primary-500 to-secondary-500 bg-size-200 bg-pos-0 hover:bg-pos-100 transition-all duration-500" %>
<% end %>
</div>
</div>
<div class="px-5 lg:w-1/3 lg:mx-auto">
<div class="mt-10 ">
<img src="/images/logo.svg" class="h-12 mx-auto mb-16" />
</div>
<%= if @last_event do %>
<%= live_patch to: Routes.event_show_path(@socket, :show, @last_event.code) do %>
<div class="rounded-md bg-gray-600 p-4 mb-8">
<div class="flex justify-center items-center">
<p class="text-sm text-white">
<%= gettext "Return to your last presentation" %> (#<span class="uppercase"><%= @last_event.code %></span>)
</p>
<p class="text-base ml-3 mt-1">
<a href="#" class="whitespace-nowrap font-medium text-white"><span aria-hidden="true">&rarr;</span></a>
</p>
</div>
</div>
<% end %>
<% end %>
<%= form_for :event, Routes.event_join_path(@socket, :join), ["phx-submit": "join", "phx-hook": "JoinEvent", id: "form"], fn f -> %>
<div class="relative">
<%= text_input f, :code, required: true, autofocus: true, id: "input", class: "transition-all bg-transparent tracking-widest w-full uppercase text-white text-2xl px-3 border-b border-gray-200 focus:border-b-2 pt-5 pl-12 pb-3 outline-none" %>
<img class="icon absolute top-5 left-2 transition-all duration-100" src="/images/icons/hashtag-white.svg" alt="code">
</div>
<div class="mt-10">
<button type="submit" id="submit" class="w-full flex justify-center text-white p-4 rounded-full tracking-wide font-bold outline-none focus:shadow-outline shadow-lg bg-gradient-to-tl from-primary-500 to-secondary-500 bg-size-200 bg-pos-0 hover:bg-pos-100 transition-all duration-500">
<%= gettext "Join" %>
</button>
<img src="/images/loading.gif" id="loading" class="hidden h-12 mx-auto" />
</div>
<% end %>
</div>
</div>

View File

@@ -0,0 +1,343 @@
defmodule ClaperWeb.EventLive.Manage do
use ClaperWeb, :live_view
alias ClaperWeb.Presence
alias Claper.Polls
@impl true
def mount(%{"code" => code}, session, socket) do
with %{"locale" => locale} <- session do
Gettext.put_locale(ClaperWeb.Gettext, locale)
end
event =
Claper.Events.get_event_with_code(code, [
:user,
presentation_file: [:polls, :presentation_state]
])
if is_nil(event) || not is_leader(socket, event) do
{:ok,
socket
|> put_flash(:error, gettext("Presentation doesn't exist"))
|> redirect(to: "/")}
else
if connected?(socket) do
Claper.Events.Event.subscribe(event.uuid)
# Claper.Presentations.subscribe(event.presentation_file.id)
Presence.track(
self(),
"event:#{event.uuid}",
socket.assigns.current_user.id,
%{}
)
end
socket =
socket
|> assign(:attendees_nb, 1)
|> assign(:event, event)
|> assign(:state, event.presentation_file.presentation_state)
|> assign(:posts, list_posts(socket, event.uuid))
|> assign(:polls, list_polls(socket, event.presentation_file.id))
|> assign(:create, nil)
|> assign(:create_action, :new)
|> push_event("page-manage", %{
current_page: event.presentation_file.presentation_state.position,
timeout: 500
})
|> poll_at_position(false)
{:ok, socket, temporary_assigns: [posts: []]}
end
end
defp is_leader(%{assigns: %{current_user: current_user}} = _socket, event) do
Claper.Events.is_leaded_by(current_user.email, event) || event.user.id == current_user.id
end
defp is_leader(_socket, _event), do: false
@impl true
def handle_info(%{event: "presence_diff"}, %{assigns: %{event: event}} = socket) do
attendees = Presence.list("event:#{event.uuid}")
{:noreply, assign(socket, :attendees_nb, Enum.count(attendees))}
end
@impl true
def handle_info({:post_created, post}, socket) do
{:noreply,
socket |> update(:posts, fn posts -> [post | posts] end) |> push_event("scroll", %{})}
end
@impl true
def handle_info({:post_updated, post}, socket) do
{:noreply, socket |> update(:posts, fn posts -> [post | posts] end)}
end
@impl true
def handle_info({:reaction_added, post}, socket) do
{:noreply, socket |> update(:posts, fn posts -> [post | posts] end)}
end
@impl true
def handle_info({:reaction_removed, post}, socket) do
{:noreply, socket |> update(:posts, fn posts -> [post | posts] end)}
end
@impl true
def handle_info({:post_deleted, post}, socket) do
{:noreply, socket |> update(:posts, fn posts -> [post | posts] end)}
end
@impl true
def handle_info({:poll_updated, poll}, socket) do
{:noreply,
socket
|> update(:current_poll, fn _current_poll -> poll end)}
end
@impl true
def handle_info(
{:current_poll, poll},
socket
) do
{:noreply, socket |> assign(:current_poll, poll)}
end
@impl true
def handle_info(_, socket) do
{:noreply, socket}
end
@impl true
def handle_event(
"current-page",
%{"page" => page},
%{assigns: %{state: state}} = socket
) do
page = String.to_integer(page)
{:ok, new_state} =
Claper.Presentations.update_presentation_state(
state,
%{
:position => page
}
)
Phoenix.PubSub.broadcast(
Claper.PubSub,
"event:#{socket.assigns.event.uuid}",
{:page_changed, page}
)
{:noreply,
socket
|> assign(:state, new_state)
|> poll_at_position}
end
def handle_event("poll-set-default", %{"id" => id}, socket) do
Polls.set_default(
id,
socket.assigns.event.presentation_file.id,
socket.assigns.state.position
)
poll = Polls.get_poll!(id)
Phoenix.PubSub.broadcast(
Claper.PubSub,
"event:#{socket.assigns.event.uuid}",
{:current_poll, poll}
)
{:noreply,
socket
|> assign(:polls, list_polls(socket, socket.assigns.event.presentation_file.id))}
end
@impl true
def handle_event(
"ban",
%{"attendee-identifier" => attendee_identifier},
%{assigns: %{event: event}} = socket
) do
Claper.Posts.delete_all_posts(:attendee_identifier, attendee_identifier, event)
ban(attendee_identifier, socket)
end
@impl true
def handle_event(
"ban",
%{"user-id" => user_id},
%{assigns: %{event: event}} = socket
) do
Claper.Posts.delete_all_posts(:user_id, user_id, event)
ban(String.to_integer(user_id), socket)
end
@impl true
def handle_event(
"checked",
%{"key" => "chat_visible", "value" => value},
%{assigns: %{state: state}} = socket
) do
{:ok, new_state} =
Claper.Presentations.update_presentation_state(
state,
%{
:chat_visible => value
}
)
{:noreply, socket |> assign(:state, new_state)}
end
@impl true
def handle_event(
"checked",
%{"key" => "poll_visible", "value" => value},
%{assigns: %{state: state}} = socket
) do
{:ok, new_state} =
Claper.Presentations.update_presentation_state(
state,
%{
:poll_visible => value
}
)
{:noreply, socket |> assign(:state, new_state)}
end
@impl true
def handle_event(
"checked",
%{"key" => "join_screen_visible", "value" => value},
%{assigns: %{state: state}} = socket
) do
{:ok, new_state} =
Claper.Presentations.update_presentation_state(
state,
%{
:join_screen_visible => value
}
)
{:noreply, socket |> assign(:state, new_state)}
end
@impl true
def handle_event("delete", %{"event-id" => event_id, "id" => id}, socket) do
post = Claper.Posts.get_post!(id, [:event])
{:ok, _} = Claper.Posts.delete_post(post)
{:noreply, assign(socket, :posts, list_posts(socket, event_id))}
end
@impl true
def handle_event("maybe-redirect", _params, socket) do
if socket.assigns.create != nil do
{:noreply,
socket
|> push_redirect(to: Routes.event_manage_path(socket, :show, socket.assigns.event.code))}
else
{:noreply, socket}
end
end
@impl true
def handle_event("delete-poll", %{"id" => id}, socket) do
poll = Polls.get_poll!(id)
{:ok, _} = Polls.delete_poll(socket.assigns.event.uuid, poll)
{:noreply,
socket
|> assign(:polls, list_polls(socket, socket.assigns.event.presentation_file.id))}
end
@impl true
def handle_params(params, _url, socket) do
{:noreply, apply_action(socket, socket.assigns.live_action, params)}
end
def toggle_add_modal(js \\ %JS{}) do
js
|> JS.toggle(
to: "#add-modal",
out: "animate__animated animate__fadeOut",
in: "animate__animated animate__fadeIn"
)
|> JS.push("maybe-redirect", target: "#add-modal")
end
defp apply_action(socket, :show, _params) do
socket
end
defp apply_action(socket, :add_poll, _params) do
socket
|> assign(:create, "poll")
|> assign(:poll, %Polls.Poll{
poll_opts: [%Polls.PollOpt{id: 0}, %Polls.PollOpt{id: 1}]
})
end
defp apply_action(socket, :edit_poll, %{"id" => id}) do
poll = Polls.get_poll!(id)
socket
|> assign(:create, "poll")
|> assign(:create_action, :edit)
|> assign(:poll, poll)
end
defp poll_at_position(
%{assigns: %{event: event, state: state}} = socket,
broadcast \\ true
) do
with poll <-
Claper.Polls.get_poll_current_position(
event.presentation_file.id,
state.position
) do
if broadcast do
Phoenix.PubSub.broadcast(
Claper.PubSub,
"event:#{event.uuid}",
{:current_poll, poll}
)
end
socket |> assign(:current_poll, poll)
end
end
defp ban(user, %{assigns: %{event: event, state: state}} = socket) do
{:ok, new_state} =
Claper.Presentations.update_presentation_state(state, %{
"banned" => state.banned ++ ["#{user}"]
})
Phoenix.PubSub.broadcast(
Claper.PubSub,
"event:#{event.uuid}",
{:banned, user}
)
{:noreply, socket |> assign(:state, new_state)}
end
defp list_posts(_socket, event_id) do
Claper.Posts.list_posts(event_id, [:event, :reactions])
end
defp list_polls(_socket, presentation_file_id) do
Claper.Polls.list_polls(presentation_file_id)
end
end

View File

@@ -0,0 +1,255 @@
<div id="manager" class="h-screen max-h-screen flex flex-col" x-data={"{date: moment.utc('#{@event.expired_at}').local().format('lll')}"} phx-hook="Manager" data-max-page={@event.presentation_file.length} data-current-page={@state.position}>
<div class="md:flex md:items-center md:justify-between px-6 pb-4 pt-2 h-12 md:h-20 shadow-base absolute top-0 left-0 w-full z-20 bg-white">
<div class="flex-1 min-w-0">
<div class="flex space-x-2">
<a data-phx-link="patch" data-phx-link-state="push" href={Routes.event_index_path(@socket, :index)} class="md:px-3 pt-0.5 md:pt-1.5 rounded-md hover:bg-gray-200">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
</svg>
</a>
<h2 class="text-2xl font-bold leading-7 text-gray-900 sm:text-3xl sm:truncate"><%= @event.name %></h2>
</div>
<div class="hidden mt-1 md:flex flex-col sm:flex-row sm:flex-wrap sm:mt-0 sm:space-x-6">
<div class="mt-2 flex items-center text-sm text-gray-500">
<svg xmlns="http://www.w3.org/2000/svg" class="flex-shrink-0 mr-1.5 h-5 w-5 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14" />
</svg>
<%= @event.code %>
</div>
<div class="hidden mt-2 md:flex items-center text-sm text-gray-500">
<svg xmlns="http://www.w3.org/2000/svg" class="flex-shrink-0 mr-1.5 h-5 w-5 text-gray-400" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd" />
</svg>
<%= @attendees_nb %>
</div>
<div class="hidden mt-2 md:flex items-center text-sm text-gray-500">
<svg class="flex-shrink-0 mr-1.5 h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fill-rule="evenodd" d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z" clip-rule="evenodd" />
</svg>
<%= gettext "Finish on" %> <span class="ml-1" x-text="date"></span>
</div>
</div>
</div>
<div class="hidden mt-5 md:flex lg:mt-0 lg:ml-4">
<span class="md:ml-3">
<span class="italic text-gray-400 text-sm mr-5"><%= raw(gettext "Press <strong>F</strong> in the presentation window to enable fullscreen" ) %></span>
<button phx-hook="OpenPresenter" id={"openPresenter-#{@event.uuid}"} data-url={Routes.event_presenter_url(@socket, :show, @event.code)} type="button" class="inline-flex items-center px-5 py-4 border border-transparent rounded-md shadow-sm text-base font-medium text-white bg-gradient-to-tl from-primary-500 to-secondary-500 bg-size-200 bg-pos-0 hover:bg-pos-100 transition-all duration-500">
<svg xmlns="http://www.w3.org/2000/svg" class="-ml-1 mr-2 h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z" />
</svg>
<%= gettext "Start" %>
</button>
</span>
</div>
</div>
<div id="add-modal" class={"#{if !@create, do: 'hidden'} fixed z-30 inset-0 overflow-y-auto p-4 sm:p-6 md:p-24 transform transition-all duration-150"} role="dialog" aria-modal="true">
<div phx-click={toggle_add_modal()} class="fixed inset-0 bg-gray-800 bg-opacity-75 transition-opacity w-full h-full" aria-hidden="true"></div>
<div class="mx-auto max-w-xl transform divide-y divide-gray-100 overflow-hidden rounded-xl bg-white shadow-2xl ring-1 ring-black ring-opacity-5 transition-all">
<button phx-click={toggle_add_modal()} class="absolute right-0 top-0">
<svg class="text-gray-500 h-9 transform rotate-45" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor"
aria-hidden="true">
<path fill-rule="evenodd"
d="M10 5a1 1 0 011 1v3h3a1 1 0 110 2h-3v3a1 1 0 11-2 0v-3H6a1 1 0 110-2h3V6a1 1 0 011-1z"
clip-rule="evenodd" />
</svg>
</button>
<div id="modal-content" class="bg-gray-100">
<%= if @create == nil do %>
<ul class="scroll-py-3 overflow-y-auto p-3" id="options" role="listbox">
<li id="option-1" role="option" tabindex="-1">
<a data-phx-link="patch" data-phx-link-state="push" href={Routes.event_manage_path(@socket, :add_poll, @event.code)} class="group flex select-none rounded-xl p-3 w-full hover:bg-gray-200 cursor-pointer">
<div class="flex h-12 w-12 flex-none text-white items-center justify-center rounded-lg bg-gradient-to-br from-primary-500 to-secondary-500">
<svg xmlns="http://www.w3.org/2000/svg" class="h-9 w-9" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M16 8v8m-4-5v5m-4-2v2m-2 4h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
</div>
<div class="ml-4 flex-auto text-left">
<p class="font-medium text-gray-700"><%= gettext("Poll") %></p>
<p class="text-gray-500"><%= gettext("Add poll to know opinion of your public.") %></p>
</div>
</a>
</li>
</ul>
<% end %>
<%= if @create == "poll" do %>
<div class="scroll-py-3 overflow-y-auto bg-gray-100 p-3">
<p class="text-xl font-bold"><%= case @create_action do
:new -> gettext("New poll")
:edit -> gettext("Edit poll") end %></p>
<.live_component module={ClaperWeb.PollLive.FormComponent} id="poll-create" event_uuid={@event.uuid} presentation_file={@event.presentation_file} poll={@poll} live_action={@create_action} position={@state.position} return_to={Routes.event_manage_path(@socket, :show, @event.code)} />
</div>
<% end %>
</div>
</div>
</div>
<div class="grid grid-cols-1 md:grid-cols-3 grid-rows-2 md:grid-rows-1 w-full h-screen pt-12 md:pt-20">
<div class="bg-gray-100 pb-10 md:col-span-2 overflow-y-auto" >
<div class="flex flex-col justify-center items-center text-center">
<%= for index <- 0..@event.presentation_file.length-1 do %>
<%= if @state.position == index && @state.position > 0 do %>
<button phx-click="current-page" phx-value-page={index-1} class="w-12 h-12 float-left ml-5 focus:outline-none">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M5 15l7-7 7 7" />
</svg>
</button>
<% end %>
<div class={"#{if @state.position == index, do: 'shadow-xl bg-white', else: 'opacity-50 bg-gray-100'} transition-all pb-5"} id={"slide-preview-#{index}"}>
<button phx-click="current-page" phx-value-page={index} class="py-4 focus:outline-none">
<%= if System.get_env("PRESENTATION_STORAGE") == "local" do %>
<img class="w-1/3 mx-auto" src={"/uploads/#{@event.presentation_file.hash}/#{index+1}.jpg"} />
<% else %>
<img class="w-1/3 mx-auto" src={"https://#{System.get_env("AWS_PRES_BUCKET")}.s3.#{System.get_env("AWS_REGION")}.amazonaws.com/presentations/#{@event.presentation_file.hash}/#{index+1}.jpg"} />
<% end %>
</button>
<div class="flex flex-col space-y-3 w-full lg:w-1/2 mx-auto justify-start items-center">
<%= for poll <- Enum.filter(@polls, fn poll -> poll.position == index end) do %>
<div class="flex space-x-2 items-center">
<div class="flex h-10 w-10 flex-none text-white items-center justify-center rounded-lg bg-gradient-to-br from-primary-500 to-secondary-500">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M16 8v8m-4-5v5m-4-2v2m-2 4h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
</div>
<div class="flex space-x-2">
<span><span class="font-semibold"><%= gettext "Poll" %></span>: <%= poll.title %> </span>
<%= if @state.position == index do %>
<%= if poll.enabled do %>
<span class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-supporting-green-100 text-supporting-green-800">
<svg style="--animate-duration: 10s;" class="mr-1.5 h-2 w-2 text-supporting-green-400 animate__animated animate__flash animate__infinite" fill="currentColor" viewBox="0 0 8 8">
<circle cx="4" cy="4" r="3" />
</svg>
<%= gettext "Active" %>
</span>
<% else %>
<button phx-click="poll-set-default" phx-value-id={poll.id} class="inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-primary-100 text-primary-800"> <%= gettext("Set active") %> </button>
<% end %>
<a data-phx-link="patch" data-phx-link-state="push" href={Routes.event_manage_path(@socket, :edit_poll, @event.code, poll.id)} class="text-xs text-primary-500">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</a>
<% end %>
</div>
</div>
<div class="h-10 border border-gray-300"></div>
<% end %>
</div>
<button class="underline" phx-click={toggle_add_modal()}><%= gettext "Add interaction" %></button>
</div>
<%= if @state.position == index && @state.position < @event.presentation_file.length - 1 do %>
<button phx-click="current-page" phx-value-page={index+1} class="w-12 h-12 float-left ml-5 focus:outline-none">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M19 9l-7 7-7-7" />
</svg>
</button>
<% end %>
<% end %>
</div>
</div>
<div class="grid grid-cols-1 grid-rows-2 md:grid-rows-3" >
<div class="bg-gray-200 py-5 md:row-span-2">
<%= if Enum.count(@posts) == 0 do %>
<div class="text-center h-full flex flex-col space-y-5 items-center justify-center text-gray-400">
<svg xmlns="http://www.w3.org/2000/svg" class="h-36 w-36" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M17 8h2a2 2 0 012 2v6a2 2 0 01-2 2h-2v4l-4-4H9a1.994 1.994 0 01-1.414-.586m0 0L11 14h4a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2v4l.586-.586z" />
</svg>
<p class="text-lg"><%= gettext "Messages from attendees will appear here." %></p>
</div>
<% end %>
<div id="post-list" class={"overflow-y-auto #{if Enum.count(@posts) > 0, do: 'max-h-full'} pb-5 px-5"} phx-update="append" data-posts-nb={Enum.count(@posts)} phx-hook="ScrollIntoDiv" data-target="#post-list">
<%= for post <- @posts do %>
<div class={if post.__meta__.state == :deleted, do: "hidden"} id={"#{post.id}-post"}>
<div class="px-4 pb-2 pt-3 rounded-b-lg rounded-tr-lg bg-white relative shadow-md text-black break-all mt-4">
<div class="float-right mr-1">
<%= if post.attendee_identifier do %>
<span class="text-red-500"><%= link gettext("Ban"), to: "#", phx_click: "ban", phx_value_attendee_identifier: post.attendee_identifier, data: [confirm: gettext("Blocking this user will delete all his messages and he will not be able to join again, confirm ?")] %></span> /
<% else %>
<span class="text-red-500"><%= link gettext("Ban"), to: "#", phx_click: "ban", phx_value_user_id: post.user_id, data: [confirm: gettext("Blocking this user will delete all his messages and he will not be able to join again, confirm ?")] %></span> /
<% end %>
<span class="text-red-500"><%= link gettext("Delete"), to: "#", phx_click: "delete", phx_value_id: post.uuid, phx_value_event_id: @event.uuid %></span>
</div>
<div class="flex space-x-3 items-center">
<%= if post.attendee_identifier do %>
<img class="h-8 w-8" src={"https://avatars.dicebear.com/api/identicon/#{post.attendee_identifier}.svg"} />
<% else %>
<img class="h-8 w-8" src={"https://avatars.dicebear.com/api/identicon/#{post.user_id}.svg"} />
<% end %>
<p class="text-xl"><%= post.body %></p>
</div>
<%= if post.like_count > 0 || post.love_count > 0 || post.lol_count > 0 do %>
<div class="flex h-6 space-x-2 text-base text-gray-500 pb-3 items-center mt-5">
<div class="flex items-center">
<%= if post.like_count > 0 do %>
<img src="/images/icons/thumb.svg" class="h-4" />
<span class="ml-1"><%= post.like_count %></span>
<% end %>
</div>
<div class="flex items-center">
<%= if post.love_count > 0 do %>
<img src="/images/icons/heart.svg" class="h-4" />
<span class="ml-1"><%= post.love_count %></span>
<% end %>
</div>
<div class="flex items-center">
<%= if post.lol_count > 0 do %>
<img src="/images/icons/laugh.svg" class="h-4" />
<span class="ml-1"><%= post.lol_count %></span>
<% end %>
</div>
</div>
<% end %>
</div>
</div>
<% end %>
</div>
</div>
<div class="w-full shadow-lg">
<div class="px-5 py-3">
<span class="font-semibold text-lg"><%= gettext "On screen settings" %></span>
<div class="flex space-x-2 items-center mt-3">
<ClaperWeb.Component.Input.check key={:join_screen_visible} checked={@state.join_screen_visible} />
<span><%= gettext "Instructions" %></span>
</div>
<div class="flex space-x-2 items-center mt-3">
<ClaperWeb.Component.Input.check key={:chat_visible} checked={@state.chat_visible} />
<span><%= gettext "Messages" %></span>
</div>
<div class={"#{if !@current_poll, do: 'opacity-50'} flex space-x-2 items-center mt-3"}>
<ClaperWeb.Component.Input.check key={:poll_visible} disabled={!@current_poll} checked={@state.poll_visible} />
<span><%= gettext "Active poll results" %></span>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@@ -0,0 +1,91 @@
defmodule ClaperWeb.EventLive.PollComponent do
use ClaperWeb, :live_component
@impl true
def render(assigns) do
~H"""
<div>
<div id="collapsed-poll" class="bg-black py-3 px-6 text-black shadow-lg mx-auto rounded-full w-max hidden">
<div class="block w-full h-full cursor-pointer" phx-click={toggle_poll()} phx-target={@myself}>
<div class="text-white flex space-x-2 items-center">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M16 8v8m-4-5v5m-4-2v2m-2 4h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<span class="font-bold"><%= gettext "See current poll" %></span>
</div>
</div>
</div>
<div id="extended-poll" class="bg-black w-full py-3 px-6 text-black shadow-lg rounded-md">
<div class="block w-full h-full cursor-pointer" phx-click={toggle_poll()} phx-target={@myself}>
<div id="poll-pane" class="float-right mt-2">
<svg xmlns="http://www.w3.org/2000/svg" class="h-8 w-8 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
</svg>
</div>
<p class="text-xs text-gray-500 my-1"><%= gettext "Current poll" %></p>
<p class="text-white text-lg font-semibold mb-4"> <%= @poll.title %> </p>
</div>
<div>
<div class="flex flex-col space-y-3">
<%= if (length @poll.poll_opts) > 0 do %>
<%= for {opt, idx} <- Enum.with_index(@poll.poll_opts) do %>
<%= if ! is_nil(@current_poll_vote) do %>
<button class="bg-gray-500 px-3 py-2 rounded-full flex justify-between items-center relative text-white">
<div style={"width: #{opt.percentage}%;"} class={"bg-gradient-to-r from-primary-500 to-secondary-500 h-full absolute left-0 transition-all rounded-l-full #{if opt.percentage == "100", do: 'rounded-r-full'}"}></div>
<div class="flex space-x-3 z-10 text-left">
<%= if @current_poll_vote.poll_opt_id == opt.id do %>
<span class="h-5 w-5 mt-0.5 rounded-full point-select bg-white"></span>
<% else %>
<span class="h-5 w-5 mt-0.5 rounded-full point-select border-2 border-white"></span>
<% end %>
<span class="flex-1"><%= opt.content %></span>
</div>
<span class="text-sm z-10"><%= opt.percentage %>% (<%= opt.vote_count %>)</span>
</button>
<% else %>
<button id={"poll-opt-#{idx}"} phx-click="select-poll-opt" phx-value-opt={idx} class="bg-gray-500 px-3 py-2 rounded-full flex justify-between items-center relative text-white">
<div style={"width: #{opt.percentage}%;"} class={"bg-gradient-to-r from-primary-500 to-secondary-500 h-full absolute left-0 transition-all rounded-l-full #{if opt.percentage == "100", do: 'rounded-r-full'}"}></div>
<div class="flex space-x-3 z-10 text-left">
<%= if @selected_poll_opt == "#{idx}" do %>
<span class="h-5 w-5 mt-0.5 rounded-full point-select bg-white"></span>
<% else %>
<span class="h-5 w-5 mt-0.5 rounded-full point-select border-2 border-white"></span>
<% end %>
<span class="flex-1"><%= opt.content %></span>
</div>
<span class="text-sm z-10"><%= opt.percentage %>% (<%= opt.vote_count %>)</span>
</button>
<% end %>
<% end %>
<% end %>
</div>
<%= if ! is_nil(@current_poll_vote) do %>
<button class="px-3 py-2 text-white font-semibold bg-gray-500 rounded-md my-5 cursor-default"><%= gettext "Vote" %></button>
<% else %>
<button phx-click="vote" phx-value-opt={@selected_poll_opt} phx-disable-with="..." class="px-3 py-2 text-white font-semibold bg-primary-500 hover:bg-primary-600 rounded-md my-5"><%= gettext "Vote" %></button>
<% end %>
</div>
</div>
</div>
"""
end
def toggle_poll(js \\ %JS{}) do
js
|> JS.toggle(
out: "animate__animated animate__zoomOut",
in: "animate__animated animate__zoomIn",
to: "#collapsed-poll",
time: 50
)
|> JS.toggle(
out: "animate__animated animate__zoomOut",
in: "animate__animated animate__zoomIn",
to: "#extended-poll"
)
end
end

View File

@@ -0,0 +1,120 @@
defmodule ClaperWeb.EventLive.PostComponent do
use ClaperWeb, :live_component
def render(assigns) do
~H"""
<div id={"post-#{@post.uuid}"} class={if @post.__meta__.state == :deleted, do: "hidden"} >
<%= if @post.attendee_identifier == @attendee_identifier || (not is_nil(@current_user) && @post.user_id == @current_user.id) do %>
<div class={"px-4 pt-3 pb-8 rounded-b-lg rounded-tl-lg bg-gray-700 text-white relative z-0 break-all"}>
<button phx-click={JS.toggle(to: "#post-menu-#{@post.id}",out: "animate__animated animate__fadeOut", in: "animate__animated animate__fadeIn")} phx-click-away={JS.hide(to: "#post-menu-#{@post.id}", transition: "animate__animated animate__fadeOut")} class="float-right mr-1">
<img src="/images/icons/ellipsis-horizontal-white.svg" class="h-5" />
</button>
<div id={"post-menu-#{@post.id}"} class="hidden absolute right-4 top-7 bg-white rounded-lg px-5 py-2">
<span class="text-red-500"><%= link gettext("Delete"), to: "#", phx_click: "delete", phx_value_id: @post.uuid, phx_value_event_id: @event.uuid, data: [confirm: gettext("Are you sure?")] %></span>
</div>
<p><%= @post.body %></p>
<div class="flex h-6 text-sm float-right text-white space-x-2">
<%= if @post.like_count > 0 do %>
<div class="flex px-1 items-center">
<img src="/images/icons/thumb.svg" class="h-4" />
<span class="ml-1 text-white"><%= @post.like_count %></span>
</div>
<% end %>
<%= if @post.love_count > 0 do %>
<div class="flex px-1 items-center">
<img src="/images/icons/heart.svg" class="h-4" />
<span class="ml-1 text-white"><%= @post.love_count %></span>
</div>
<% end %>
<%= if @post.lol_count > 0 do %>
<div class="flex px-1 items-center">
<img src="/images/icons/laugh.svg" class="h-4" />
<span class="ml-1 text-white"><%= @post.lol_count %></span>
</div>
<% end %>
</div>
</div>
<% else %>
<div class={"px-4 pt-3 pb-8 rounded-b-lg rounded-tr-lg bg-white text-black relative z-0 break-all"}>
<%= if is_a_leader(@post, @event, @leaders) do %>
<div class="inline-flex items-center space-x-1 justify-center px-3 py-0.5 rounded-full text-xs font-medium bg-supporting-yellow-100 text-supporting-yellow-800 mb-2">
<img src="/images/icons/star.svg" class="h-3" />
<span><%= gettext "Host" %></span>
</div>
<% end %>
<%= if @is_leader do %>
<button phx-click={JS.toggle(to: "#post-menu-#{@post.id}",out: "animate__animated animate__fadeOut", in: "animate__animated animate__fadeIn")} phx-click-away={JS.hide(to: "#post-menu-#{@post.id}", transition: "animate__animated animate__fadeOut")} class="float-right mr-1">
<img src="/images/icons/ellipsis-horizontal.svg" class="h-5" />
</button>
<div id={"post-menu-#{@post.id}"} class="hidden absolute right-4 top-7 bg-gray-900 rounded-lg px-5 py-2">
<span class="text-red-500"><%= link gettext("Delete"), to: "#", phx_click: "delete", phx_value_id: @post.uuid, phx_value_event_id: @event.uuid, data: [confirm: gettext("Are you sure?")] %></span>
</div>
<% end %>
<p><%= @post.body %></p>
<div class="flex h-6 text-xs float-right space-x-2">
<%= if not Enum.member?(@liked_posts, @post.id) do %>
<button phx-click="react" phx-value-type="👍" phx-value-post-id={@post.uuid} class="flex rounded-full px-3 py-1 border border-gray-300 bg-white items-center">
<img src="/images/icons/thumb.svg" class="h-4" />
<%= if @post.like_count > 0 do %>
<span class="ml-1"><%= @post.like_count %></span>
<% end %>
</button>
<% else %>
<button phx-click="unreact" phx-value-type="👍" phx-value-post-id={@post.uuid} class="flex rounded-full px-3 py-1 border border-gray-300 bg-gray-100 items-center">
<span class="">
<img src="/images/icons/thumb.svg" class="h-4" />
</span>
<%= if @post.like_count > 0 do %>
<span class="ml-1"><%= @post.like_count %></span>
<% end %>
</button>
<% end %>
<%= if not Enum.member?(@loved_posts, @post.id) do %>
<button phx-click="react" phx-value-type="❤️" phx-value-post-id={@post.uuid} class="flex rounded-full px-3 py-1 border border-gray-300 bg-white items-center">
<img src="/images/icons/heart.svg" class="h-4" />
<%= if @post.love_count > 0 do %>
<span class="ml-1"><%= @post.love_count %></span>
<% end %>
</button>
<% else %>
<button phx-click="unreact" phx-value-type="❤️" phx-value-post-id={@post.uuid} class="flex rounded-full px-3 py-1 border border-gray-300 bg-gray-100 items-center">
<img src="/images/icons/heart.svg" class="h-4" />
<%= if @post.love_count > 0 do %>
<span class="ml-1"><%= @post.love_count %></span>
<% end %>
</button>
<% end %>
<%= if not Enum.member?(@loled_posts, @post.id) do %>
<button phx-click="react" phx-value-type="😂" phx-value-post-id={@post.uuid} class="flex rounded-full px-3 py-1 border border-gray-300 bg-white items-center">
<img src="/images/icons/laugh.svg" class="h-4" />
<%= if @post.lol_count > 0 do %>
<span class="ml-1"><%= @post.lol_count %></span>
<% end %>
</button>
<% else %>
<button phx-click="unreact" phx-value-type="😂" phx-value-post-id={@post.uuid} class="flex rounded-full px-3 py-1 border border-gray-300 bg-gray-100 items-center">
<img src="/images/icons/laugh.svg" class="h-4" />
<%= if @post.lol_count > 0 do %>
<span class="ml-1"><%= @post.lol_count %></span>
<% end %>
</button>
<% end %>
</div>
</div>
<% end %>
</div>
"""
end
defp is_a_leader(post, event, leaders) do
!is_nil(post.user_id) &&
(post.user_id == event.user_id ||
Enum.any?(leaders, fn leader ->
leader.user_id == post.user_id
end))
end
end

View File

@@ -0,0 +1,178 @@
defmodule ClaperWeb.EventLive.Presenter do
use ClaperWeb, :live_view
alias ClaperWeb.Presence
@impl true
def mount(%{"code" => code}, session, socket) do
with %{"locale" => locale} <- session do
Gettext.put_locale(ClaperWeb.Gettext, locale)
end
event =
Claper.Events.get_event_with_code(code, [
:user,
presentation_file: [:polls, :presentation_state]
])
if is_nil(event) || not is_leader(socket, event) do
{:ok,
socket
|> put_flash(:error, gettext("Presentation doesn't exist"))
|> redirect(to: "/")}
else
if connected?(socket) do
Claper.Events.Event.subscribe(event.uuid)
Claper.Presentations.subscribe(event.presentation_file.id)
Presence.track(
self(),
"event:#{event.uuid}",
socket.assigns.current_user.id,
%{}
)
end
socket =
socket
|> assign(:attendees_nb, 1)
|> assign(:event, event)
|> assign(:state, event.presentation_file.presentation_state)
|> assign(:posts, list_posts(socket, event.uuid))
|> assign(:reacts, [])
|> poll_at_position
{:ok, socket, temporary_assigns: [posts: []]}
end
end
defp is_leader(%{assigns: %{current_user: current_user}} = _socket, event) do
Claper.Events.is_leaded_by(current_user.email, event) || event.user.id == current_user.id
end
defp is_leader(_socket, _event), do: false
@impl true
def handle_info(%{event: "presence_diff"}, %{assigns: %{event: event}} = socket) do
attendees = Presence.list("event:#{event.uuid}")
{:noreply, assign(socket, :attendees_nb, Enum.count(attendees))}
end
@impl true
def handle_info({:post_created, post}, socket) do
{:noreply,
socket
|> update(:posts, fn posts -> [post | posts] end)}
end
@impl true
def handle_info({:state_updated, state}, socket) do
{:noreply,
socket
|> assign(:state, state)
|> push_event("page", %{current_page: state.position})
|> push_event("reset-global-react", %{})
|> poll_at_position}
end
@impl true
def handle_info({:post_updated, post}, socket) do
{:noreply, socket |> update(:posts, fn posts -> [post | posts] end)}
end
@impl true
def handle_info({:reaction_added, post}, socket) do
{:noreply, socket |> update(:posts, fn posts -> [post | posts] end)}
end
@impl true
def handle_info({:reaction_removed, post}, socket) do
{:noreply, socket |> update(:posts, fn posts -> [post | posts] end)}
end
@impl true
def handle_info({:post_deleted, post}, socket) do
{:noreply, socket |> update(:posts, fn posts -> [post | posts] end)}
end
@impl true
def handle_info({:poll_updated, poll}, socket) do
{:noreply,
socket
|> update(:current_poll, fn _current_poll -> poll end)}
end
@impl true
def handle_info({:poll_deleted, _poll}, socket) do
{:noreply,
socket
|> update(:current_poll, fn _current_poll -> nil end)}
end
@impl true
def handle_info({:chat_visible, value}, socket) do
{:noreply,
socket
|> push_event("chat-visible", %{value: value})
|> update(:chat_visible, fn _chat_visible -> value end)}
end
@impl true
def handle_info({:poll_visible, value}, socket) do
{:noreply,
socket
|> push_event("poll-visible", %{value: value})
|> update(:poll_visible, fn _poll_visible -> value end)}
end
@impl true
def handle_info({:join_screen_visible, value}, socket) do
{:noreply,
socket
|> push_event("join-screen-visible", %{value: value})
|> update(:join_screen_visible, fn _join_screen_visible -> value end)}
end
@impl true
def handle_info({:react, type}, socket) do
{:noreply,
socket
|> push_event("global-react", %{type: type})}
end
@impl true
def handle_info(
{:current_poll, poll},
socket
) do
{:noreply, socket |> assign(:current_poll, poll)}
end
@impl true
def handle_info(_, socket) do
{:noreply, socket}
end
@impl true
def handle_params(params, _url, socket) do
{:noreply, apply_action(socket, socket.assigns.live_action, params)}
end
defp apply_action(socket, :show, _params) do
socket
end
defp poll_at_position(%{assigns: %{event: event, state: state}} = socket) do
with poll <-
Claper.Polls.get_poll_current_position(
event.presentation_file.id,
state.position
) do
socket |> assign(:current_poll, poll)
end
end
defp list_posts(_socket, event_id) do
Claper.Posts.list_posts(event_id, [:event, :reactions])
end
end

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