diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..da6d418 --- /dev/null +++ b/.env.example @@ -0,0 +1,56 @@ +# ───────────────────────────────────────────────────────────── +# jama — Configuration +# just another messaging app +# +# Copy this file to .env and customize before first run. +# ───────────────────────────────────────────────────────────── + +# Project name — used as the Docker container name. +# If you run multiple jama instances on the same host, give each a unique name. +PROJECT_NAME=jama + +# Image version to run (set by build.sh, or use 'latest') +JAMA_VERSION=0.9.23 + +# App port — the host port Docker maps to the container +PORT=3000 + +# Timezone — must match your host timezone +# Run 'timedatectl' on Linux or 'ls /usr/share/zoneinfo' to find your value +# Examples: America/Toronto, Europe/London, Asia/Tokyo +TZ=UTC + +# ── App ─────────────────────────────────────────────────────── +# App name (can also be changed in the Settings UI after first run) +APP_NAME=jama + +# Default public group name (created on first run only) +DEFCHAT_NAME=General Chat + +# ── Admin credentials (used on FIRST RUN only) ──────────────── +ADMIN_NAME=Admin User +ADMIN_EMAIL=admin@jama.local +ADMIN_PASS=Admin@1234 + +# Default password for bulk-imported users (when no password is set in CSV) +USER_PASS=user@1234 + +# Set to true to reset the admin password to ADMIN_PASS on every restart. +# WARNING: Leave false in production — shows a warning banner on the login page when true. +ADMPW_RESET=false + +# ── Security ────────────────────────────────────────────────── +# JWT secret — change this to a long random string in production! +# Generate one: openssl rand -hex 32 +JWT_SECRET=changeme_super_secret_jwt_key_change_in_production + +# Database encryption key (SQLCipher AES-256) +# Generate a strong key: openssl rand -hex 32 +# Leave blank to run without encryption (not recommended for production). +# +# IMPORTANT — upgrading an existing unencrypted install: +# 1. docker compose down +# 2. Find your DB: docker volume inspect _jama_db +# 3. node backend/scripts/encrypt-db.js --db /path/to/jama.db --key YOUR_KEY +# 4. Add DB_KEY=YOUR_KEY here, then: ./build.sh && docker compose up -d +DB_KEY= diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..31efb4b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,48 @@ +ARG VERSION=dev +ARG BUILD_DATE=unknown + +FROM node:20-alpine AS builder + +WORKDIR /app + +# Install frontend dependencies and build +COPY frontend/package*.json ./frontend/ +RUN cd frontend && npm install + +COPY frontend/ ./frontend/ +RUN cd frontend && npm run build + +# Backend +FROM node:20-alpine + +ARG VERSION=dev +ARG BUILD_DATE=unknown + +LABEL org.opencontainers.image.title="jama" \ + org.opencontainers.image.description="Self-hosted team chat PWA" \ + org.opencontainers.image.version="${VERSION}" \ + org.opencontainers.image.created="${BUILD_DATE}" \ + org.opencontainers.image.source="https://github.com/yourorg/jama" + +ENV JAMA_VERSION=${VERSION} + +RUN apk add --no-cache sqlite python3 make g++ openssl-dev + +WORKDIR /app + +COPY backend/package*.json ./ +RUN npm install --omit=dev + +# Remove build tools after compile to keep image lean +RUN apk del python3 make g++ + +COPY backend/ ./ +COPY --from=builder /app/frontend/dist ./public + +# Create data and uploads directories +RUN mkdir -p /app/data /app/uploads/avatars /app/uploads/logos /app/uploads/images + + +EXPOSE 3000 + +CMD ["node", "src/index.js"] diff --git a/LICENSE b/LICENSE index c65b08e..7eb68f6 100644 --- a/LICENSE +++ b/LICENSE @@ -1,71 +1,68 @@ -GNU GENERAL PUBLIC LICENSE -Version 3, 29 June 2007 +GNU AFFERO GENERAL PUBLIC LICENSE +Version 3, 19 November 2007 -Copyright © 2007 Free Software Foundation, Inc. +Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. -Preamble + Preamble -The GNU General Public License is a free, copyleft license for software and other kinds of works. +The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. -The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, 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. +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. -When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. +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. +Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. -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. +A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. -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. +The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. -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. +An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. -TERMS AND CONDITIONS + TERMS AND CONDITIONS 0. Definitions. -“This License” refers to version 3 of the GNU General Public License. +"This License" refers to version 3 of the GNU Affero General Public License. -“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. +"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. +"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. +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. +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 "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. +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. +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. +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. +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 "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" 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. +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. +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. +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. @@ -80,153 +77,159 @@ You may charge any price or no price for each copy that you convey, and you may 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. + 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”. + 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. + 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. + 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. +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. + 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. + 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. + 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. + 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. + 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. +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. +"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). +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. +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. +"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. +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 + 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 + 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 + 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 + 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 + 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. + 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. +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). + +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. +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. + +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. +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. -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. +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. +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. +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 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. +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. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Remote Network Interaction; Use with the GNU General Public License. + +Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. + +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. -The Free Software Foundation may publish revised and/or new versions of the GNU 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. +The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. -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. +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. -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. +If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +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 + 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. +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. - jama-full + teamchat Copyright (C) 2026 rick - 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 free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. + This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. - You should have received a copy of the GNU General Public License along with this program. If not, see . + You should have received a copy of the GNU Affero General Public License along with this program. If not, see . 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: +If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. - jama-full Copyright (C) 2026 rick - 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 . - -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 . +You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . diff --git a/README.md b/README.md index ff00c55..29e76ca 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,412 @@ -# jama-full +# jama 💬 +### *just another messaging app* +A modern, self-hosted team messaging Progressive Web App (PWA) built for small to medium teams. jama runs entirely in a single Docker container with no external database dependencies — all data is stored locally using SQLite. + +--- + +## Features + +### Messaging +- **Real-time messaging** — WebSocket-powered (Socket.io); messages appear instantly across all clients +- **Image attachments** — Attach and send images via the + menu; auto-compressed client-side before upload +- **Camera capture** — Take a photo directly from the + menu on mobile devices +- **Emoji picker** — Send standalone emoji messages at large size via the + menu +- **Message replies** — Quote and reply to any message with an inline preview +- **Emoji reactions** — Quick-react with common emojis or open the full emoji picker; one reaction per user, replaceable +- **@Mentions** — Type `@` to search and tag users using `@[Display Name]` syntax; autocomplete scoped to group members; mentioned users receive a notification +- **Link previews** — URLs are automatically expanded with Open Graph metadata (title, image, site name) +- **Typing indicators** — See when others are composing a message +- **Image lightbox** — Tap any image to open it full-screen with pinch-to-zoom support +- **Message grouping** — Consecutive messages from the same user are visually grouped; avatar and name shown only on first message +- **Last message preview** — Sidebar shows "You:" prefix when the current user sent the last message + +### Channels & Groups +- **Public channels** — Admin-created; all users are automatically added +- **Private groups / DMs** — Any user can create; membership is invite-only by the owner +- **Direct messages** — One-to-one private conversations; sidebar title always shows the other user's real name +- **Duplicate group prevention** — Creating a private group with the same member set as an existing group redirects to the existing group automatically +- **Read-only channels** — Admin-configurable announcement-style channels; only admins can post +- **Support group** — A private admin-only group that receives submissions from the login page contact form +- **Custom group names** — Each user can set a personal display name for any group, visible only to them + +### Users & Profiles +- **Authentication** — Email/password login with optional Remember Me (30-day session) +- **Forced password change** — New users must change their password on first login +- **User profiles** — Custom display name, avatar upload, About Me text +- **Profile popup** — Click any user's avatar in chat to view their profile card +- **Admin badge** — Admins display a role badge; can be hidden per-user in Profile settings + +### Notifications +- **In-app notifications** — Mention alerts with toast notifications +- **Unread indicators** — Private groups with new unread messages are highlighted and bolded in the sidebar +- **Web Push notifications** — Badge and push notifications for mentions and new private messages when the app is backgrounded or closed (requires HTTPS) + +### Admin & Settings +- **User Manager** — Create, suspend, activate, delete users; reset passwords; change roles +- **Bulk CSV import** — Import multiple users at once from a CSV file +- **App branding** — Customize app name and logo via the Settings panel +- **Reset to defaults** — One-click reset of all branding customizations +- **Version display** — Current app version shown in the Settings panel +- **Default user password** — Configurable via `USER_PASS` env var; shown live in User Manager + +### Help & Onboarding +- **Getting Started modal** — Appears automatically on first login; users can dismiss permanently with "Do not show again" +- **Help menu item** — Always accessible from the user menu regardless of dismissed state +- **Editable help content** — `data/help.md` is edited before build and baked into the image at build time + +### PWA +- **Installable** — Install to home screen on mobile and desktop via the browser install prompt +- **Adaptive icons** — Separate `any` and `maskable` icon entries; maskable icons sized for Android circular crop +- **Dynamic app icon** — Uploaded logo is automatically resized and used as the PWA shortcut icon +- **Dynamic manifest** — App name and icons update live when changed in Settings +- **Pull-to-refresh disabled** — In PWA standalone mode, pull-to-refresh is disabled to prevent a layout shift bug on mobile + +### Contact Form +- **Login page contact form** — A "Contact Support" button on the login page opens a form that posts directly into the admin Support group + +--- + +## Tech Stack + +| Layer | Technology | +|---|---| +| Backend | Node.js, Express, Socket.io | +| Database | SQLite (better-sqlite3) | +| Frontend | React 18, Vite | +| Markdown rendering | marked | +| Emoji picker | emoji-mart | +| Image processing | sharp | +| Push notifications | web-push (VAPID) | +| Containerization | Docker, Docker Compose | +| Reverse proxy / SSL | Caddy (recommended) | + +--- + +## Requirements + +- **Docker** and **Docker Compose v2** +- A domain name with DNS pointed at your server (required for HTTPS and Web Push notifications) +- Ports **80** and **443** open on your server firewall (if using Caddy for SSL) + +--- + +## Building the Image + +All builds use `build.sh`. No host Node.js installation is required. + +> **Tip:** Edit `data/help.md` before running `build.sh` to customise the Getting Started help content baked into the image. + +```bash +# Build and tag as :latest only +./build.sh + +# Build and tag as a specific version +./build.sh 1.0.0 +``` + +--- + +## Installation + +### 1. Clone the repository + +```bash +git clone https://your-gitea/youruser/jama.git +cd jama +``` + +### 2. Build the Docker image + +```bash +./build.sh 1.0.0 +``` + +### 3. Configure environment + +```bash +cp .env.example .env +nano .env +``` + +At minimum, change `ADMIN_EMAIL`, `ADMIN_PASS`, and `JWT_SECRET`. + +### 4. Start the container + +```bash +docker compose up -d +docker compose logs -f jama +``` + +### 5. Log in + +Open `http://your-server:3000`, log in with your `ADMIN_EMAIL` and `ADMIN_PASS`, and change your password when prompted. + +--- + +## HTTPS & SSL + +jama does not manage SSL itself. Use **Caddy** as a reverse proxy. + +### Caddyfile + +``` +chat.yourdomain.com { + reverse_proxy jama:3000 +} +``` + +### docker-compose.yaml (with Caddy) + +```yaml +version: '3.8' +services: + jama: + image: jama:${JAMA_VERSION:-latest} + container_name: jama + restart: unless-stopped + expose: + - "3000" + environment: + - NODE_ENV=production + - ADMIN_NAME=${ADMIN_NAME:-Admin User} + - ADMIN_EMAIL=${ADMIN_EMAIL:-admin@jama.local} + - ADMIN_PASS=${ADMIN_PASS:-Admin@1234} + - USER_PASS=${USER_PASS:-user@1234} + - ADMPW_RESET=${ADMPW_RESET:-false} + - JWT_SECRET=${JWT_SECRET:-changeme} + - APP_NAME=${APP_NAME:-jama} + - JAMA_VERSION=${JAMA_VERSION:-latest} + volumes: + - jama_db:/app/data + - jama_uploads:/app/uploads + + caddy: + image: caddy:alpine + container_name: caddy + restart: unless-stopped + ports: + - "80:80" + - "443:443" + - "443:443/udp" + volumes: + - ./Caddyfile:/etc/caddy/Caddyfile:ro + - caddy_data:/data + - caddy_certs:/config + depends_on: + - jama + +volumes: + jama_db: + jama_uploads: + caddy_data: + caddy_certs: +``` + +--- + +## Environment Variables + +| Variable | Default | Description | +|---|---|---| +| `JAMA_VERSION` | `latest` | Docker image tag to run | +| `TZ` | `UTC` | Container timezone (e.g. `America/Toronto`) | +| `ADMIN_NAME` | `Admin User` | Display name of the default admin account | +| `ADMIN_EMAIL` | `admin@jama.local` | Login email for the default admin account | +| `ADMIN_PASS` | `Admin@1234` | Initial password for the default admin account | +| `USER_PASS` | `user@1234` | Default temporary password for bulk-imported users when no password is specified in CSV | +| `ADMPW_RESET` | `false` | If `true`, resets the **admin** password to `ADMIN_PASS` on every restart. Emergency access recovery only. Shows a warning banner when active. | +| `JWT_SECRET` | *(insecure default)* | Secret used to sign auth tokens. **Must be changed in production.** | +| `PORT` | `3000` | Host port to bind (without Caddy) | +| `APP_NAME` | `jama` | Initial application name (can also be changed in Settings UI) | +| `DEFCHAT_NAME` | `General Chat` | Name of the default public group created on first run | + +> `ADMIN_EMAIL` and `ADMIN_PASS` are only used on the **first run**. Once the database exists they are ignored — unless `ADMPW_RESET=true`. + +### Example `.env` + +```env +JAMA_VERSION=1.0.0 +TZ=America/Toronto + +ADMIN_NAME=Your Name +ADMIN_EMAIL=admin@yourdomain.com +ADMIN_PASS=ChangeThisNow! + +USER_PASS=Welcome@123 +ADMPW_RESET=false + +JWT_SECRET=replace-this-with-a-long-random-string-at-least-32-chars + +PORT=3000 +APP_NAME=jama +DEFCHAT_NAME=General Chat +``` + +--- + +## First Login & Setup Checklist + +1. Log in with `ADMIN_EMAIL` / `ADMIN_PASS` +2. Change your password when prompted +3. Read the **Getting Started** guide that appears on first login +4. Open ⚙️ **Settings** → upload a logo and set the app name +5. Open 👥 **User Manager** to create accounts for your team + +--- + +## User Management + +Accessible from the bottom-left menu (admin only). + +| Action | Description | +|---|---| +| Create user | Set name, email, temporary password, and role | +| Bulk CSV import | Upload a CSV to create multiple users at once | +| Reset password | User is forced to set a new password on next login | +| Suspend | Blocks login; messages are preserved | +| Activate | Re-enables a suspended account | +| Delete | Removes account; messages remain attributed to user | +| Change role | Promote member → admin or demote admin → member | + +### CSV Import Format + +```csv +name,email,password,role +John Doe,john@example.com,TempPass123,member +Jane Smith,jane@example.com,,admin +``` + +- `password` is optional — defaults to the value of `USER_PASS` if omitted +- All imported users must change their password on first login + +--- + +## Group Types + +| | Public Channels | Private Groups | Direct Messages | +|---|---|---|---| +| Who can create | Admin only | Any user | Any user | +| Membership | All users (automatic) | Invite-only by owner | Two users only | +| Sidebar title | Group name | Group name (customisable per user) | Other user's real name | +| Rename | Admin only | Owner only | ❌ Not allowed | +| Read-only mode | ✅ Optional | ❌ N/A | ❌ N/A | +| Duplicate prevention | N/A | ✅ Redirects to existing | ✅ Redirects to existing | + +### @Mention Scoping + +- **Public channels** — all active users appear in the `@` autocomplete +- **Private groups** — only members of that group appear +- **Direct messages** — only the other participant appears + +--- + +## Custom Group Names + +Any user can set a personal display name for any group: + +1. Open the group and tap the **ⓘ info** icon +2. Enter a name under **Your custom name** and tap **Save** +3. The custom name appears in your sidebar and chat header only +4. Message Info shows: `Custom Name (Owner's Name)` +5. Clear the field and tap **Save** to revert to the owner's name + +--- + +## Help Content + +The Getting Started guide is sourced from `data/help.md`. Edit before running `build.sh` — it is baked into the image at build time. + +```bash +nano data/help.md +./build.sh 1.0.0 +``` + +Users can access the guide at any time via **User menu → Help**. + +--- + +## Data Persistence + +| Volume | Container path | Contents | +|---|---|---| +| `jama_db` | `/app/data` | SQLite database (`jama.db`), `help.md` | +| `jama_uploads` | `/app/uploads` | Avatars, logos, PWA icons, message images | + +### Backup + +```bash +# Backup database +docker run --rm \ + -v jama_db:/data \ + -v $(pwd):/backup alpine \ + tar czf /backup/jama_db_$(date +%Y%m%d).tar.gz -C /data . + +# Backup uploads +docker run --rm \ + -v jama_uploads:/data \ + -v $(pwd):/backup alpine \ + tar czf /backup/jama_uploads_$(date +%Y%m%d).tar.gz -C /data . +``` + +--- + +## Upgrades & Rollbacks + +```bash +# Upgrade +./build.sh 1.1.0 +# Set JAMA_VERSION=1.1.0 in .env +docker compose up -d + +# Rollback +# Set JAMA_VERSION=1.0.0 in .env +docker compose up -d +``` + +Data volumes are untouched in both cases. + +--- + +## PWA Icons + +| File | Purpose | +|---|---| +| `icon-192.png` / `icon-512.png` | Standard icons — PC PWA shortcuts (`purpose: any`) | +| `icon-192-maskable.png` / `icon-512-maskable.png` | Adaptive icons — Android home screen (`purpose: maskable`); logo at 75% scale on solid background | + +--- + +## ADMPW_RESET Flag + +Resets the **admin account** password to `ADMIN_PASS` on every container restart. Use only when the admin password has been lost. + +```env +# Enable for recovery +ADMPW_RESET=true + +# Disable after recovering access +ADMPW_RESET=false +``` + +A ⚠️ warning banner is shown on the login page and in Settings when active. + +--- + +## Development + +```bash +# Backend (port 3000) +cd backend && npm install && npm run dev + +# Frontend (port 5173) +cd frontend && npm install && npm run dev +``` + +The Vite dev server proxies all `/api` and `/socket.io` requests to the backend automatically. + +--- + +## License + +MIT diff --git a/about.json.example b/about.json.example new file mode 100644 index 0000000..94902e1 --- /dev/null +++ b/about.json.example @@ -0,0 +1,7 @@ +{ + "built_with": "Node.js · Express · Socket.io · SQLite · React · Vite · Claude.ai", + "developer": "Your Name or Organization", + "license": "AGPL 3.0", + "license_url": "https://www.gnu.org/licenses/agpl-3.0.html", + "description": "Self-hosted, privacy-first team messaging." +} diff --git a/backend/package.json b/backend/package.json new file mode 100644 index 0000000..74a7973 --- /dev/null +++ b/backend/package.json @@ -0,0 +1,27 @@ +{ + "name": "jama-backend", + "version": "0.9.23", + "description": "TeamChat backend server", + "main": "src/index.js", + "scripts": { + "start": "node src/index.js", + "dev": "nodemon src/index.js" + }, + "dependencies": { + "bcryptjs": "^2.4.3", + "cookie-parser": "^1.4.6", + "cors": "^2.8.5", + "express": "^4.18.2", + "jsonwebtoken": "^9.0.2", + "multer": "^1.4.5-lts.1", + "nanoid": "^3.3.7", + "node-fetch": "^2.7.0", + "sharp": "^0.33.2", + "socket.io": "^4.6.1", + "web-push": "^3.6.7", + "better-sqlite3-multiple-ciphers": "^12.6.2" + }, + "devDependencies": { + "nodemon": "^3.0.2" + } +} \ No newline at end of file diff --git a/backend/scripts/encrypt-db.js b/backend/scripts/encrypt-db.js new file mode 100644 index 0000000..71a8219 --- /dev/null +++ b/backend/scripts/encrypt-db.js @@ -0,0 +1,136 @@ +#!/usr/bin/env node +/** + * jama DB encryption migration + * ───────────────────────────────────────────────────────────────────────────── + * Converts an existing plain SQLite database to SQLCipher (AES-256 encrypted). + * + * Run ONCE before upgrading to a jama version that includes DB_KEY support. + * The container must be STOPPED before running this script. + * + * Usage (run on the Docker host, not inside the container): + * + * node encrypt-db.js --db /path/to/jama.db --key YOUR_DB_KEY + * + * Or using env vars: + * + * DB_PATH=/path/to/jama.db DB_KEY=yourkey node encrypt-db.js + * + * To find your Docker volume path: + * docker volume inspect jama_jama_db + * (look for the "Mountpoint" field) + * + * The script will: + * 1. Verify the source file is a plain (unencrypted) SQLite database + * 2. Create an encrypted copy at .encrypted + * 3. Back up the original to .plaintext-backup + * 4. Move the encrypted copy into place as + * + * If anything goes wrong, restore with: + * cp jama.db.plaintext-backup jama.db + * ───────────────────────────────────────────────────────────────────────────── + */ + +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +// Parse CLI args --db and --key +const args = process.argv.slice(2); +const argDb = args[args.indexOf('--db') + 1]; +const argKey = args[args.indexOf('--key') + 1]; + +const DB_PATH = argDb || process.env.DB_PATH || '/app/data/jama.db'; +const DB_KEY = argKey || process.env.DB_KEY || ''; + +// ── Validation ──────────────────────────────────────────────────────────────── + +if (!DB_KEY) { + console.error('ERROR: No DB_KEY provided.'); + console.error('Usage: node encrypt-db.js --db /path/to/jama.db --key YOUR_KEY'); + console.error(' or: DB_KEY=yourkey node encrypt-db.js'); + process.exit(1); +} + +if (!fs.existsSync(DB_PATH)) { + console.error(`ERROR: Database file not found: ${DB_PATH}`); + process.exit(1); +} + +// Check it looks like a plain SQLite file (magic bytes: "SQLite format 3\000") +const MAGIC = 'SQLite format 3\0'; +const fd = fs.openSync(DB_PATH, 'r'); +const header = Buffer.alloc(16); +fs.readSync(fd, header, 0, 16, 0); +fs.closeSync(fd); + +if (header.toString('ascii') !== MAGIC) { + console.error('ERROR: The database does not appear to be a plain (unencrypted) SQLite file.'); + console.error('It may already be encrypted, or the path is wrong.'); + process.exit(1); +} + +// ── Migration ───────────────────────────────────────────────────────────────── + +let Database; +try { + Database = require('better-sqlite3-multiple-ciphers'); +} catch (e) { + console.error('ERROR: better-sqlite3-sqlcipher is not installed.'); + console.error('Run: npm install better-sqlite3-sqlcipher'); + process.exit(1); +} + +const encPath = DB_PATH + '.encrypted'; +const backupPath = DB_PATH + '.plaintext-backup'; + +console.log(`\njama DB encryption migration`); +console.log(`────────────────────────────`); +console.log(`Source: ${DB_PATH}`); +console.log(`Backup: ${backupPath}`); +console.log(`Output: ${DB_PATH} (encrypted)\n`); + +try { + // Open the plain DB (no key) + console.log('Step 1/4 Opening plain database...'); + const plain = new Database(DB_PATH); + + // Create encrypted copy using sqlcipher_export via ATTACH + console.log('Step 2/4 Encrypting to temporary file...'); + const safeKey = DB_KEY.replace(/'/g, "''"); + plain.exec(`ATTACH DATABASE '${encPath}' AS encrypted KEY '${safeKey}'`); + plain.exec(`SELECT sqlcipher_export('encrypted')`); + plain.exec(`DETACH DATABASE encrypted`); + plain.close(); + + // Verify the encrypted file opens correctly with cipher settings + console.log('Step 3/4 Verifying encrypted database...'); + const enc = new Database(encPath); + enc.pragma(`cipher='sqlcipher'`); + enc.pragma(`legacy=4`); + enc.pragma(`key='${safeKey}'`); + const count = enc.prepare("SELECT COUNT(*) as n FROM sqlite_master").get(); + enc.close(); + console.log(` OK — ${count.n} objects found in encrypted DB`); + + // Swap files: backup plain, move encrypted into place + console.log('Step 4/4 Swapping files...'); + fs.renameSync(DB_PATH, backupPath); + fs.renameSync(encPath, DB_PATH); + + console.log(`\n✓ Migration complete!`); + console.log(` Encrypted DB: ${DB_PATH}`); + console.log(` Plain backup: ${backupPath}`); + console.log(`\nNext steps:`); + console.log(` 1. Set DB_KEY=${DB_KEY} in your .env file`); + console.log(` 2. Start jama — it will open the encrypted database`); + console.log(` 3. Once confirmed working, delete the plain backup:`); + console.log(` rm ${backupPath}\n`); + +} catch (err) { + console.error(`\n✗ Migration failed: ${err.message}`); + // Clean up any partial encrypted file + if (fs.existsSync(encPath)) fs.unlinkSync(encPath); + console.error('No changes were made to the original database.'); + process.exit(1); +} diff --git a/backend/src/data/help.md b/backend/src/data/help.md new file mode 100644 index 0000000..70828ce --- /dev/null +++ b/backend/src/data/help.md @@ -0,0 +1,134 @@ +# Getting Started with JAMA + +Welcome to **JAMA** — your private, self-hosted team messaging app. + +**JAMA** - **J**ust **A**nother **M**essaging **A**pp + +--- + +## What is JAMA? + +JAMA is a private chat system that doesn’t need the internet to work—you can host it on a completely offline network. Even if you do run JAMA while you're online, it stays locked inside its own "container," so it never reaches out to other internet services. + +We keep things private, too: the only info we ask for is a name and an email, and technically speaking they don't even have to be real. Your name just helps your team know who you are, and your email is only used as your login (it's never shares with anyone else). + +There’s no annoying phone or email verification to deal with, so you can jump right in. If you ever get locked out, just hit the "Get Help" link on the login page. JAMA is easy and intuitive, you're going to love it. + +---- +---- + +## Security + +### 🛡️ Your Privacy Assured +**Encryption**, the JAMA database is fully encrypted. Your posts are protected from prying eyes, including the JAMA administrators. + +The only people that can read your direct messages (**person 2 person** or **group**) are the members of your message group. No one else knows, including JAMA admins, which direct message groups exist or which you are part of, well, unless they are a member of the group. With the database being encrypted there is no easy way to access your data. + +**Every user**, at minimum, can read all public messages. + +---- +---- + +## Navigating JAMA + +### Message List (Left Sidebar) +The sidebar shows all your message groups and direct conversations. Tap or click any group to open it. + +- **#** prefix indicates a **Public** group — visible to all users +- **Bold** group names, with a notification badge means you have unread messages +- A message with the newest post with alway be listed at the top +- The last message preview shows a message from a user in your group, or **You:** if you sent it + + +## Sending Messages + +Type your message in the input box at the bottom and press **Enter** to send. + +- **Shift + Enter** adds a new line without sending +- Tap the **+** button to attach a photo or emoji +- Use the **camera** icon to take a photo directly (mobile only) + +### Mentioning Someone +Type **@** will bring a group user list, select a users real name to mention them. Users receive a notification. + +Example: `@[John Smith]` will notify John Smith of the message. + +### Replying to a Message +Hover over any message and click the **reply arrow** in the pop-up to quote and reply to it. + +### Reacting to a Message +Hover over any message and select a common emoji in the pop-up to or click the **emoji** button to bring up a full list to select from. + +--- + +## Direct Messages + +There are two ways to start a private conversation with one person: + +_**New Chat Button**_ +1. Click the **New Chat** icon in the sidebar +2. Select one user from the list +3. Click **Start Conversation** + +_**Message Window**_ +1. Click the users avatar in a message window to bring up the profile +2. Click **Direct Message** + +> _Users have the ability to disable direct and private messages in their profile. If set, they will not be listed in the "New Chat" user list and the "Direct Message" button is not enabled._ + +--- + +## Group Messages + +To create a group conversation: + +1. Click the **new chat** icon +2. Select two or more users from the +3. Enter a **Message Name** +4. Click **Create** + +> _If a message group with the exact same members already exists, you will be redirected to it automatically. This helps to avoid duplication._ + +_**Note:** Users have the option to leave any direct message group by selecting the "Message Info" button in the top right corner in the message title._ + +--- + +## Your Profile + +Click your name or avatar at the bottom of the sidebar to: + +- Update your **display name** (displayed in message windows) +- Add an **about me** note +- Upload a **profile photo** for your avatar +- Change your **password** + +--- + +## Customising Group Names + +You can set a personal display name for any group that only you will see: + +1. Open the message +2. Click the **message info** icon in the top right +3. Enter your custom name under **Your custom name** +4. Click **Save** + +Other members still see the original group name, unless they change to customised name for themselves. + +--- + +## Admin Options + +Admins can access **Settings** from the user menu to configure: + +- **Branding:** a new app name and/or logo, title colour and message list avatar background colours +- **User Manager:** Create new user password, change passwords, suspend and delete user accounts. +- **Settings:** Various options + +--- + +## Tips + +- 🌙 Toggle **dark mode** from the user menu +- 🔔 Enable **push notifications** when prompted to receive alerts when the app is closed +- 📱 Install JAMA as a **PWA** on your device — tap *Add to Home Screen* in your browser menu for an app-like experience diff --git a/backend/src/index.js b/backend/src/index.js new file mode 100644 index 0000000..6b32fd5 --- /dev/null +++ b/backend/src/index.js @@ -0,0 +1,363 @@ +const express = require('express'); +const http = require('http'); +const { Server } = require('socket.io'); +const cookieParser = require('cookie-parser'); +const cors = require('cors'); +const path = require('path'); +const jwt = require('jsonwebtoken'); +const { initDb, seedAdmin, getOrCreateSupportGroup, getDb } = require('./models/db'); +const { router: pushRouter, sendPushToUser } = require('./routes/push'); +const { getLinkPreview } = require('./utils/linkPreview'); + +const app = express(); +const server = http.createServer(app); +const io = new Server(server, { + cors: { origin: '*', methods: ['GET', 'POST'] } +}); + +const JWT_SECRET = process.env.JWT_SECRET || 'changeme_super_secret'; +const PORT = process.env.PORT || 3000; + +// Init DB +initDb(); +seedAdmin(); +// Ensure Support group exists and all admins are members +const supportGroupId = getOrCreateSupportGroup(); +if (supportGroupId) { + const db = getDb(); + const admins = db.prepare("SELECT id FROM users WHERE role = 'admin' AND status = 'active'").all(); + const insert = db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)'); + for (const a of admins) insert.run(supportGroupId, a.id); +} + +// Middleware +app.use(cors()); +app.use(express.json()); +app.use(cookieParser()); +app.use('/uploads', express.static('/app/uploads')); + +// API Routes +app.use('/api/auth', require('./routes/auth')(io)); +app.use('/api/users', require('./routes/users')); +app.use('/api/groups', require('./routes/groups')(io)); +app.use('/api/messages', require('./routes/messages')(io)); +app.use('/api/settings', require('./routes/settings')); +app.use('/api/about', require('./routes/about')); +app.use('/api/help', require('./routes/help')); +app.use('/api/push', pushRouter); + +// Link preview proxy +app.get('/api/link-preview', async (req, res) => { + const { url } = req.query; + if (!url) return res.status(400).json({ error: 'URL required' }); + const preview = await getLinkPreview(url); + res.json({ preview }); +}); + +// Health check +app.get('/api/health', (req, res) => res.json({ ok: true })); + +// Dynamic manifest — must be before express.static so it takes precedence +app.get('/manifest.json', (req, res) => { + const db = getDb(); + const rows = db.prepare("SELECT key, value FROM settings WHERE key IN ('app_name', 'logo_url', 'pwa_icon_192', 'pwa_icon_512')").all(); + const s = {}; + for (const r of rows) s[r.key] = r.value; + + const appName = s.app_name || process.env.APP_NAME || 'jama'; + const pwa192 = s.pwa_icon_192 || ''; + const pwa512 = s.pwa_icon_512 || ''; + + // Use uploaded+resized icons if they exist, else fall back to bundled PNGs. + // Chrome requires explicit pixel sizes (not "any") to use icons for PWA shortcuts. + const icon192 = pwa192 || '/icons/icon-192.png'; + const icon512 = pwa512 || '/icons/icon-512.png'; + + const icons = [ + { src: icon192, sizes: '192x192', type: 'image/png', purpose: 'any' }, + { src: icon192, sizes: '192x192', type: 'image/png', purpose: 'maskable' }, + { src: icon512, sizes: '512x512', type: 'image/png', purpose: 'any' }, + { src: icon512, sizes: '512x512', type: 'image/png', purpose: 'maskable' }, + ]; + + const manifest = { + name: appName, + short_name: appName.length > 12 ? appName.substring(0, 12) : appName, + description: `${appName} - Team messaging`, + start_url: '/', + scope: '/', + display: 'standalone', + orientation: 'portrait-primary', + background_color: '#ffffff', + theme_color: '#1a73e8', + icons, + }; + + res.setHeader('Content-Type', 'application/manifest+json'); + res.setHeader('Cache-Control', 'no-cache'); + res.json(manifest); +}); + +// Serve frontend +app.use(express.static(path.join(__dirname, '../public'))); +app.get('*', (req, res) => { + res.sendFile(path.join(__dirname, '../public/index.html')); +}); + +// Socket.io authentication +io.use((socket, next) => { + const token = socket.handshake.auth.token; + if (!token) return next(new Error('Unauthorized')); + try { + const decoded = jwt.verify(token, JWT_SECRET); + const db = getDb(); + const user = db.prepare('SELECT id, name, display_name, avatar, role, status FROM users WHERE id = ? AND status = ?').get(decoded.id, 'active'); + if (!user) return next(new Error('User not found')); + // Per-device enforcement: token must match an active session row + const session = db.prepare('SELECT * FROM active_sessions WHERE user_id = ? AND token = ?').get(decoded.id, token); + if (!session) return next(new Error('Session displaced')); + socket.user = user; + socket.token = token; + socket.device = session.device; + next(); + } catch (e) { + next(new Error('Invalid token')); + } +}); + +// Track online users: userId -> Set of socketIds +const onlineUsers = new Map(); + +io.on('connection', (socket) => { + const userId = socket.user.id; + + if (!onlineUsers.has(userId)) onlineUsers.set(userId, new Set()); + onlineUsers.get(userId).add(socket.id); + + // Record last_online timestamp + getDb().prepare("UPDATE users SET last_online = datetime('now') WHERE id = ?").run(userId); + + // Broadcast online status + io.emit('user:online', { userId }); + + // Join personal room for direct notifications + socket.join(`user:${userId}`); + + // Join rooms for all user's groups + const db = getDb(); + const publicGroups = db.prepare("SELECT id FROM groups WHERE type = 'public'").all(); + for (const g of publicGroups) socket.join(`group:${g.id}`); + + const privateGroups = db.prepare("SELECT group_id FROM group_members WHERE user_id = ?").all(userId); + for (const g of privateGroups) socket.join(`group:${g.group_id}`); + + // When a new group is created and pushed to this socket, join its room + socket.on('group:join-room', ({ groupId }) => { + socket.join(`group:${groupId}`); + }); + + // When a user leaves a group, remove them from the socket room + socket.on('group:leave-room', ({ groupId }) => { + socket.leave(`group:${groupId}`); + }); + + // Handle new message + socket.on('message:send', async (data) => { + const { groupId, content, replyToId, imageUrl, linkPreview } = data; + const db = getDb(); + + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(groupId); + if (!group) return; + if (group.is_readonly && socket.user.role !== 'admin') return; + + // Check access + if (group.type === 'private') { + const member = db.prepare('SELECT id FROM group_members WHERE group_id = ? AND user_id = ?').get(groupId, userId); + if (!member) return; + } + + const result = db.prepare(` + INSERT INTO messages (group_id, user_id, content, image_url, type, reply_to_id, link_preview) + VALUES (?, ?, ?, ?, ?, ?, ?) + `).run(groupId, userId, content || null, imageUrl || null, imageUrl ? 'image' : 'text', replyToId || null, linkPreview ? JSON.stringify(linkPreview) : null); + + const message = db.prepare(` + SELECT m.*, + u.name as user_name, u.display_name as user_display_name, u.avatar as user_avatar, u.role as user_role, u.status as user_status, u.hide_admin_tag as user_hide_admin_tag, u.about_me as user_about_me, + rm.content as reply_content, rm.image_url as reply_image_url, rm.is_deleted as reply_is_deleted, + ru.name as reply_user_name, ru.display_name as reply_user_display_name + FROM messages m + JOIN users u ON m.user_id = u.id + LEFT JOIN messages rm ON m.reply_to_id = rm.id + LEFT JOIN users ru ON rm.user_id = ru.id + WHERE m.id = ? + `).get(result.lastInsertRowid); + + message.reactions = []; + + io.to(`group:${groupId}`).emit('message:new', message); + + // For private groups: push notify members who are offline + // (reuse `group` already fetched above) + if (group?.type === 'private') { + const members = db.prepare('SELECT user_id FROM group_members WHERE group_id = ?').all(groupId); + const senderName = socket.user?.display_name || socket.user?.name || 'Someone'; + for (const m of members) { + if (m.user_id === userId) continue; // don't notify sender + if (!onlineUsers.has(m.user_id)) { + // User is offline — send push + sendPushToUser(m.user_id, { + title: senderName, + body: (content || (imageUrl ? '📷 Image' : '')).slice(0, 100), + url: '/', + groupId, + badge: 1, + }).catch(() => {}); + } else { + // User is online but not necessarily in this group — send socket notification + const notif = { type: 'private_message', groupId, fromUser: socket.user }; + for (const sid of onlineUsers.get(m.user_id)) { + io.to(sid).emit('notification:new', notif); + } + } + } + } + + // Process @mentions — format is @[display name], look up user by display_name or name + if (content) { + const mentionNames = [...new Set((content.match(/@\[([^\]]+)\]/g) || []).map(m => m.slice(2, -1)))]; + for (const mentionName of mentionNames) { + const mentionedUser = db.prepare( + "SELECT id FROM users WHERE status = 'active' AND (LOWER(display_name) = LOWER(?) OR LOWER(name) = LOWER(?))" + ).get(mentionName, mentionName); + const matchId = mentionedUser?.id?.toString(); + if (matchId && parseInt(matchId) !== userId) { + const notifResult = db.prepare(` + INSERT INTO notifications (user_id, type, message_id, group_id, from_user_id) + VALUES (?, 'mention', ?, ?, ?) + `).run(parseInt(matchId), result.lastInsertRowid, groupId, userId); + + // Notify mentioned user — socket if online, push if not + const mentionedUserId = parseInt(matchId); + const notif = { + id: notifResult.lastInsertRowid, + type: 'mention', + groupId, + messageId: result.lastInsertRowid, + fromUser: socket.user, + }; + if (onlineUsers.has(mentionedUserId)) { + for (const sid of onlineUsers.get(mentionedUserId)) { + io.to(sid).emit('notification:new', notif); + } + } + // Always send push (badge even when app is open) + const senderName = socket.user?.display_name || socket.user?.name || 'Someone'; + sendPushToUser(mentionedUserId, { + title: `${senderName} mentioned you`, + body: (content || '').replace(/@\[([^\]]+)\]/g, '@$1').slice(0, 100), + url: '/', + badge: 1, + }).catch(() => {}); + } + } + } + }); + + // Handle reaction — one reaction per user; same emoji toggles off, different emoji replaces + socket.on('reaction:toggle', (data) => { + const { messageId, emoji } = data; + const db = getDb(); + const message = db.prepare('SELECT m.*, g.id as gid FROM messages m JOIN groups g ON m.group_id = g.id WHERE m.id = ? AND m.is_deleted = 0').get(messageId); + if (!message) return; + + // Find any existing reaction by this user on this message + const existing = db.prepare('SELECT * FROM reactions WHERE message_id = ? AND user_id = ?').get(messageId, userId); + + if (existing) { + if (existing.emoji === emoji) { + // Same emoji — toggle off (remove) + db.prepare('DELETE FROM reactions WHERE id = ?').run(existing.id); + } else { + // Different emoji — replace + db.prepare('UPDATE reactions SET emoji = ? WHERE id = ?').run(emoji, existing.id); + } + } else { + // No existing reaction — insert + db.prepare('INSERT INTO reactions (message_id, user_id, emoji) VALUES (?, ?, ?)').run(messageId, userId, emoji); + } + + const reactions = db.prepare(` + SELECT r.emoji, r.user_id, u.name as user_name + FROM reactions r JOIN users u ON r.user_id = u.id + WHERE r.message_id = ? + `).all(messageId); + + io.to(`group:${message.group_id}`).emit('reaction:updated', { messageId, reactions }); + }); + + // Handle message delete + socket.on('message:delete', (data) => { + const { messageId } = data; + const db = getDb(); + const message = db.prepare(` + SELECT m.*, g.type as group_type, g.owner_id as group_owner_id, g.is_direct + FROM messages m JOIN groups g ON m.group_id = g.id WHERE m.id = ? + `).get(messageId); + if (!message) return; + + const isAdmin = socket.user.role === 'admin'; + const isOwner = message.group_owner_id === userId; + const isAuthor = message.user_id === userId; + + // Rules: + // 1. Author can always delete their own message + // 2. Admin can delete in any public group or any group they're a member of + // 3. Group owner can delete any message in their group + // 4. In direct messages: author + owner rules apply (no blanket block) + let canDelete = isAuthor || isOwner; + if (!canDelete && isAdmin) { + if (message.group_type === 'public') { + canDelete = true; + } else { + // Admin can delete in private/direct groups they're a member of + const membership = db.prepare('SELECT id FROM group_members WHERE group_id = ? AND user_id = ?').get(message.group_id, userId); + if (membership) canDelete = true; + } + } + + if (!canDelete) return; + + db.prepare("UPDATE messages SET is_deleted = 1, content = null, image_url = null WHERE id = ?").run(messageId); + io.to(`group:${message.group_id}`).emit('message:deleted', { messageId, groupId: message.group_id }); + }); + + // Handle typing + socket.on('typing:start', ({ groupId }) => { + socket.to(`group:${groupId}`).emit('typing:start', { userId, groupId, user: socket.user }); + }); + socket.on('typing:stop', ({ groupId }) => { + socket.to(`group:${groupId}`).emit('typing:stop', { userId, groupId }); + }); + + // Get online users + socket.on('users:online', () => { + socket.emit('users:online', { userIds: [...onlineUsers.keys()] }); + }); + + // Handle disconnect + socket.on('disconnect', () => { + if (onlineUsers.has(userId)) { + onlineUsers.get(userId).delete(socket.id); + if (onlineUsers.get(userId).size === 0) { + onlineUsers.delete(userId); + getDb().prepare("UPDATE users SET last_online = datetime('now') WHERE id = ?").run(userId); + io.emit('user:offline', { userId }); + } + } + }); +}); + +server.listen(PORT, () => { + console.log(`jama server running on port ${PORT}`); +}); diff --git a/backend/src/middleware/auth.js b/backend/src/middleware/auth.js new file mode 100644 index 0000000..a464b25 --- /dev/null +++ b/backend/src/middleware/auth.js @@ -0,0 +1,73 @@ +const jwt = require('jsonwebtoken'); +const { getDb } = require('../models/db'); + +const JWT_SECRET = process.env.JWT_SECRET || 'changeme_super_secret'; + +// Classify a User-Agent string into 'mobile' or 'desktop'. +// Tablets are treated as mobile (one shared slot). +function getDeviceClass(ua) { + if (!ua) return 'desktop'; + const s = ua.toLowerCase(); + if (/mobile|android(?!.*tablet)|iphone|ipod|blackberry|windows phone|opera mini|silk/.test(s)) return 'mobile'; + if (/tablet|ipad|kindle|playbook|android/.test(s)) return 'mobile'; + return 'desktop'; +} + +function authMiddleware(req, res, next) { + const token = req.headers.authorization?.split(' ')[1] || req.cookies?.token; + if (!token) return res.status(401).json({ error: 'Unauthorized' }); + + try { + const decoded = jwt.verify(token, JWT_SECRET); + const db = getDb(); + const user = db.prepare('SELECT * FROM users WHERE id = ? AND status = ?').get(decoded.id, 'active'); + if (!user) return res.status(401).json({ error: 'User not found or suspended' }); + + // Per-device enforcement: token must match an active session row + const session = db.prepare('SELECT * FROM active_sessions WHERE user_id = ? AND token = ?').get(decoded.id, token); + if (!session) { + return res.status(401).json({ error: 'Session expired. Please log in again.' }); + } + + req.user = user; + req.token = token; + req.device = session.device; + next(); + } catch (e) { + return res.status(401).json({ error: 'Invalid token' }); + } +} + +function adminMiddleware(req, res, next) { + if (req.user?.role !== 'admin') return res.status(403).json({ error: 'Admin only' }); + next(); +} + +function generateToken(userId) { + return jwt.sign({ id: userId }, JWT_SECRET, { expiresIn: '30d' }); +} + +// Upsert the active session for this user+device class. +// Displaces any prior session on the same device class; the other device class is unaffected. +function setActiveSession(userId, token, userAgent) { + const db = getDb(); + const device = getDeviceClass(userAgent); + db.prepare(` + INSERT INTO active_sessions (user_id, device, token, ua, created_at) + VALUES (?, ?, ?, ?, datetime('now')) + ON CONFLICT(user_id, device) DO UPDATE SET token = ?, ua = ?, created_at = datetime('now') + `).run(userId, device, token, userAgent || null, token, userAgent || null); + return device; +} + +// Clear one device slot on logout, or all slots (no device arg) for suspend/delete +function clearActiveSession(userId, device) { + const db = getDb(); + if (device) { + db.prepare('DELETE FROM active_sessions WHERE user_id = ? AND device = ?').run(userId, device); + } else { + db.prepare('DELETE FROM active_sessions WHERE user_id = ?').run(userId); + } +} + +module.exports = { authMiddleware, adminMiddleware, generateToken, setActiveSession, clearActiveSession, getDeviceClass }; diff --git a/backend/src/models/db.js b/backend/src/models/db.js new file mode 100644 index 0000000..bafc87e --- /dev/null +++ b/backend/src/models/db.js @@ -0,0 +1,368 @@ +const Database = require('better-sqlite3-multiple-ciphers'); +const path = require('path'); +const fs = require('fs'); +const bcrypt = require('bcryptjs'); + +const DB_PATH = process.env.DB_PATH || '/app/data/jama.db'; +const DB_KEY = process.env.DB_KEY || ''; + +let db; + +function getDb() { + if (!db) { + // Ensure the data directory exists before opening the DB + const dir = path.dirname(DB_PATH); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + console.log(`[DB] Created data directory: ${dir}`); + } + db = new Database(DB_PATH); + if (DB_KEY) { + // Use SQLCipher4 AES-256-CBC — compatible with standard sqlcipher CLI and DB Browser + // Must be applied before any other DB access + const safeKey = DB_KEY.replace(/'/g, "''"); + db.pragma(`cipher='sqlcipher'`); + db.pragma(`legacy=4`); + db.pragma(`key='${safeKey}'`); + console.log('[DB] Encryption key applied (SQLCipher4)'); + } else { + console.warn('[DB] WARNING: DB_KEY not set — database is unencrypted'); + } + const journalMode = db.pragma('journal_mode = WAL', { simple: true }); + if (journalMode !== 'wal') { + console.warn(`[DB] WARNING: journal_mode is '${journalMode}', expected 'wal' — performance may be degraded`); + } + db.pragma('synchronous = NORMAL'); // safe with WAL, faster than FULL + db.pragma('cache_size = -8000'); // 8MB page cache + db.pragma('foreign_keys = ON'); + console.log(`[DB] Opened database at ${DB_PATH} (journal=${journalMode})`); + } + return db; +} + +function initDb() { + const db = getDb(); + + db.exec(` + CREATE TABLE IF NOT EXISTS users ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + email TEXT UNIQUE NOT NULL, + password TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'member', + status TEXT NOT NULL DEFAULT 'active', + is_default_admin INTEGER NOT NULL DEFAULT 0, + must_change_password INTEGER NOT NULL DEFAULT 1, + avatar TEXT, + about_me TEXT, + display_name TEXT, + hide_admin_tag INTEGER NOT NULL DEFAULT 0, + allow_dm INTEGER NOT NULL DEFAULT 1, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS groups ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + type TEXT NOT NULL DEFAULT 'public', + owner_id INTEGER, + is_default INTEGER NOT NULL DEFAULT 0, + is_readonly INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + updated_at TEXT NOT NULL DEFAULT (datetime('now')), + FOREIGN KEY (owner_id) REFERENCES users(id) + ); + + CREATE TABLE IF NOT EXISTS group_members ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + group_id INTEGER NOT NULL, + user_id INTEGER NOT NULL, + joined_at TEXT NOT NULL DEFAULT (datetime('now')), + UNIQUE(group_id, user_id), + FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ); + + CREATE TABLE IF NOT EXISTS messages ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + group_id INTEGER NOT NULL, + user_id INTEGER NOT NULL, + content TEXT, + type TEXT NOT NULL DEFAULT 'text', + image_url TEXT, + reply_to_id INTEGER, + is_deleted INTEGER NOT NULL DEFAULT 0, + link_preview TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE, + FOREIGN KEY (user_id) REFERENCES users(id), + FOREIGN KEY (reply_to_id) REFERENCES messages(id) + ); + + CREATE TABLE IF NOT EXISTS reactions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + message_id INTEGER NOT NULL, + user_id INTEGER NOT NULL, + emoji TEXT NOT NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + UNIQUE(message_id, user_id, emoji), + FOREIGN KEY (message_id) REFERENCES messages(id) ON DELETE CASCADE, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ); + + CREATE TABLE IF NOT EXISTS notifications ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + type TEXT NOT NULL, + message_id INTEGER, + group_id INTEGER, + from_user_id INTEGER, + is_read INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ); + + CREATE TABLE IF NOT EXISTS sessions ( + id TEXT PRIMARY KEY, + user_id INTEGER NOT NULL, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + expires_at TEXT NOT NULL, + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL DEFAULT (datetime('now')) + ); + + CREATE TABLE IF NOT EXISTS active_sessions ( + user_id INTEGER NOT NULL, + device TEXT NOT NULL DEFAULT 'desktop', + token TEXT NOT NULL, + ua TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY (user_id, device), + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ); + + CREATE TABLE IF NOT EXISTS push_subscriptions ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id INTEGER NOT NULL, + endpoint TEXT NOT NULL, + p256dh TEXT NOT NULL, + auth TEXT NOT NULL, + device TEXT NOT NULL DEFAULT 'desktop', + created_at TEXT NOT NULL DEFAULT (datetime('now')), + UNIQUE(user_id, device), + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ); + `); + + // Initialize default settings + const insertSetting = db.prepare('INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)'); + insertSetting.run('app_name', process.env.APP_NAME || 'jama'); + insertSetting.run('logo_url', ''); + insertSetting.run('pw_reset_active', process.env.ADMPW_RESET === 'true' ? 'true' : 'false'); + insertSetting.run('icon_newchat', ''); + insertSetting.run('icon_groupinfo', ''); + insertSetting.run('pwa_icon_192', ''); + insertSetting.run('pwa_icon_512', ''); + insertSetting.run('color_title', ''); + insertSetting.run('color_title_dark', ''); + insertSetting.run('color_avatar_public', ''); + insertSetting.run('color_avatar_dm', ''); + + // Migration: add hide_admin_tag if upgrading from older version + try { + db.exec("ALTER TABLE users ADD COLUMN hide_admin_tag INTEGER NOT NULL DEFAULT 0"); + console.log('[DB] Migration: added hide_admin_tag column'); + } catch (e) { /* column already exists */ } + + // Migration: add allow_dm if upgrading from older version + try { + db.exec("ALTER TABLE users ADD COLUMN allow_dm INTEGER NOT NULL DEFAULT 1"); + console.log('[DB] Migration: added allow_dm column'); + } catch (e) { /* column already exists */ } + + // Migration: replace single-session active_sessions with per-device version + try { + const cols = db.prepare("PRAGMA table_info(active_sessions)").all().map(c => c.name); + if (!cols.includes('device')) { + db.exec("DROP TABLE IF EXISTS active_sessions"); + db.exec(` + CREATE TABLE IF NOT EXISTS active_sessions ( + user_id INTEGER NOT NULL, + device TEXT NOT NULL DEFAULT 'desktop', + token TEXT NOT NULL, + ua TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY (user_id, device), + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ) + `); + console.log('[DB] Migration: rebuilt active_sessions for per-device sessions'); + } + } catch (e) { console.error('[DB] active_sessions migration error:', e.message); } + + // Migration: add is_direct for user-to-user direct messages + try { + db.exec("ALTER TABLE groups ADD COLUMN is_direct INTEGER NOT NULL DEFAULT 0"); + console.log('[DB] Migration: added is_direct column'); + } catch (e) { /* column already exists */ } + + // Migration: store both peer IDs so direct-message names survive member leave + try { + db.exec("ALTER TABLE groups ADD COLUMN direct_peer1_id INTEGER"); + console.log('[DB] Migration: added direct_peer1_id column'); + } catch (e) { /* column already exists */ } + try { + db.exec("ALTER TABLE groups ADD COLUMN direct_peer2_id INTEGER"); + console.log('[DB] Migration: added direct_peer2_id column'); + } catch (e) { /* column already exists */ } + + // Migration: last_online timestamp per user + try { + db.exec("ALTER TABLE users ADD COLUMN last_online TEXT"); + console.log('[DB] Migration: added last_online column'); + } catch (e) { /* column already exists */ } + + // Migration: help_dismissed preference per user + try { + db.exec("ALTER TABLE users ADD COLUMN help_dismissed INTEGER NOT NULL DEFAULT 0"); + console.log('[DB] Migration: added help_dismissed column'); + } catch (e) { /* column already exists */ } + + // Migration: user-customised group display names (per-user, per-group) + try { + db.exec(` + CREATE TABLE IF NOT EXISTS user_group_names ( + user_id INTEGER NOT NULL, + group_id INTEGER NOT NULL, + name TEXT NOT NULL, + PRIMARY KEY (user_id, group_id) + ) + `); + console.log('[DB] Migration: user_group_names table ready'); + } catch (e) { console.error('[DB] user_group_names migration error:', e.message); } + + // Migration: pinned conversations (per-user, pins a group to top of sidebar) + try { + db.exec(` + CREATE TABLE IF NOT EXISTS pinned_conversations ( + user_id INTEGER NOT NULL, + group_id INTEGER NOT NULL, + pinned_at TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY (user_id, group_id), + FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (group_id) REFERENCES groups(id) ON DELETE CASCADE + ) + `); + console.log('[DB] Migration: pinned_conversations table ready'); + } catch (e) { console.error('[DB] pinned_conversations migration error:', e.message); } + + console.log('[DB] Schema initialized'); + return db; +} + +function seedAdmin() { + const db = getDb(); + + // Strip any surrounding quotes from env vars (common docker-compose mistake) + const adminEmail = (process.env.ADMIN_EMAIL || 'admin@jama.local').replace(/^["']|["']$/g, '').trim(); + const adminName = (process.env.ADMIN_NAME || 'Admin User').replace(/^["']|["']$/g, '').trim(); + const adminPass = (process.env.ADMIN_PASS || 'Admin@1234').replace(/^["']|["']$/g, '').trim(); + const pwReset = process.env.ADMPW_RESET === 'true'; + + console.log(`[DB] Checking for default admin (${adminEmail})...`); + + const existing = db.prepare('SELECT * FROM users WHERE is_default_admin = 1').get(); + + if (!existing) { + try { + const hash = bcrypt.hashSync(adminPass, 10); + const result = db.prepare(` + INSERT INTO users (name, email, password, role, status, is_default_admin, must_change_password) + VALUES (?, ?, ?, 'admin', 'active', 1, 1) + `).run(adminName, adminEmail, hash); + + console.log(`[DB] Default admin created: ${adminEmail} (id=${result.lastInsertRowid})`); + + // Create default public group + const groupResult = db.prepare(` + INSERT INTO groups (name, type, is_default, owner_id) + VALUES (?, 'public', 1, ?) + `).run(process.env.DEFCHAT_NAME || 'General Chat', result.lastInsertRowid); + + // Add admin to default group + db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)') + .run(groupResult.lastInsertRowid, result.lastInsertRowid); + + console.log(`[DB] Default group created: ${process.env.DEFCHAT_NAME || 'General Chat'}`); + seedSupportGroup(); + } catch (err) { + console.error('[DB] ERROR creating default admin:', err.message); + } + return; + } + + console.log(`[DB] Default admin already exists (id=${existing.id})`); + + // Handle ADMPW_RESET + if (pwReset) { + const hash = bcrypt.hashSync(adminPass, 10); + db.prepare(` + UPDATE users SET password = ?, must_change_password = 1, updated_at = datetime('now') + WHERE is_default_admin = 1 + `).run(hash); + db.prepare("UPDATE settings SET value = 'true', updated_at = datetime('now') WHERE key = 'pw_reset_active'").run(); + console.log('[DB] Admin password reset via ADMPW_RESET=true'); + } else { + db.prepare("UPDATE settings SET value = 'false', updated_at = datetime('now') WHERE key = 'pw_reset_active'").run(); + } +} + +function addUserToPublicGroups(userId) { + const db = getDb(); + const publicGroups = db.prepare("SELECT id FROM groups WHERE type = 'public'").all(); + const insert = db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)'); + for (const g of publicGroups) { + insert.run(g.id, userId); + } +} + +function seedSupportGroup() { + const db = getDb(); + + // Create the Support group if it doesn't exist + const existing = db.prepare("SELECT id FROM groups WHERE name = 'Support' AND type = 'private'").get(); + if (existing) return existing.id; + + const admin = db.prepare('SELECT id FROM users WHERE is_default_admin = 1').get(); + if (!admin) return null; + + const result = db.prepare(` + INSERT INTO groups (name, type, owner_id, is_default) + VALUES ('Support', 'private', ?, 0) + `).run(admin.id); + + const groupId = result.lastInsertRowid; + + // Add all current admins to the Support group + const admins = db.prepare("SELECT id FROM users WHERE role = 'admin' AND status = 'active'").all(); + const insert = db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)'); + for (const a of admins) insert.run(groupId, a.id); + + console.log('[DB] Support group created'); + return groupId; +} + +function getOrCreateSupportGroup() { + const db = getDb(); + const group = db.prepare("SELECT id FROM groups WHERE name = 'Support' AND type = 'private'").get(); + if (group) return group.id; + return seedSupportGroup(); +} + +module.exports = { getDb, initDb, seedAdmin, seedSupportGroup, getOrCreateSupportGroup, addUserToPublicGroups }; diff --git a/backend/src/routes/about.js b/backend/src/routes/about.js new file mode 100644 index 0000000..3f77aeb --- /dev/null +++ b/backend/src/routes/about.js @@ -0,0 +1,43 @@ +const express = require('express'); +const router = express.Router(); +const fs = require('fs'); + +const ABOUT_FILE = '/app/data/about.json'; + +const DEFAULTS = { + built_with: 'Node.js · Express · Socket.io · SQLite · React · Vite · Claude.ai', + developer: 'Ricky Stretch', + license: 'AGPL 3.0', + license_url: 'https://www.gnu.org/licenses/agpl-3.0.html', + description: 'Self-hosted, privacy-first team messaging.', +}; + +// GET /api/about — public, no auth required +router.get('/', (req, res) => { + let overrides = {}; + try { + if (fs.existsSync(ABOUT_FILE)) { + const raw = fs.readFileSync(ABOUT_FILE, 'utf8'); + overrides = JSON.parse(raw); + } + } catch (e) { + console.warn('about.json parse error:', e.message); + } + + // Version always comes from the runtime env (same source as Settings window) + const about = { + ...DEFAULTS, + ...overrides, + version: process.env.JAMA_VERSION || process.env.TEAMCHAT_VERSION || 'dev', + // Always expose original app identity — not overrideable via about.json or settings + default_app_name: 'jama', + default_logo: '/icons/jama.png', + }; + + // Never expose docker_image — removed from UI + delete about.docker_image; + + res.json({ about }); +}); + +module.exports = router; diff --git a/backend/src/routes/auth.js b/backend/src/routes/auth.js new file mode 100644 index 0000000..388b0e7 --- /dev/null +++ b/backend/src/routes/auth.js @@ -0,0 +1,130 @@ +const express = require('express'); +const bcrypt = require('bcryptjs'); +const { getDb, getOrCreateSupportGroup } = require('../models/db'); +const { generateToken, authMiddleware, setActiveSession, clearActiveSession } = require('../middleware/auth'); + +module.exports = function(io) { +const router = express.Router(); + +// Login +router.post('/login', (req, res) => { + const { email, password, rememberMe } = req.body; + const db = getDb(); + + const user = db.prepare('SELECT * FROM users WHERE email = ?').get(email); + if (!user) return res.status(401).json({ error: 'Invalid credentials' }); + + if (user.status === 'suspended') { + const adminUser = db.prepare('SELECT email FROM users WHERE is_default_admin = 1').get(); + return res.status(403).json({ + error: 'suspended', + adminEmail: adminUser?.email + }); + } + if (user.status === 'deleted') return res.status(403).json({ error: 'Account not found' }); + + const valid = bcrypt.compareSync(password, user.password); + if (!valid) return res.status(401).json({ error: 'Invalid credentials' }); + + const token = generateToken(user.id); + const ua = req.headers['user-agent'] || ''; + const device = setActiveSession(user.id, token, ua); // displaces prior session on same device class + // Kick any live socket on the same device class — it now holds a stale token + if (io) { + io.to(`user:${user.id}`).emit('session:displaced', { device }); + } + + const { password: _, ...userSafe } = user; + res.json({ + token, + user: userSafe, + mustChangePassword: !!user.must_change_password, + rememberMe: !!rememberMe + }); +}); + +// Change password +router.post('/change-password', authMiddleware, (req, res) => { + const { currentPassword, newPassword } = req.body; + const db = getDb(); + const user = db.prepare('SELECT * FROM users WHERE id = ?').get(req.user.id); + + if (!bcrypt.compareSync(currentPassword, user.password)) { + return res.status(400).json({ error: 'Current password is incorrect' }); + } + if (newPassword.length < 8) return res.status(400).json({ error: 'Password must be at least 8 characters' }); + + const hash = bcrypt.hashSync(newPassword, 10); + db.prepare("UPDATE users SET password = ?, must_change_password = 0, updated_at = datetime('now') WHERE id = ?").run(hash, req.user.id); + + res.json({ success: true }); +}); + +// Get current user +router.get('/me', authMiddleware, (req, res) => { + const { password, ...user } = req.user; + res.json({ user }); +}); + +// Logout — clear active session for this device class only +router.post('/logout', authMiddleware, (req, res) => { + clearActiveSession(req.user.id, req.device); + res.json({ success: true }); +}); + +// Public support contact form — no auth required +router.post('/support', (req, res) => { + const { name, email, message } = req.body; + if (!name?.trim() || !email?.trim() || !message?.trim()) { + return res.status(400).json({ error: 'All fields are required' }); + } + if (message.trim().length > 2000) { + return res.status(400).json({ error: 'Message too long (max 2000 characters)' }); + } + + const db = getDb(); + + // Get or create the Support group + const groupId = getOrCreateSupportGroup(); + if (!groupId) return res.status(500).json({ error: 'Support group unavailable' }); + + // Find a system/admin user to post as (default admin) + const admin = db.prepare('SELECT id FROM users WHERE is_default_admin = 1').get(); + if (!admin) return res.status(500).json({ error: 'No admin configured' }); + + // Format the support message + const content = `📬 **Support Request** +**Name:** ${name.trim()} +**Email:** ${email.trim()} + +${message.trim()}`; + + const msgResult = db.prepare(` + INSERT INTO messages (group_id, user_id, content, type) + VALUES (?, ?, ?, 'text') + `).run(groupId, admin.id, content); + + // Emit socket event so online admins see the message immediately + const newMsg = db.prepare(` + SELECT m.*, u.name as user_name, u.display_name as user_display_name, u.avatar as user_avatar + FROM messages m JOIN users u ON m.user_id = u.id + WHERE m.id = ? + `).get(msgResult.lastInsertRowid); + + if (newMsg) { + newMsg.reactions = []; + io.to(`group:${groupId}`).emit('message:new', newMsg); + } + + // Notify each admin via their user channel so they can reload groups if needed + const admins = db.prepare("SELECT id FROM users WHERE role = 'admin' AND status = 'active'").all(); + for (const a of admins) { + io.to(`user:${a.id}`).emit('notification:new', { type: 'support', groupId }); + } + + console.log(`[Support] Message from ${email} posted to Support group`); + res.json({ success: true }); +}); + + return router; +}; diff --git a/backend/src/routes/groups.js b/backend/src/routes/groups.js new file mode 100644 index 0000000..f564051 --- /dev/null +++ b/backend/src/routes/groups.js @@ -0,0 +1,422 @@ +const express = require('express'); +const fs = require('fs'); +const router = express.Router(); +const { getDb } = require('../models/db'); +const { authMiddleware, adminMiddleware } = require('../middleware/auth'); + +// Helper: emit group:new to all members of a group +function emitGroupNew(io, groupId) { + const db = getDb(); + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(groupId); + if (!group) return; + if (group.type === 'public') { + io.emit('group:new', { group }); + } else { + const members = db.prepare('SELECT user_id FROM group_members WHERE group_id = ?').all(groupId); + for (const m of members) { + io.to(`user:${m.user_id}`).emit('group:new', { group }); + } + } +} + +// Delete an uploaded image file from disk +function deleteImageFile(imageUrl) { + if (!imageUrl) return; + try { + const filePath = '/app' + imageUrl; + if (fs.existsSync(filePath)) fs.unlinkSync(filePath); + } catch (e) { + console.warn('[Groups] Could not delete image file:', e.message); + } +} + +// Helper: emit group:deleted to all members +function emitGroupDeleted(io, groupId, members) { + for (const uid of members) { + io.to(`user:${uid}`).emit('group:deleted', { groupId }); + } +} + +// Helper: emit group:updated to all members +function emitGroupUpdated(io, groupId) { + const db = getDb(); + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(groupId); + if (!group) return; + const members = db.prepare('SELECT user_id FROM group_members WHERE group_id = ?').all(groupId); + const uids = group.type === 'public' + ? db.prepare("SELECT id as user_id FROM users WHERE status = 'active'").all() + : members; + for (const m of uids) { + io.to(`user:${m.user_id}`).emit('group:updated', { group }); + } +} + +// Inject io into routes + +module.exports = (io) => { + +// Get all groups for current user +router.get('/', authMiddleware, (req, res) => { + const db = getDb(); + const userId = req.user.id; + + const publicGroups = db.prepare(` + SELECT g.*, + (SELECT COUNT(*) FROM messages m WHERE m.group_id = g.id AND m.is_deleted = 0) as message_count, + (SELECT m.content FROM messages m WHERE m.group_id = g.id AND m.is_deleted = 0 ORDER BY m.created_at DESC LIMIT 1) as last_message, + (SELECT m.created_at FROM messages m WHERE m.group_id = g.id AND m.is_deleted = 0 ORDER BY m.created_at DESC LIMIT 1) as last_message_at, + (SELECT m.user_id FROM messages m WHERE m.group_id = g.id AND m.is_deleted = 0 ORDER BY m.created_at DESC LIMIT 1) as last_message_user_id + FROM groups g + WHERE g.type = 'public' + ORDER BY g.is_default DESC, g.name ASC + `).all(); + + // For direct messages, replace name with opposite user's display name + const privateGroupsRaw = db.prepare(` + SELECT g.*, + u.name as owner_name, + (SELECT COUNT(*) FROM messages m WHERE m.group_id = g.id AND m.is_deleted = 0) as message_count, + (SELECT m.content FROM messages m WHERE m.group_id = g.id AND m.is_deleted = 0 ORDER BY m.created_at DESC LIMIT 1) as last_message, + (SELECT m.created_at FROM messages m WHERE m.group_id = g.id AND m.is_deleted = 0 ORDER BY m.created_at DESC LIMIT 1) as last_message_at, + (SELECT m.user_id FROM messages m WHERE m.group_id = g.id AND m.is_deleted = 0 ORDER BY m.created_at DESC LIMIT 1) as last_message_user_id + FROM groups g + JOIN group_members gm ON g.id = gm.group_id AND gm.user_id = ? + LEFT JOIN users u ON g.owner_id = u.id + WHERE g.type = 'private' + ORDER BY last_message_at DESC NULLS LAST + `).all(userId); + + // For direct groups, set the name to the other user's display name + // Uses direct_peer1_id / direct_peer2_id so the name survives after a user leaves + const privateGroups = privateGroupsRaw.map(g => { + if (g.is_direct) { + // Backfill peer IDs for groups created before this migration + if (!g.direct_peer1_id || !g.direct_peer2_id) { + const peers = db.prepare('SELECT user_id FROM group_members WHERE group_id = ? LIMIT 2').all(g.id); + if (peers.length === 2) { + db.prepare('UPDATE groups SET direct_peer1_id = ?, direct_peer2_id = ? WHERE id = ?') + .run(peers[0].user_id, peers[1].user_id, g.id); + g.direct_peer1_id = peers[0].user_id; + g.direct_peer2_id = peers[1].user_id; + } + } + const otherUserId = g.direct_peer1_id === userId ? g.direct_peer2_id : g.direct_peer1_id; + if (otherUserId) { + const other = db.prepare('SELECT display_name, name, avatar FROM users WHERE id = ?').get(otherUserId); + if (other) { + g.peer_id = otherUserId; + g.peer_real_name = other.name; + g.peer_display_name = other.display_name || null; // null if no custom display name set + g.peer_avatar = other.avatar || null; + g.name = other.display_name || other.name; + } + } + } + // Apply user's custom group name if set + const custom = db.prepare('SELECT name FROM user_group_names WHERE user_id = ? AND group_id = ?').get(userId, g.id); + if (custom) { + g.owner_name_original = g.name; // original name shown in brackets in GroupInfoModal + g.name = custom.name; + } + return g; + }); + + res.json({ publicGroups, privateGroups }); +}); + +// Create group +router.post('/', authMiddleware, (req, res) => { + const { name, type, memberIds, isReadonly, isDirect } = req.body; + const db = getDb(); + + if (type === 'public' && req.user.role !== 'admin') { + return res.status(403).json({ error: 'Only admins can create public groups' }); + } + + // Direct message: find or create + if (isDirect && memberIds && memberIds.length === 1) { + const otherUserId = memberIds[0]; + const userId = req.user.id; + + // Check if a direct group already exists between these two users + const existing = db.prepare(` + SELECT g.id FROM groups g + JOIN group_members gm1 ON gm1.group_id = g.id AND gm1.user_id = ? + JOIN group_members gm2 ON gm2.group_id = g.id AND gm2.user_id = ? + WHERE g.is_direct = 1 + LIMIT 1 + `).get(userId, otherUserId); + + if (existing) { + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(existing.id); + // Ensure current user is still a member (may have left) + db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)').run(existing.id, userId); + // Re-set readonly to false so both can post again + db.prepare("UPDATE groups SET is_readonly = 0, owner_id = NULL, updated_at = datetime('now') WHERE id = ?").run(existing.id); + return res.json({ group: db.prepare('SELECT * FROM groups WHERE id = ?').get(existing.id) }); + } + + // Get other user's display name for the group name (stored internally, overridden per-user on fetch) + const otherUser = db.prepare('SELECT name, display_name FROM users WHERE id = ?').get(otherUserId); + const dmName = (otherUser?.display_name || otherUser?.name) + ' ↔ ' + (req.user.display_name || req.user.name); + + const result = db.prepare(` + INSERT INTO groups (name, type, owner_id, is_readonly, is_direct, direct_peer1_id, direct_peer2_id) + VALUES (?, 'private', NULL, 0, 1, ?, ?) + `).run(dmName, userId, otherUserId); + + const groupId = result.lastInsertRowid; + db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)').run(groupId, userId); + db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)').run(groupId, otherUserId); + + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(groupId); + + // Notify both users via socket + emitGroupNew(io, groupId); + + return res.json({ group }); + } + + // For private groups: check if exact same set of members already exists in a group + if ((type === 'private' || !type) && !isDirect && memberIds && memberIds.length > 0) { + const allMemberIds = [...new Set([req.user.id, ...memberIds])].sort((a, b) => a - b); + const count = allMemberIds.length; + + // Find all private non-direct groups where the creator is a member + const candidates = db.prepare(` + SELECT g.id FROM groups g + JOIN group_members gm ON gm.group_id = g.id AND gm.user_id = ? + WHERE g.type = 'private' AND g.is_direct = 0 + `).all(req.user.id); + + for (const candidate of candidates) { + const members = db.prepare( + 'SELECT user_id FROM group_members WHERE group_id = ? ORDER BY user_id' + ).all(candidate.id).map(r => r.user_id); + if (members.length === count && + members.every((id, i) => id === allMemberIds[i])) { + // Exact duplicate found — return the existing group + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(candidate.id); + return res.json({ group, duplicate: true }); + } + } + } + + const result = db.prepare(` + INSERT INTO groups (name, type, owner_id, is_readonly, is_direct) + VALUES (?, ?, ?, ?, 0) + `).run(name, type || 'private', req.user.id, isReadonly ? 1 : 0); + + const groupId = result.lastInsertRowid; + + if (type === 'public') { + const allUsers = db.prepare("SELECT id FROM users WHERE status = 'active'").all(); + const insert = db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)'); + for (const u of allUsers) insert.run(groupId, u.id); + } else { + db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)').run(groupId, req.user.id); + if (memberIds && memberIds.length > 0) { + const insert = db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)'); + for (const uid of memberIds) insert.run(groupId, uid); + } + } + + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(groupId); + + // Notify all members via socket + emitGroupNew(io, groupId); + + res.json({ group }); +}); + +// Rename group +router.patch('/:id/rename', authMiddleware, (req, res) => { + const { name } = req.body; + const db = getDb(); + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(req.params.id); + if (!group) return res.status(404).json({ error: 'Group not found' }); + if (group.is_default) return res.status(403).json({ error: 'Cannot rename default group' }); + if (group.is_direct) return res.status(403).json({ error: 'Cannot rename a direct message' }); + if (group.type === 'public' && req.user.role !== 'admin') return res.status(403).json({ error: 'Only admins can rename public groups' }); + if (group.type === 'private' && group.owner_id !== req.user.id && req.user.role !== 'admin') { + return res.status(403).json({ error: 'Only owner can rename private group' }); + } + db.prepare("UPDATE groups SET name = ?, updated_at = datetime('now') WHERE id = ?").run(name, group.id); + emitGroupUpdated(io, group.id); + res.json({ success: true }); +}); + +// Get group members +router.get('/:id/members', authMiddleware, (req, res) => { + const db = getDb(); + const members = db.prepare(` + SELECT u.id, u.name, u.display_name, u.avatar, u.role, u.status + FROM group_members gm + JOIN users u ON gm.user_id = u.id + WHERE gm.group_id = ? + ORDER BY u.name ASC + `).all(req.params.id); + res.json({ members }); +}); + +// Add member to private group +router.post('/:id/members', authMiddleware, (req, res) => { + const { userId } = req.body; + const db = getDb(); + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(req.params.id); + if (!group) return res.status(404).json({ error: 'Group not found' }); + if (group.type !== 'private') return res.status(400).json({ error: 'Cannot manually add members to public groups' }); + if (group.is_direct) return res.status(400).json({ error: 'Cannot add members to a direct message' }); + if (group.owner_id !== req.user.id && req.user.role !== 'admin') { + return res.status(403).json({ error: 'Only owner can add members' }); + } + db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)').run(group.id, userId); + + // Post a system message so all members see who was added + const addedUser = db.prepare('SELECT name, display_name FROM users WHERE id = ?').get(userId); + const addedName = addedUser?.display_name || addedUser?.name || 'Unknown'; + const sysResult = db.prepare(` + INSERT INTO messages (group_id, user_id, content, type) + VALUES (?, ?, ?, 'system') + `).run(group.id, userId, `${addedName} has joined the conversation.`); + const sysMsg = db.prepare(` + SELECT m.*, u.name as user_name, u.display_name as user_display_name, + u.avatar as user_avatar, u.role as user_role, u.status as user_status, + u.hide_admin_tag as user_hide_admin_tag, u.about_me as user_about_me + FROM messages m JOIN users u ON m.user_id = u.id WHERE m.id = ? + `).get(sysResult.lastInsertRowid); + sysMsg.reactions = []; + io.to(`group:${group.id}`).emit('message:new', sysMsg); + + // Join all of the added user's active sockets to the group room server-side, + // so they receive messages immediately without needing a client round-trip + io.in(`user:${userId}`).socketsJoin(`group:${group.id}`); + // Notify the added user in real-time so their sidebar updates without a refresh + io.to(`user:${userId}`).emit('group:new', { group }); + res.json({ success: true }); +}); + +// Remove a member from a private group +router.delete('/:id/members/:userId', authMiddleware, (req, res) => { + const db = getDb(); + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(req.params.id); + if (!group) return res.status(404).json({ error: 'Group not found' }); + if (group.type !== 'private') return res.status(400).json({ error: 'Cannot remove members from public groups' }); + if (group.owner_id !== req.user.id && req.user.role !== 'admin') { + return res.status(403).json({ error: 'Only owner or admin can remove members' }); + } + const targetId = parseInt(req.params.userId); + if (targetId === group.owner_id) return res.status(400).json({ error: 'Cannot remove the group owner' }); + db.prepare('DELETE FROM group_members WHERE group_id = ? AND user_id = ?').run(group.id, targetId); + res.json({ success: true }); +}); + +// Leave private group +router.delete('/:id/leave', authMiddleware, (req, res) => { + const db = getDb(); + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(req.params.id); + if (!group) return res.status(404).json({ error: 'Group not found' }); + if (group.type === 'public') return res.status(400).json({ error: 'Cannot leave public groups' }); + + const userId = req.user.id; + const leaverName = req.user.display_name || req.user.name; + + db.prepare('DELETE FROM group_members WHERE group_id = ? AND user_id = ?').run(group.id, userId); + + // Post a system message so remaining members see the leave notice + const sysResult = db.prepare(` + INSERT INTO messages (group_id, user_id, content, type) + VALUES (?, ?, ?, 'system') + `).run(group.id, userId, `${leaverName} has left the conversation.`); + + const sysMsg = db.prepare(` + SELECT m.*, u.name as user_name, u.display_name as user_display_name, + u.avatar as user_avatar, u.role as user_role, u.status as user_status, + u.hide_admin_tag as user_hide_admin_tag, u.about_me as user_about_me + FROM messages m JOIN users u ON m.user_id = u.id WHERE m.id = ? + `).get(sysResult.lastInsertRowid); + sysMsg.reactions = []; + + // Broadcast to remaining members in the group room + io.to(`group:${group.id}`).emit('message:new', sysMsg); + + if (group.is_direct) { + // Make remaining user owner so they can still manage the conversation + const remaining = db.prepare('SELECT user_id FROM group_members WHERE group_id = ? LIMIT 1').get(group.id); + if (remaining) { + db.prepare("UPDATE groups SET owner_id = ?, updated_at = datetime('now') WHERE id = ?") + .run(remaining.user_id, group.id); + } + // Tell the leaver's socket to leave the group room and remove from sidebar + io.to(`user:${userId}`).emit('group:deleted', { groupId: group.id }); + } + + res.json({ success: true }); +}); + +// Admin take ownership +router.post('/:id/take-ownership', authMiddleware, adminMiddleware, (req, res) => { + const db = getDb(); + db.prepare("UPDATE groups SET owner_id = ?, updated_at = datetime('now') WHERE id = ?").run(req.user.id, req.params.id); + db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)').run(req.params.id, req.user.id); + res.json({ success: true }); +}); + +// Delete group +router.delete('/:id', authMiddleware, (req, res) => { + const db = getDb(); + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(req.params.id); + if (!group) return res.status(404).json({ error: 'Group not found' }); + if (group.is_default) return res.status(403).json({ error: 'Cannot delete default group' }); + if (group.type === 'public' && req.user.role !== 'admin') return res.status(403).json({ error: 'Only admins can delete public groups' }); + if (group.type === 'private' && group.owner_id !== req.user.id && req.user.role !== 'admin') { + return res.status(403).json({ error: 'Only owner or admin can delete private groups' }); + } + + // Collect members before deleting + const members = db.prepare('SELECT user_id FROM group_members WHERE group_id = ?').all(group.id).map(m => m.user_id); + // Add all active users for public groups + if (group.type === 'public') { + const all = db.prepare("SELECT id FROM users WHERE status = 'active'").all(); + all.forEach(u => { if (!members.includes(u.id)) members.push(u.id); }); + } + + // Collect all image files for this group before deleting + const imageMessages = db.prepare("SELECT image_url FROM messages WHERE group_id = ? AND image_url IS NOT NULL").all(group.id); + + db.prepare('DELETE FROM groups WHERE id = ?').run(group.id); + + // Delete image files from disk after DB delete + for (const msg of imageMessages) deleteImageFile(msg.image_url); + + // Notify all affected users + emitGroupDeleted(io, group.id, members); + + res.json({ success: true }); +}); + + +// Set or update user's custom name for a group +router.patch('/:id/custom-name', authMiddleware, (req, res) => { + const db = getDb(); + const groupId = parseInt(req.params.id); + const userId = req.user.id; + const { name } = req.body; + + if (!name || !name.trim()) { + // Empty name = remove custom name (revert to owner name) + db.prepare('DELETE FROM user_group_names WHERE user_id = ? AND group_id = ?').run(userId, groupId); + return res.json({ success: true, name: null }); + } + + db.prepare(` + INSERT INTO user_group_names (user_id, group_id, name) + VALUES (?, ?, ?) + ON CONFLICT(user_id, group_id) DO UPDATE SET name = excluded.name + `).run(userId, groupId, name.trim()); + + res.json({ success: true, name: name.trim() }); +}); + +return router; +}; \ No newline at end of file diff --git a/backend/src/routes/help.js b/backend/src/routes/help.js new file mode 100644 index 0000000..0e30bce --- /dev/null +++ b/backend/src/routes/help.js @@ -0,0 +1,40 @@ +const express = require('express'); +const router = express.Router(); +const fs = require('fs'); +const path = require('path'); +const { getDb } = require('../models/db'); +const { authMiddleware } = require('../middleware/auth'); + +// help.md lives inside the backend source tree — NOT in /app/data which is +// volume-mounted and would hide files baked into the image at build time. +const HELP_FILE = path.join(__dirname, '../data/help.md'); + +// GET /api/help — returns markdown content +router.get('/', authMiddleware, (req, res) => { + let content = ''; + const filePath = HELP_FILE; + try { + content = fs.readFileSync(filePath, 'utf8'); + } catch (e) { + content = '# Getting Started\n\nHelp content is not available yet.'; + } + res.json({ content }); +}); + +// GET /api/help/status — returns whether user has dismissed help +router.get('/status', authMiddleware, (req, res) => { + const db = getDb(); + const user = db.prepare('SELECT help_dismissed FROM users WHERE id = ?').get(req.user.id); + res.json({ dismissed: !!user?.help_dismissed }); +}); + +// POST /api/help/dismiss — set help_dismissed for current user +router.post('/dismiss', authMiddleware, (req, res) => { + const { dismissed } = req.body; + const db = getDb(); + db.prepare("UPDATE users SET help_dismissed = ? WHERE id = ?") + .run(dismissed ? 1 : 0, req.user.id); + res.json({ success: true }); +}); + +module.exports = router; diff --git a/backend/src/routes/messages.js b/backend/src/routes/messages.js new file mode 100644 index 0000000..4b7fb96 --- /dev/null +++ b/backend/src/routes/messages.js @@ -0,0 +1,202 @@ +const express = require('express'); +const multer = require('multer'); +const path = require('path'); +const fs = require('fs'); +const { getDb } = require('../models/db'); + +// Delete an uploaded image file from disk if it lives under /app/uploads/images +function deleteImageFile(imageUrl) { + if (!imageUrl) return; + try { + const filePath = '/app' + imageUrl; // imageUrl is like /uploads/images/img_xxx.jpg + if (fs.existsSync(filePath)) fs.unlinkSync(filePath); + } catch (e) { + console.warn('[Messages] Could not delete image file:', e.message); + } +} + +module.exports = function(io) { +const router = express.Router(); +const { authMiddleware } = require('../middleware/auth'); + +const imgStorage = multer.diskStorage({ + destination: '/app/uploads/images', + filename: (req, file, cb) => { + const ext = path.extname(file.originalname); + cb(null, `img_${Date.now()}_${Math.random().toString(36).substr(2, 6)}${ext}`); + } +}); +const uploadImage = multer({ + storage: imgStorage, + limits: { fileSize: 10 * 1024 * 1024 }, + fileFilter: (req, file, cb) => { + if (file.mimetype.startsWith('image/')) cb(null, true); + else cb(new Error('Images only')); + } +}); + +function getUserForMessage(db, userId) { + return db.prepare('SELECT id, name, display_name, avatar, role, status FROM users WHERE id = ?').get(userId); +} + +function canAccessGroup(db, groupId, userId) { + const group = db.prepare('SELECT * FROM groups WHERE id = ?').get(groupId); + if (!group) return null; + if (group.type === 'public') return group; + const member = db.prepare('SELECT id FROM group_members WHERE group_id = ? AND user_id = ?').get(groupId, userId); + if (!member) return null; + return group; +} + +// Get messages for group +router.get('/group/:groupId', authMiddleware, (req, res) => { + const db = getDb(); + const group = canAccessGroup(db, req.params.groupId, req.user.id); + if (!group) return res.status(403).json({ error: 'Access denied' }); + + const { before, limit = 50 } = req.query; + let query = ` + SELECT m.*, + u.name as user_name, u.display_name as user_display_name, u.avatar as user_avatar, u.role as user_role, u.status as user_status, u.hide_admin_tag as user_hide_admin_tag, u.about_me as user_about_me, u.allow_dm as user_allow_dm, + rm.content as reply_content, rm.image_url as reply_image_url, + ru.name as reply_user_name, ru.display_name as reply_user_display_name, + rm.is_deleted as reply_is_deleted + FROM messages m + JOIN users u ON m.user_id = u.id + LEFT JOIN messages rm ON m.reply_to_id = rm.id + LEFT JOIN users ru ON rm.user_id = ru.id + WHERE m.group_id = ? + `; + const params = [req.params.groupId]; + + if (before) { + query += ' AND m.id < ?'; + params.push(before); + } + + query += ' ORDER BY m.created_at DESC LIMIT ?'; + params.push(parseInt(limit)); + + const messages = db.prepare(query).all(...params); + + // Get reactions for these messages + for (const msg of messages) { + msg.reactions = db.prepare(` + SELECT r.emoji, r.user_id, u.name as user_name + FROM reactions r JOIN users u ON r.user_id = u.id + WHERE r.message_id = ? + `).all(msg.id); + } + + res.json({ messages: messages.reverse() }); +}); + +// Send message +router.post('/group/:groupId', authMiddleware, (req, res) => { + const db = getDb(); + const group = canAccessGroup(db, req.params.groupId, req.user.id); + if (!group) return res.status(403).json({ error: 'Access denied' }); + if (group.is_readonly && req.user.role !== 'admin') return res.status(403).json({ error: 'This group is read-only' }); + + const { content, replyToId, linkPreview } = req.body; + if (!content?.trim() && !req.body.imageUrl) return res.status(400).json({ error: 'Message cannot be empty' }); + + const result = db.prepare(` + INSERT INTO messages (group_id, user_id, content, reply_to_id, link_preview) + VALUES (?, ?, ?, ?, ?) + `).run(req.params.groupId, req.user.id, content?.trim() || null, replyToId || null, linkPreview ? JSON.stringify(linkPreview) : null); + + const message = db.prepare(` + SELECT m.*, + u.name as user_name, u.display_name as user_display_name, u.avatar as user_avatar, u.role as user_role, u.allow_dm as user_allow_dm, + rm.content as reply_content, ru.name as reply_user_name, ru.display_name as reply_user_display_name + FROM messages m + JOIN users u ON m.user_id = u.id + LEFT JOIN messages rm ON m.reply_to_id = rm.id + LEFT JOIN users ru ON rm.user_id = ru.id + WHERE m.id = ? + `).get(result.lastInsertRowid); + + message.reactions = []; + io.to(`group:${req.params.groupId}`).emit('message:new', message); + res.json({ message }); +}); + +// Upload image message +router.post('/group/:groupId/image', authMiddleware, uploadImage.single('image'), (req, res) => { + const db = getDb(); + const group = canAccessGroup(db, req.params.groupId, req.user.id); + if (!group) return res.status(403).json({ error: 'Access denied' }); + if (group.is_readonly && req.user.role !== 'admin') return res.status(403).json({ error: 'Read-only group' }); + if (!req.file) return res.status(400).json({ error: 'No image' }); + + const imageUrl = `/uploads/images/${req.file.filename}`; + const { content, replyToId } = req.body; + + const result = db.prepare(` + INSERT INTO messages (group_id, user_id, content, image_url, type, reply_to_id) + VALUES (?, ?, ?, ?, 'image', ?) + `).run(req.params.groupId, req.user.id, content || null, imageUrl, replyToId || null); + + const message = db.prepare(` + SELECT m.*, + u.name as user_name, u.display_name as user_display_name, u.avatar as user_avatar, u.role as user_role, u.allow_dm as user_allow_dm + FROM messages m JOIN users u ON m.user_id = u.id + WHERE m.id = ? + `).get(result.lastInsertRowid); + + message.reactions = []; + io.to(`group:${req.params.groupId}`).emit('message:new', message); + res.json({ message }); +}); + +// Delete message +router.delete('/:id', authMiddleware, (req, res) => { + const db = getDb(); + const message = db.prepare('SELECT m.*, g.type as group_type, g.owner_id as group_owner_id, g.is_readonly FROM messages m JOIN groups g ON m.group_id = g.id WHERE m.id = ?').get(req.params.id); + if (!message) return res.status(404).json({ error: 'Message not found' }); + + const canDelete = message.user_id === req.user.id || + req.user.role === 'admin' || + (message.group_type === 'private' && message.group_owner_id === req.user.id); + + if (!canDelete) return res.status(403).json({ error: 'Cannot delete this message' }); + + const imageUrl = message.image_url; + db.prepare("UPDATE messages SET is_deleted = 1, content = null, image_url = null WHERE id = ?").run(message.id); + deleteImageFile(imageUrl); + io.to(`group:${message.group_id}`).emit('message:deleted', { messageId: message.id, groupId: message.group_id }); + res.json({ success: true, messageId: message.id }); +}); + +// Add/toggle reaction +router.post('/:id/reactions', authMiddleware, (req, res) => { + const { emoji } = req.body; + const db = getDb(); + const message = db.prepare('SELECT * FROM messages WHERE id = ? AND is_deleted = 0').get(req.params.id); + if (!message) return res.status(404).json({ error: 'Message not found' }); + + // Check if user's message is from deleted/suspended user + const msgUser = db.prepare('SELECT status FROM users WHERE id = ?').get(message.user_id); + if (msgUser.status !== 'active') return res.status(400).json({ error: 'Cannot react to this message' }); + + const existing = db.prepare('SELECT * FROM reactions WHERE message_id = ? AND user_id = ? AND emoji = ?').get(message.id, req.user.id, emoji); + + if (existing) { + db.prepare('DELETE FROM reactions WHERE id = ?').run(existing.id); + } else { + db.prepare('INSERT INTO reactions (message_id, user_id, emoji) VALUES (?, ?, ?)').run(message.id, req.user.id, emoji); + } + + const reactions = db.prepare(` + SELECT r.emoji, r.user_id, u.name as user_name + FROM reactions r JOIN users u ON r.user_id = u.id + WHERE r.message_id = ? + `).all(message.id); + io.to(`group:${message.group_id}`).emit('reaction:updated', { messageId: message.id, reactions }); + res.json({ reactions }); +}); + + +return router; +}; diff --git a/backend/src/routes/push.js b/backend/src/routes/push.js new file mode 100644 index 0000000..76010ab --- /dev/null +++ b/backend/src/routes/push.js @@ -0,0 +1,104 @@ +const express = require('express'); +const webpush = require('web-push'); +const router = express.Router(); +const { getDb } = require('../models/db'); +const { authMiddleware } = require('../middleware/auth'); + +// Get or generate VAPID keys stored in settings +function getVapidKeys() { + const db = getDb(); + let pub = db.prepare("SELECT value FROM settings WHERE key = 'vapid_public'").get(); + let priv = db.prepare("SELECT value FROM settings WHERE key = 'vapid_private'").get(); + + if (!pub?.value || !priv?.value) { + const keys = webpush.generateVAPIDKeys(); + const ins = db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = ?"); + ins.run('vapid_public', keys.publicKey, keys.publicKey); + ins.run('vapid_private', keys.privateKey, keys.privateKey); + console.log('[Push] Generated new VAPID keys'); + return keys; + } + return { publicKey: pub.value, privateKey: priv.value }; +} + +function initWebPush() { + const keys = getVapidKeys(); + webpush.setVapidDetails( + 'mailto:admin@jama.local', + keys.publicKey, + keys.privateKey + ); + return keys.publicKey; +} + +// Export for use in index.js +let vapidPublicKey = null; +function getVapidPublicKey() { + if (!vapidPublicKey) vapidPublicKey = initWebPush(); + return vapidPublicKey; +} + +// Send a push notification to all subscriptions for a user +async function sendPushToUser(userId, payload) { + const db = getDb(); + getVapidPublicKey(); // ensure webpush is configured + const subs = db.prepare('SELECT * FROM push_subscriptions WHERE user_id = ?').all(userId); + for (const sub of subs) { + try { + await webpush.sendNotification( + { endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } }, + JSON.stringify(payload) + ); + } catch (err) { + if (err.statusCode === 410 || err.statusCode === 404) { + // Subscription expired — remove it + db.prepare('DELETE FROM push_subscriptions WHERE id = ?').run(sub.id); + } + } + } +} + +// GET /api/push/vapid-public — returns VAPID public key for client subscription +router.get('/vapid-public', (req, res) => { + res.json({ publicKey: getVapidPublicKey() }); +}); + +// POST /api/push/subscribe — save push subscription for current user +router.post('/subscribe', authMiddleware, (req, res) => { + const { endpoint, keys } = req.body; + if (!endpoint || !keys?.p256dh || !keys?.auth) { + return res.status(400).json({ error: 'Invalid subscription' }); + } + const db = getDb(); + const device = req.device || 'desktop'; + // Delete any existing subscription for this user+device or this endpoint, then insert fresh + db.prepare('DELETE FROM push_subscriptions WHERE endpoint = ? OR (user_id = ? AND device = ?)').run(endpoint, req.user.id, device); + db.prepare('INSERT INTO push_subscriptions (user_id, device, endpoint, p256dh, auth) VALUES (?, ?, ?, ?, ?)').run(req.user.id, device, endpoint, keys.p256dh, keys.auth); + res.json({ success: true }); +}); + +// POST /api/push/generate-vapid — admin: generate (or regenerate) VAPID keys +router.post('/generate-vapid', authMiddleware, (req, res) => { + if (req.user.role !== 'admin') return res.status(403).json({ error: 'Admins only' }); + const db = getDb(); + const keys = webpush.generateVAPIDKeys(); + const ins = db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = ?"); + ins.run('vapid_public', keys.publicKey, keys.publicKey); + ins.run('vapid_private', keys.privateKey, keys.privateKey); + // Reinitialise webpush with new keys immediately + webpush.setVapidDetails('mailto:admin@jama.local', keys.publicKey, keys.privateKey); + vapidPublicKey = keys.publicKey; + console.log('[Push] VAPID keys regenerated by admin'); + res.json({ publicKey: keys.publicKey }); +}); + +// POST /api/push/unsubscribe — remove subscription +router.post('/unsubscribe', authMiddleware, (req, res) => { + const { endpoint } = req.body; + if (!endpoint) return res.status(400).json({ error: 'Endpoint required' }); + const db = getDb(); + db.prepare('DELETE FROM push_subscriptions WHERE user_id = ? AND endpoint = ?').run(req.user.id, endpoint); + res.json({ success: true }); +}); + +module.exports = { router, sendPushToUser, getVapidPublicKey }; diff --git a/backend/src/routes/settings.js b/backend/src/routes/settings.js new file mode 100644 index 0000000..d418aba --- /dev/null +++ b/backend/src/routes/settings.js @@ -0,0 +1,137 @@ +const express = require('express'); +const multer = require('multer'); +const path = require('path'); +const fs = require('fs'); +const sharp = require('sharp'); +const router = express.Router(); +const { getDb } = require('../models/db'); +const { authMiddleware, adminMiddleware } = require('../middleware/auth'); + +// Generic icon storage factory +function makeIconStorage(prefix) { + return multer.diskStorage({ + destination: '/app/uploads/logos', + filename: (req, file, cb) => { + const ext = path.extname(file.originalname); + cb(null, `${prefix}_${Date.now()}${ext}`); + } + }); +} + +const iconUploadOpts = { + limits: { fileSize: 1 * 1024 * 1024 }, + fileFilter: (req, file, cb) => { + if (file.mimetype.startsWith('image/')) cb(null, true); + else cb(new Error('Images only')); + } +}; + +const uploadLogo = multer({ storage: makeIconStorage('logo'), ...iconUploadOpts }); +const uploadNewChat = multer({ storage: makeIconStorage('newchat'), ...iconUploadOpts }); +const uploadGroupInfo = multer({ storage: makeIconStorage('groupinfo'), ...iconUploadOpts }); + +// Get public settings (accessible by all) +router.get('/', (req, res) => { + const db = getDb(); + const settings = db.prepare('SELECT key, value FROM settings').all(); + const obj = {}; + for (const s of settings) obj[s.key] = s.value; + const admin = db.prepare('SELECT email FROM users WHERE is_default_admin = 1').get(); + if (admin) obj.admin_email = admin.email; + // Expose app version from Docker build arg env var + obj.app_version = process.env.JAMA_VERSION || process.env.TEAMCHAT_VERSION || 'dev'; + obj.user_pass = process.env.USER_PASS || 'user@1234'; + res.json({ settings: obj }); +}); + +// Update app name (admin) +router.patch('/app-name', authMiddleware, adminMiddleware, (req, res) => { + const { name } = req.body; + if (!name?.trim()) return res.status(400).json({ error: 'Name required' }); + const db = getDb(); + db.prepare("UPDATE settings SET value = ?, updated_at = datetime('now') WHERE key = 'app_name'").run(name.trim()); + res.json({ success: true, name: name.trim() }); +}); + +// Upload app logo (admin) — also generates 192x192 and 512x512 PWA icons +router.post('/logo', authMiddleware, adminMiddleware, uploadLogo.single('logo'), async (req, res) => { + if (!req.file) return res.status(400).json({ error: 'No file' }); + + const logoUrl = `/uploads/logos/${req.file.filename}`; + const srcPath = req.file.path; + + try { + // Generate PWA icons from the uploaded logo + const icon192Path = '/app/uploads/logos/pwa-icon-192.png'; + const icon512Path = '/app/uploads/logos/pwa-icon-512.png'; + + await sharp(srcPath) + .resize(192, 192, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 0 } }) + .png() + .toFile(icon192Path); + + await sharp(srcPath) + .resize(512, 512, { fit: 'contain', background: { r: 255, g: 255, b: 255, alpha: 0 } }) + .png() + .toFile(icon512Path); + + const db = getDb(); + db.prepare("UPDATE settings SET value = ?, updated_at = datetime('now') WHERE key = 'logo_url'").run(logoUrl); + // Store the PWA icon paths so the manifest can reference them + db.prepare("INSERT INTO settings (key, value) VALUES ('pwa_icon_192', ?) ON CONFLICT(key) DO UPDATE SET value = ?, updated_at = datetime('now')") + .run('/uploads/logos/pwa-icon-192.png', '/uploads/logos/pwa-icon-192.png'); + db.prepare("INSERT INTO settings (key, value) VALUES ('pwa_icon_512', ?) ON CONFLICT(key) DO UPDATE SET value = ?, updated_at = datetime('now')") + .run('/uploads/logos/pwa-icon-512.png', '/uploads/logos/pwa-icon-512.png'); + + res.json({ logoUrl }); + } catch (err) { + console.error('[Logo] Failed to generate PWA icons:', err.message); + // Still save the logo even if icon generation fails + const db = getDb(); + db.prepare("UPDATE settings SET value = ?, updated_at = datetime('now') WHERE key = 'logo_url'").run(logoUrl); + res.json({ logoUrl }); + } +}); + +// Upload New Chat icon (admin) +router.post('/icon-newchat', authMiddleware, adminMiddleware, uploadNewChat.single('icon'), (req, res) => { + if (!req.file) return res.status(400).json({ error: 'No file' }); + const iconUrl = `/uploads/logos/${req.file.filename}`; + const db = getDb(); + db.prepare("INSERT INTO settings (key, value) VALUES ('icon_newchat', ?) ON CONFLICT(key) DO UPDATE SET value = ?, updated_at = datetime('now')") + .run(iconUrl, iconUrl); + res.json({ iconUrl }); +}); + +// Upload Group Info icon (admin) +router.post('/icon-groupinfo', authMiddleware, adminMiddleware, uploadGroupInfo.single('icon'), (req, res) => { + if (!req.file) return res.status(400).json({ error: 'No file' }); + const iconUrl = `/uploads/logos/${req.file.filename}`; + const db = getDb(); + db.prepare("INSERT INTO settings (key, value) VALUES ('icon_groupinfo', ?) ON CONFLICT(key) DO UPDATE SET value = ?, updated_at = datetime('now')") + .run(iconUrl, iconUrl); + res.json({ iconUrl }); +}); + +// Reset all settings to defaults (admin) +router.patch('/colors', authMiddleware, adminMiddleware, (req, res) => { + const { colorTitle, colorTitleDark, colorAvatarPublic, colorAvatarDm } = req.body; + const db = getDb(); + const upd = db.prepare("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = ?, updated_at = datetime('now')"); + if (colorTitle !== undefined) upd.run('color_title', colorTitle || '', colorTitle || ''); + if (colorTitleDark !== undefined) upd.run('color_title_dark', colorTitleDark || '', colorTitleDark || ''); + if (colorAvatarPublic !== undefined) upd.run('color_avatar_public', colorAvatarPublic || '', colorAvatarPublic || ''); + if (colorAvatarDm !== undefined) upd.run('color_avatar_dm', colorAvatarDm || '', colorAvatarDm || ''); + res.json({ success: true }); +}); + +router.post('/reset', authMiddleware, adminMiddleware, (req, res) => { + const db = getDb(); + const originalName = process.env.APP_NAME || 'jama'; + db.prepare("UPDATE settings SET value = ?, updated_at = datetime('now') WHERE key = 'app_name'").run(originalName); + db.prepare("UPDATE settings SET value = '', updated_at = datetime('now') WHERE key = 'logo_url'").run(); + db.prepare("UPDATE settings SET value = '', updated_at = datetime('now') WHERE key IN ('icon_newchat', 'icon_groupinfo', 'pwa_icon_192', 'pwa_icon_512', 'color_title', 'color_title_dark', 'color_avatar_public', 'color_avatar_dm')").run(); + res.json({ success: true }); +}); + +module.exports = router; diff --git a/backend/src/routes/users.js b/backend/src/routes/users.js new file mode 100644 index 0000000..f02ed75 --- /dev/null +++ b/backend/src/routes/users.js @@ -0,0 +1,320 @@ +const express = require('express'); +const bcrypt = require('bcryptjs'); +const multer = require('multer'); +const path = require('path'); +const router = express.Router(); +const { getDb, addUserToPublicGroups, getOrCreateSupportGroup } = require('../models/db'); +const { authMiddleware, adminMiddleware } = require('../middleware/auth'); + +const avatarStorage = multer.diskStorage({ + destination: '/app/uploads/avatars', + filename: (req, file, cb) => { + const ext = path.extname(file.originalname); + cb(null, `avatar_${req.user.id}_${Date.now()}${ext}`); + } +}); +const uploadAvatar = multer({ + storage: avatarStorage, + limits: { fileSize: 2 * 1024 * 1024 }, + fileFilter: (req, file, cb) => { + if (file.mimetype.startsWith('image/')) cb(null, true); + else cb(new Error('Images only')); + } +}); + +// Resolve unique name: "John Doe" exists → return "John Doe (1)", then "(2)" etc. +function resolveUniqueName(db, baseName, excludeId = null) { + const existing = db.prepare( + "SELECT name FROM users WHERE status != 'deleted' AND id != ? AND (name = ? OR name LIKE ?)" + ).all(excludeId ?? -1, baseName, `${baseName} (%)`); + if (existing.length === 0) return baseName; + let max = 0; + for (const u of existing) { + const m = u.name.match(/\((\d+)\)$/); + if (m) max = Math.max(max, parseInt(m[1])); + else max = Math.max(max, 0); + } + return `${baseName} (${max + 1})`; +} + +function isValidEmail(email) { + return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email); +} + +function getDefaultPassword(db) { + return process.env.USER_PASS || 'user@1234'; +} + +// List users (admin) +router.get('/', authMiddleware, adminMiddleware, (req, res) => { + const db = getDb(); + const users = db.prepare(` + SELECT id, name, email, role, status, is_default_admin, must_change_password, avatar, about_me, display_name, allow_dm, created_at, last_online + FROM users WHERE status != 'deleted' + ORDER BY created_at ASC + `).all(); + res.json({ users }); +}); + +// Search users (public-ish for mentions/add-member) +router.get('/search', authMiddleware, (req, res) => { + const { q, groupId } = req.query; + const db = getDb(); + let users; + if (groupId) { + const group = db.prepare('SELECT type, is_direct FROM groups WHERE id = ?').get(parseInt(groupId)); + if (group && (group.type === 'private' || group.is_direct)) { + // Private group or direct message — only show members of this group + users = db.prepare(` + SELECT u.id, u.name, u.display_name, u.avatar, u.role, u.status, u.hide_admin_tag, u.allow_dm + FROM users u + JOIN group_members gm ON gm.user_id = u.id AND gm.group_id = ? + WHERE u.status = 'active' AND u.id != ? + AND (u.name LIKE ? OR u.display_name LIKE ?) + LIMIT 10 + `).all(parseInt(groupId), req.user.id, `%${q}%`, `%${q}%`); + } else { + // Public group — all active users + users = db.prepare(` + SELECT id, name, display_name, avatar, role, status, hide_admin_tag, allow_dm FROM users + WHERE status = 'active' AND id != ? AND (name LIKE ? OR display_name LIKE ?) + LIMIT 10 + `).all(req.user.id, `%${q}%`, `%${q}%`); + } + } else { + users = db.prepare(` + SELECT id, name, display_name, avatar, role, status, hide_admin_tag, allow_dm FROM users + WHERE status = 'active' AND (name LIKE ? OR display_name LIKE ?) + LIMIT 10 + `).all(`%${q}%`, `%${q}%`); + } + res.json({ users }); +}); + +// Check if a display name is already taken (excludes self) +router.get('/check-display-name', authMiddleware, (req, res) => { + const { name } = req.query; + if (!name) return res.json({ taken: false }); + const db = getDb(); + const conflict = db.prepare( + "SELECT id FROM users WHERE LOWER(display_name) = LOWER(?) AND id != ? AND status != 'deleted'" + ).get(name, req.user.id); + res.json({ taken: !!conflict }); +}); + +// Create user (admin) — req 3: skip duplicate email, req 4: suffix duplicate names +router.post('/', authMiddleware, adminMiddleware, (req, res) => { + const { name, email, password, role } = req.body; + if (!name || !email) return res.status(400).json({ error: 'Name and email required' }); + if (!isValidEmail(email)) return res.status(400).json({ error: 'Invalid email address' }); + + const db = getDb(); + const exists = db.prepare('SELECT id FROM users WHERE email = ?').get(email); + if (exists) return res.status(400).json({ error: 'Email already in use' }); + + const resolvedName = resolveUniqueName(db, name.trim()); + const pw = (password || '').trim() || getDefaultPassword(db); + const hash = bcrypt.hashSync(pw, 10); + const result = db.prepare(` + INSERT INTO users (name, email, password, role, status, must_change_password) + VALUES (?, ?, ?, ?, 'active', 1) + `).run(resolvedName, email, hash, role === 'admin' ? 'admin' : 'member'); + + addUserToPublicGroups(result.lastInsertRowid); + // Admin users are automatically added to the Support group + if (role === 'admin') { + const supportGroupId = getOrCreateSupportGroup(); + if (supportGroupId) { + db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)').run(supportGroupId, result.lastInsertRowid); + } + } + const user = db.prepare('SELECT id, name, email, role, status, must_change_password, created_at FROM users WHERE id = ?').get(result.lastInsertRowid); + res.json({ user }); +}); + +// Bulk create users +router.post('/bulk', authMiddleware, adminMiddleware, (req, res) => { + const { users } = req.body; + const db = getDb(); + const results = { created: [], skipped: [] }; + const seenEmails = new Set(); + const defaultPw = getDefaultPassword(db); + + const insertUser = db.prepare(` + INSERT INTO users (name, email, password, role, status, must_change_password) + VALUES (?, ?, ?, ?, 'active', 1) + `); + + for (const u of users) { + const email = (u.email || '').trim().toLowerCase(); + const name = (u.name || '').trim(); + if (!name || !email) { results.skipped.push({ email: email || '(blank)', reason: 'Missing name or email' }); continue; } + if (!isValidEmail(email)) { results.skipped.push({ email, reason: 'Invalid email address' }); continue; } + if (seenEmails.has(email)) { results.skipped.push({ email, reason: 'Duplicate email in CSV' }); continue; } + seenEmails.add(email); + const exists = db.prepare('SELECT id FROM users WHERE email = ?').get(email); + if (exists) { results.skipped.push({ email, reason: 'Email already exists' }); continue; } + try { + const resolvedName = resolveUniqueName(db, name); + const pw = (u.password || '').trim() || defaultPw; + const hash = bcrypt.hashSync(pw, 10); + const newRole = u.role === 'admin' ? 'admin' : 'member'; + const r = insertUser.run(resolvedName, email, hash, newRole); + addUserToPublicGroups(r.lastInsertRowid); + if (newRole === 'admin') { + const supportGroupId = getOrCreateSupportGroup(); + if (supportGroupId) { + db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)').run(supportGroupId, r.lastInsertRowid); + } + } + results.created.push(email); + } catch (e) { + results.skipped.push({ email, reason: e.message }); + } + } + + res.json(results); +}); + +// Update user name (admin only — req 5) +router.patch('/:id/name', authMiddleware, adminMiddleware, (req, res) => { + const { name } = req.body; + if (!name || !name.trim()) return res.status(400).json({ error: 'Name required' }); + const db = getDb(); + const target = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); + if (!target) return res.status(404).json({ error: 'User not found' }); + // Pass the target's own id so their current name is excluded from the duplicate check + const resolvedName = resolveUniqueName(db, name.trim(), req.params.id); + db.prepare("UPDATE users SET name = ?, updated_at = datetime('now') WHERE id = ?").run(resolvedName, target.id); + res.json({ success: true, name: resolvedName }); +}); + +// Update user role (admin) +router.patch('/:id/role', authMiddleware, adminMiddleware, (req, res) => { + const { role } = req.body; + const db = getDb(); + const target = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); + if (!target) return res.status(404).json({ error: 'User not found' }); + if (target.is_default_admin) return res.status(403).json({ error: 'Cannot modify default admin role' }); + if (!['member', 'admin'].includes(role)) return res.status(400).json({ error: 'Invalid role' }); + db.prepare("UPDATE users SET role = ?, updated_at = datetime('now') WHERE id = ?").run(role, target.id); + // If promoted to admin, ensure they're in the Support group + if (role === 'admin') { + const supportGroupId = getOrCreateSupportGroup(); + if (supportGroupId) { + db.prepare('INSERT OR IGNORE INTO group_members (group_id, user_id) VALUES (?, ?)').run(supportGroupId, target.id); + } + } + res.json({ success: true }); +}); + +// Reset user password (admin) +router.patch('/:id/reset-password', authMiddleware, adminMiddleware, (req, res) => { + const { password } = req.body; + if (!password || password.length < 6) return res.status(400).json({ error: 'Password too short' }); + const db = getDb(); + const hash = bcrypt.hashSync(password, 10); + db.prepare("UPDATE users SET password = ?, must_change_password = 1, updated_at = datetime('now') WHERE id = ?").run(hash, req.params.id); + res.json({ success: true }); +}); + +// Suspend user (admin) +router.patch('/:id/suspend', authMiddleware, adminMiddleware, (req, res) => { + const db = getDb(); + const target = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); + if (!target) return res.status(404).json({ error: 'User not found' }); + if (target.is_default_admin) return res.status(403).json({ error: 'Cannot suspend default admin' }); + db.prepare("UPDATE users SET status = 'suspended', updated_at = datetime('now') WHERE id = ?").run(target.id); + res.json({ success: true }); +}); + +// Activate user (admin) +router.patch('/:id/activate', authMiddleware, adminMiddleware, (req, res) => { + const db = getDb(); + db.prepare("UPDATE users SET status = 'active', updated_at = datetime('now') WHERE id = ?").run(req.params.id); + res.json({ success: true }); +}); + +// Delete user (admin) +router.delete('/:id', authMiddleware, adminMiddleware, (req, res) => { + const db = getDb(); + const target = db.prepare('SELECT * FROM users WHERE id = ?').get(req.params.id); + if (!target) return res.status(404).json({ error: 'User not found' }); + if (target.is_default_admin) return res.status(403).json({ error: 'Cannot delete default admin' }); + db.prepare("UPDATE users SET status = 'deleted', updated_at = datetime('now') WHERE id = ?").run(target.id); + res.json({ success: true }); +}); + +// Update own profile — display name must be unique (req 6) +router.patch('/me/profile', authMiddleware, (req, res) => { + const { displayName, aboutMe, hideAdminTag, allowDm } = req.body; + const db = getDb(); + if (displayName) { + const conflict = db.prepare( + "SELECT id FROM users WHERE LOWER(display_name) = LOWER(?) AND id != ? AND status != 'deleted'" + ).get(displayName, req.user.id); + if (conflict) return res.status(400).json({ error: 'Display name already in use' }); + } + db.prepare("UPDATE users SET display_name = ?, about_me = ?, hide_admin_tag = ?, allow_dm = ?, updated_at = datetime('now') WHERE id = ?") + .run(displayName || null, aboutMe || null, hideAdminTag ? 1 : 0, allowDm === false ? 0 : 1, req.user.id); + const user = db.prepare('SELECT id, name, email, role, status, avatar, about_me, display_name, hide_admin_tag, allow_dm FROM users WHERE id = ?').get(req.user.id); + res.json({ user }); +}); + +// Upload avatar — resize if needed, skip compression for files under 500 KB +router.post('/me/avatar', authMiddleware, uploadAvatar.single('avatar'), async (req, res) => { + if (!req.file) return res.status(400).json({ error: 'No file uploaded' }); + try { + const sharp = require('sharp'); + const filePath = req.file.path; + const fileSizeBytes = req.file.size; + const FIVE_HUNDRED_KB = 500 * 1024; + const MAX_DIM = 256; // max width/height in pixels + + const image = sharp(filePath); + const meta = await image.metadata(); + const needsResize = (meta.width > MAX_DIM || meta.height > MAX_DIM); + + if (fileSizeBytes < FIVE_HUNDRED_KB && !needsResize) { + // Small enough and already correctly sized — serve as-is + } else { + // Resize (and compress only if over 500 KB) + const outPath = filePath.replace(/(\.[^.]+)$/, '_p$1'); + let pipeline = sharp(filePath).resize(MAX_DIM, MAX_DIM, { fit: 'cover', withoutEnlargement: true }); + if (fileSizeBytes >= FIVE_HUNDRED_KB) { + // Compress: use webp for best size/quality ratio + pipeline = pipeline.webp({ quality: 82 }); + await pipeline.toFile(outPath + '.webp'); + const fs = require('fs'); + fs.unlinkSync(filePath); + fs.renameSync(outPath + '.webp', filePath.replace(/\.[^.]+$/, '.webp')); + const newPath = filePath.replace(/\.[^.]+$/, '.webp'); + const newFilename = path.basename(newPath); + const db = getDb(); + const avatarUrl = `/uploads/avatars/${newFilename}`; + db.prepare("UPDATE users SET avatar = ?, updated_at = datetime('now') WHERE id = ?").run(avatarUrl, req.user.id); + return res.json({ avatarUrl }); + } else { + // Under 500 KB but needs resize — resize only, keep original format + await pipeline.toFile(outPath); + const fs = require('fs'); + fs.unlinkSync(filePath); + fs.renameSync(outPath, filePath); + } + } + + const avatarUrl = `/uploads/avatars/${req.file.filename}`; + const db = getDb(); + db.prepare("UPDATE users SET avatar = ?, updated_at = datetime('now') WHERE id = ?").run(avatarUrl, req.user.id); + res.json({ avatarUrl }); + } catch (err) { + console.error('Avatar processing error:', err); + // Fall back to serving unprocessed file + const avatarUrl = `/uploads/avatars/${req.file.filename}`; + const db = getDb(); + db.prepare("UPDATE users SET avatar = ?, updated_at = datetime('now') WHERE id = ?").run(avatarUrl, req.user.id); + res.json({ avatarUrl }); + } +}); + +module.exports = router; diff --git a/backend/src/utils/linkPreview.js b/backend/src/utils/linkPreview.js new file mode 100644 index 0000000..a644e23 --- /dev/null +++ b/backend/src/utils/linkPreview.js @@ -0,0 +1,37 @@ +const fetch = require('node-fetch'); + +async function getLinkPreview(url) { + try { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 5000); + + const res = await fetch(url, { + signal: controller.signal, + headers: { 'User-Agent': 'JamaBot/1.0' } + }); + clearTimeout(timeout); + + const html = await res.text(); + + const getTag = (name) => { + const match = html.match(new RegExp(`]*property=["']${name}["'][^>]*content=["']([^"']+)["']`, 'i')) || + html.match(new RegExp(`]*content=["']([^"']+)["'][^>]*property=["']${name}["']`, 'i')) || + html.match(new RegExp(`]*name=["']${name}["'][^>]*content=["']([^"']+)["']`, 'i')); + return match?.[1] || ''; + }; + + const titleMatch = html.match(/]*>([^<]+)<\/title>/i); + + return { + url, + title: getTag('og:title') || titleMatch?.[1] || url, + description: getTag('og:description') || getTag('description') || '', + image: getTag('og:image') || '', + siteName: getTag('og:site_name') || new URL(url).hostname, + }; + } catch (e) { + return null; + } +} + +module.exports = { getLinkPreview }; diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..6172330 --- /dev/null +++ b/build.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# ───────────────────────────────────────────────────────────── +# jama — Docker build & release script +# +# Usage: +# ./build.sh # builds jama:latest +# ./build.sh 1.2.0 # builds jama:1.2.0 AND jama:latest +# ./build.sh 1.2.0 push # builds, tags, and pushes to registry +# +# To push to a registry, set REGISTRY env var: +# REGISTRY=ghcr.io/yourname ./build.sh 1.2.0 push +# REGISTRY=yourdockerhubuser ./build.sh 1.2.0 push +# ───────────────────────────────────────────────────────────── +set -euo pipefail + +VERSION="${1:-0.9.23}" +ACTION="${2:-}" +REGISTRY="${REGISTRY:-}" +IMAGE_NAME="jama" + +# If a registry is set, prefix image name +if [[ -n "$REGISTRY" ]]; then + FULL_IMAGE="${REGISTRY}/${IMAGE_NAME}" +else + FULL_IMAGE="${IMAGE_NAME}" +fi + +echo "╔══════════════════════════════════════╗" +echo "║ jama Docker Builder ║" +echo "╠══════════════════════════════════════╣" +echo "║ Image : ${FULL_IMAGE}" +echo "║ Version : ${VERSION}" +echo "╚══════════════════════════════════════╝" +echo "" + +# Build — npm install runs inside Docker, no host npm required +echo "▶ Building image..." +docker build \ + --build-arg BUILD_DATE="$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ + --build-arg VERSION="${VERSION}" \ + -t "${FULL_IMAGE}:${VERSION}" \ + -t "${FULL_IMAGE}:latest" \ + -f Dockerfile \ + . + +echo "" +echo "✔ Built successfully:" +echo " ${FULL_IMAGE}:${VERSION}" +echo " ${FULL_IMAGE}:latest" + +# Optionally push +if [[ "$ACTION" == "push" ]]; then + if [[ -z "$REGISTRY" ]]; then + echo "" + echo "⚠ No REGISTRY set. Pushing to Docker Hub as '${IMAGE_NAME}'." + echo " Set REGISTRY=youruser or REGISTRY=ghcr.io/yourorg to override." + fi + echo "" + echo "▶ Pushing ${FULL_IMAGE}:${VERSION}..." + docker push "${FULL_IMAGE}:${VERSION}" + echo "▶ Pushing ${FULL_IMAGE}:latest..." + docker push "${FULL_IMAGE}:latest" + echo "" + echo "✔ Pushed successfully." +fi + +echo "" +echo "─────────────────────────────────────────" +echo "To deploy this version, set in your .env:" +echo " JAMA_VERSION=${VERSION}" +echo "" +echo "Then run:" +echo " docker compose up -d" +echo "─────────────────────────────────────────" diff --git a/data/help.md b/data/help.md new file mode 100644 index 0000000..ddf7b0c --- /dev/null +++ b/data/help.md @@ -0,0 +1,110 @@ +# Getting Started with JAMA + +Welcome to **JAMA** — your private, self-hosted team messaging app. + +--- + +## Navigating JAMA + +### PRIVACY ASSURED +The only people that can read your direct messages (person 2 person or group) are the members of the message group. No one else, including admins, know which message groups exist or which you are part of, unless an they are a member of a given group that you are. + +Every user can, at minimum, read all public messages. + +--- + +### Message List (Left Sidebar) +The sidebar shows all your message groups and direct conversations. Tap or click any group to open it. + +- **#** prefix indicates a **Public** group — visible to all users +- **Lock** icon indicates a **Private** group — invite only +- **Bold** group names have unread messages +- The last message preview shows **You:** if you sent it + +--- + +## Sending Messages + +Type your message in the input box at the bottom and press **Enter** to send. + +- **Shift + Enter** adds a new line without sending +- Tap the **+** button to attach a photo or emoji +- Use the **camera** icon to take a photo directly (mobile only) + +### Mentioning Someone +Type **@** followed by the person's name to mention them. Select from the dropdown that appears. Mentioned users receive a notification. + +Example: `@[John Smith]` will notify John. + +### Replying to a Message +Hover over any message and click the **reply arrow** to quote and reply to it. + +### Reacting to a Message +Hover over any message and click the **emoji** button to react with an emoji. + +--- + +## Direct Messages + +Two ways to start a private conversation with one person: + +1. Click the **New Chat** icon in the sidebar +2. Select one user from the list +3. Click **Start Conversation** +4. Click the users avatar in a message to bring up the profile +5. Click **Direct Message** + +--- + +## Group Messages + +To create a group conversation: + +1. Click the **new chat** icon +2. Select two or more users from the +3. Enter a **Message Name** +4. Click **Create** + +> If a group with the exact same members already exists, you will be redirected to it automatically to help avoid duplication. + +--- + +## Your Profile + +Click your name or avatar at the bottom of the sidebar to: + +- Update your **display name** (displayed in message windows) +- Add an **about me** note +- Upload a **profile photo** +- Change your **password** + +--- + +## Customising Group Names + +You can set a personal display name for any group that only you will see: + +1. Open the message +2. Click the **message info** icon in the top right +3. Enter your custom name under **Your custom name** +4. Click **Save** + +Other members still see the original group name, unless they change to customised name. + +--- + +## Settings + +Admins can access **Settings** from the user menu to configure: + +- Branding a new app name and logo +- Set new user password +- Notification preferences + +--- + +## Tips + +- 🌙 Toggle **dark mode** from the user menu +- 🔔 Enable **push notifications** when prompted to receive alerts when the app is closed +- 📱 Install JAMA as a **PWA** on your device — tap *Add to Home Screen* in your browser menu for an app-like experience diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..6917806 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,33 @@ +services: + jama: + image: jama:${JAMA_VERSION:-latest} + container_name: ${PROJECT_NAME:-jama} + restart: unless-stopped + ports: + - "${PORT:-3000}:3000" + environment: + - NODE_ENV=production + - TZ=${TZ:-UTC} + - ADMIN_NAME=${ADMIN_NAME:-Admin User} + - ADMIN_EMAIL=${ADMIN_EMAIL:-admin@jama.local} + - ADMIN_PASS=${ADMIN_PASS:-Admin@1234} + - USER_PASS=${USER_PASS:-user@1234} + - ADMPW_RESET=${ADMPW_RESET:-false} + - JWT_SECRET=${JWT_SECRET:-changeme_super_secret_jwt_key_2024} + - DB_KEY=${DB_KEY} + - APP_NAME=${APP_NAME:-jama} + - DEFCHAT_NAME=${DEFCHAT_NAME:-General Chat} + volumes: + - jama_db:/app/data + - jama_uploads:/app/uploads + healthcheck: + test: ["CMD", "wget", "-q", "--spider", "http://localhost:3000/api/health"] + interval: 30s + timeout: 10s + retries: 3 + +volumes: + jama_db: + driver: local + jama_uploads: + driver: local diff --git a/docker-setup.md b/docker-setup.md new file mode 100644 index 0000000..70e83f5 --- /dev/null +++ b/docker-setup.md @@ -0,0 +1,87 @@ +## docker-compose.yaml + +added multiple variable options, that requires a .env file (envirnment variable) + +``` +services: + jama: + image: jama:${JAMA_VERSION:-latest} + container_name: ${PROJECT_NAME:-jamachat} + restart: unless-stopped + ports: + - "${PORT:-3000}:3000" + environment: + - NODE_ENV=production + - TZ=${TZ:-UTC} + - ADMIN_NAME=${ADMIN_NAME:-Admin User} + - ADMIN_EMAIL=${ADMIN_EMAIL:-admin@jama.local} + - ADMIN_PASS=${ADMIN_PASS:-Admin@1234} + - USER_PASS=${USER_PASS:-user@1234} + - ADMPW_RESET=${ADMPW_RESET:-false} + - JWT_SECRET=${JWT_SECRET:-changeme_super_secret_jwt_key_2024} + - DB_KEY=${DB_KEY} + - APP_NAME=${APP_NAME:-jama} + - DEFCHAT_NAME=${DEFCHAT_NAME:-General Chat} + volumes: + - ${PROJECT_NAME}_db:/app/data + - ${PROJECT_NAME}t_uploads:/app/uploads + healthcheck: + test: ["CMD", "wget", "-q", "--spider", "http://localhost:3000/api/health"] + interval: 30s + timeout: 10s + retries: 3 + +volumes: + ${PROJECT_NAME:-jamachat}_db: + driver: local + ${PROJECT_NAME:-jamachat}_uploads: + driver: local +``` +## .env file + +these are an example of a required .env. It can usually be imported in to docker managers. + +``` +# jama Configuration +# just another messaging app + +# Timezone — must match your host timezone (e.g. America/Toronto, Europe/London, Asia/Tokyo) +# Run 'timedatectl' on your host to find the correct value +TZ=UTC +# Copy this file to .env and customize + +# Image version to run (set by build.sh, or use 'latest') +JAMA_VERSION=0.9.3 + +# Default admin credentials (used on FIRST RUN only) +ADMIN_NAME=Admin User +ADMIN_EMAIL=admin@jama.local +ADMIN_PASS=Admin@1234 + +# Default password for bulk-imported users (when no password is set in CSV) +USER_PASS=user@1234 + +# Set to true to reset admin password to ADMIN_PASS on every restart +# WARNING: Leave false in production - shows a warning on login page when true +ADMPW_RESET=false + +# JWT secret - change this to a random string in production! +JWT_SECRET=changeme_super_secret_jwt_key_change_in_production + +# Database encryption key (SQLCipher AES-256) +# Generate a strong random key: openssl rand -hex 32 +# IMPORTANT: If you are upgrading from an unencrypted install, run the +# migration script first: node scripts/encrypt-db.js +# Leave blank to run without encryption (not recommended for production) +DB_KEY= + +# App port (default 3000) +PORT=3069 + +# App name (can also be changed in Settings UI) + +# Default public group name (created on first run only) +DEFCHAT_NAME=General Chat +APP_NAME=jama + +PROJECT_NAME=myjamachat ``` \ No newline at end of file diff --git a/frontend/index.html b/frontend/index.html new file mode 100644 index 0000000..2666525 --- /dev/null +++ b/frontend/index.html @@ -0,0 +1,17 @@ + + + + + + + + + + + jama + + +
+ + + diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000..8eb0a66 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,26 @@ +{ + "name": "jama-frontend", + "version": "0.9.23", + "private": true, + "scripts": { + "dev": "vite", + "build": "vite build", + "preview": "vite preview" + }, + "dependencies": { + "react": "^18.2.0", + "react-dom": "^18.2.0", + "react-router-dom": "^6.22.0", + "socket.io-client": "^4.6.1", + "emoji-mart": "^5.5.2", + "@emoji-mart/data": "^1.1.2", + "@emoji-mart/react": "^1.1.1", + "papaparse": "^5.4.1", + "date-fns": "^3.3.1", + "marked": "^12.0.0" + }, + "devDependencies": { + "@vitejs/plugin-react": "^4.2.1", + "vite": "^5.1.4" + } +} \ No newline at end of file diff --git a/frontend/public/favicon.ico b/frontend/public/favicon.ico new file mode 100644 index 0000000..3f7a56c Binary files /dev/null and b/frontend/public/favicon.ico differ diff --git a/frontend/public/icons/icon-192-maskable.png b/frontend/public/icons/icon-192-maskable.png new file mode 100644 index 0000000..c62db49 Binary files /dev/null and b/frontend/public/icons/icon-192-maskable.png differ diff --git a/frontend/public/icons/icon-192.png b/frontend/public/icons/icon-192.png new file mode 100644 index 0000000..20e4a9b Binary files /dev/null and b/frontend/public/icons/icon-192.png differ diff --git a/frontend/public/icons/icon-512-maskable.png b/frontend/public/icons/icon-512-maskable.png new file mode 100644 index 0000000..f8710bd Binary files /dev/null and b/frontend/public/icons/icon-512-maskable.png differ diff --git a/frontend/public/icons/icon-512.png b/frontend/public/icons/icon-512.png new file mode 100644 index 0000000..650f2a6 Binary files /dev/null and b/frontend/public/icons/icon-512.png differ diff --git a/frontend/public/icons/jama.png b/frontend/public/icons/jama.png new file mode 100644 index 0000000..650f2a6 Binary files /dev/null and b/frontend/public/icons/jama.png differ diff --git a/frontend/public/icons/logo-64.png b/frontend/public/icons/logo-64.png new file mode 100644 index 0000000..37d4051 Binary files /dev/null and b/frontend/public/icons/logo-64.png differ diff --git a/frontend/public/manifest.json b/frontend/public/manifest.json new file mode 100644 index 0000000..0b70959 --- /dev/null +++ b/frontend/public/manifest.json @@ -0,0 +1,38 @@ +{ + "name": "jama", + "short_name": "jama", + "description": "Modern team messaging application", + "start_url": "/", + "scope": "/", + "display": "standalone", + "orientation": "any", + "background_color": "#ffffff", + "theme_color": "#1a73e8", + "icons": [ + { + "src": "/icons/icon-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "any" + }, + { + "src": "/icons/icon-192-maskable.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "/icons/icon-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "any" + }, + { + "src": "/icons/icon-512-maskable.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ], + "min_width": "320px" +} \ No newline at end of file diff --git a/frontend/public/sw.js b/frontend/public/sw.js new file mode 100644 index 0000000..68ced58 --- /dev/null +++ b/frontend/public/sw.js @@ -0,0 +1,109 @@ +const CACHE_NAME = 'jama-v1'; +const STATIC_ASSETS = ['/']; + +self.addEventListener('install', (event) => { + event.waitUntil( + caches.open(CACHE_NAME).then((cache) => cache.addAll(STATIC_ASSETS)) + ); + self.skipWaiting(); +}); + +self.addEventListener('activate', (event) => { + event.waitUntil( + caches.keys().then((keys) => + Promise.all(keys.filter(k => k !== CACHE_NAME).map(k => caches.delete(k))) + ) + ); + self.clients.claim(); +}); + +self.addEventListener('fetch', (event) => { + const url = event.request.url; + if (url.includes('/api/') || url.includes('/socket.io/') || url.includes('/manifest.json')) { + return; + } + event.respondWith( + fetch(event.request).catch(() => caches.match(event.request)) + ); +}); + +// Track badge count in SW scope +let badgeCount = 0; + +self.addEventListener('push', (event) => { + if (!event.data) return; + + let data = {}; + try { data = event.data.json(); } catch (e) { return; } + + badgeCount++; + + // Update app badge + if (self.navigator && self.navigator.setAppBadge) { + self.navigator.setAppBadge(badgeCount).catch(() => {}); + } + + // Check if app is currently visible — if so, skip the notification + const showNotification = clients.matchAll({ + type: 'window', + includeUncontrolled: true, + }).then((clientList) => { + const appVisible = clientList.some( + (c) => c.visibilityState === 'visible' + ); + // Still show if app is open but hidden (minimized), skip only if truly visible + if (appVisible) return; + + return self.registration.showNotification(data.title || 'New Message', { + body: data.body || '', + icon: '/icons/icon-192.png', + badge: '/icons/icon-192-maskable.png', + data: { url: data.url || '/' }, + // Use unique tag per group so notifications group by conversation + tag: data.groupId ? `jama-group-${data.groupId}` : 'jama-message', + renotify: true, + }); + }); + + event.waitUntil(showNotification); +}); + +self.addEventListener('notificationclick', (event) => { + event.notification.close(); + badgeCount = 0; + if (self.navigator && self.navigator.clearAppBadge) { + self.navigator.clearAppBadge().catch(() => {}); + } + event.waitUntil( + clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => { + const url = event.notification.data?.url || '/'; + for (const client of clientList) { + if (client.url.includes(self.location.origin) && 'focus' in client) { + client.focus(); + return; + } + } + return clients.openWindow(url); + }) + ); +}); + +// Clear badge when app signals it +self.addEventListener('message', (event) => { + if (event.data?.type === 'CLEAR_BADGE') { + badgeCount = 0; + if (self.navigator && self.navigator.clearAppBadge) { + self.navigator.clearAppBadge().catch(() => {}); + } + } + if (event.data?.type === 'SET_BADGE') { + badgeCount = event.data.count || 0; + if (self.navigator && self.navigator.setAppBadge) { + if (badgeCount > 0) { + self.navigator.setAppBadge(badgeCount).catch(() => {}); + } else { + self.navigator.clearAppBadge().catch(() => {}); + } + } + } +}); diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx new file mode 100644 index 0000000..d9a022c --- /dev/null +++ b/frontend/src/App.jsx @@ -0,0 +1,54 @@ +import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'; +import { AuthProvider, useAuth } from './contexts/AuthContext.jsx'; +import { SocketProvider } from './contexts/SocketContext.jsx'; +import { ToastProvider } from './contexts/ToastContext.jsx'; +import Login from './pages/Login.jsx'; +import Chat from './pages/Chat.jsx'; +import ChangePassword from './pages/ChangePassword.jsx'; + +function ProtectedRoute({ children }) { + const { user, loading, mustChangePassword } = useAuth(); + if (loading) return ( +
+
+
+ ); + if (!user) return ; + if (mustChangePassword) return ; + return children; +} + +function AuthRoute({ children }) { + const { user, loading, mustChangePassword } = useAuth(); + // Always show login in light mode regardless of user's saved theme preference + document.documentElement.setAttribute('data-theme', 'light'); + if (loading) return null; + if (user && !mustChangePassword) return ; + return children; +} + +function RestoreTheme() { + // Called when entering a protected route — restore the user's saved theme + const saved = localStorage.getItem('jama-theme') || 'light'; + document.documentElement.setAttribute('data-theme', saved); + return null; +} + +export default function App() { + return ( + + + + + + } /> + } /> + } /> + } /> + + + + + + ); +} diff --git a/frontend/src/components/AboutModal.jsx b/frontend/src/components/AboutModal.jsx new file mode 100644 index 0000000..4657151 --- /dev/null +++ b/frontend/src/components/AboutModal.jsx @@ -0,0 +1,86 @@ +import { useState, useEffect } from 'react'; +import { api } from '../utils/api.js'; + +const CLAUDE_URL = 'https://claude.ai'; + +// Render "Built With" value — separator trails its token so it never starts a new line +function BuiltWithValue({ value }) { + if (!value) return null; + const parts = value.split('·').map(s => s.trim()); + return ( + + {parts.map((part, i) => ( + + {part === 'Claude.ai' + ? {part} + : part} + {i < parts.length - 1 && ·} + + ))} + + ); +} + +export default function AboutModal({ onClose }) { + const [about, setAbout] = useState(null); + + useEffect(() => { + fetch('/api/about') + .then(r => r.json()) + .then(({ about }) => setAbout(about)) + .catch(() => {}); + }, []); + + // Always use the original app identity — not the user-customised settings name/logo + const appName = about?.default_app_name || 'jama'; + const logoSrc = about?.default_logo || '/icons/jama.png'; + const version = about?.version || ''; + const a = about || {}; + + const rows = [ + { label: 'Version', value: version }, + { label: 'Built With', value: a.built_with, builtWith: true }, + { label: 'Developer', value: a.developer }, + { label: 'License', value: a.license, link: a.license_url }, + ].filter(r => r.value); + + return ( +
e.target === e.currentTarget && onClose()}> +
+ + +
+ {appName} +

{appName}

+

just another messaging app

+
+ + {about ? ( + <> +
+ {rows.map(({ label, value, builtWith, link }) => ( +
+ {label} + + {builtWith + ? + : link + ? {value} + : value} + +
+ ))} +
+ {a.description &&

{a.description}

} + + ) : ( +
+ )} +
+
+ ); +} diff --git a/frontend/src/components/Avatar.jsx b/frontend/src/components/Avatar.jsx new file mode 100644 index 0000000..41ad42a --- /dev/null +++ b/frontend/src/components/Avatar.jsx @@ -0,0 +1,24 @@ +export default function Avatar({ user, size = 'md', className = '' }) { + if (!user) return null; + + const initials = (() => { + const name = user.display_name || user.name || ''; + const parts = name.trim().split(' ').filter(Boolean); + if (parts.length >= 2) return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase(); + if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase(); + return '??'; + })(); + + const colors = ['#1a73e8','#ea4335','#34a853','#fa7b17','#a142f4','#00897b','#e91e8c','#0097a7']; + const colorIdx = (user.name || '').charCodeAt(0) % colors.length; + const bg = colors[colorIdx]; + + return ( +
+ {user.avatar + ? {initials} + : initials + } +
+ ); +} diff --git a/frontend/src/components/BrandingModal.jsx b/frontend/src/components/BrandingModal.jsx new file mode 100644 index 0000000..fee7846 --- /dev/null +++ b/frontend/src/components/BrandingModal.jsx @@ -0,0 +1,559 @@ +import { useState, useEffect, useRef, useCallback } from 'react'; +import { api } from '../utils/api.js'; +import { useToast } from '../contexts/ToastContext.jsx'; + +const DEFAULT_TITLE_COLOR = '#1a73e8'; // light mode default +const DEFAULT_TITLE_DARK_COLOR = '#60a5fa'; // dark mode default (lighter blue readable on dark bg) +const DEFAULT_PUBLIC_COLOR = '#1a73e8'; +const DEFAULT_DM_COLOR = '#a142f4'; + +const COLOUR_SUGGESTIONS = [ + '#1a73e8', '#a142f4', '#e53935', '#fa7b17', '#fdd835', '#34a853', +]; + +// ── Title Colour Row — one row per mode ────────────────────────────────────── + +function TitleColourRow({ bgColor, bgLabel, textColor, onChange }) { + const [mode, setMode] = useState('idle'); // 'idle' | 'custom' + + return ( +
+ {/* Preview box */} +
+ + Title + +
+ + {mode === 'idle' && ( + <> + {textColor} + + + )} + + {mode === 'custom' && ( +
+ { onChange(hex); setMode('idle'); }} + onBack={() => setMode('idle')} + /> +
+ )} +
+ ); +} + +// ── Colour math helpers ────────────────────────────────────────────────────── + +function hexToHsv(hex) { + const r = parseInt(hex.slice(1,3),16)/255; + const g = parseInt(hex.slice(3,5),16)/255; + const b = parseInt(hex.slice(5,7),16)/255; + const max = Math.max(r,g,b), min = Math.min(r,g,b), d = max - min; + let h = 0; + if (d !== 0) { + if (max === r) h = ((g - b) / d + (g < b ? 6 : 0)) / 6; + else if (max === g) h = ((b - r) / d + 2) / 6; + else h = ((r - g) / d + 4) / 6; + } + return { h: h * 360, s: max === 0 ? 0 : d / max, v: max }; +} + +function hsvToHex(h, s, v) { + h = h / 360; + const i = Math.floor(h * 6); + const f = h * 6 - i; + const p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s); + let r, g, b; + switch (i % 6) { + case 0: r=v; g=t; b=p; break; case 1: r=q; g=v; b=p; break; + case 2: r=p; g=v; b=t; break; case 3: r=p; g=q; b=v; break; + case 4: r=t; g=p; b=v; break; default: r=v; g=p; b=q; + } + return '#' + [r,g,b].map(x => Math.round(x*255).toString(16).padStart(2,'0')).join(''); +} + +function isValidHex(h) { return /^#[0-9a-fA-F]{6}$/.test(h); } + +// ── SV (saturation/value) square ───────────────────────────────────────────── + +function SvSquare({ hue, s, v, onChange }) { + const canvasRef = useRef(null); + const dragging = useRef(false); + + useEffect(() => { + const canvas = canvasRef.current; + if (!canvas) return; + const ctx = canvas.getContext('2d'); + const W = canvas.width, H = canvas.height; + // White → hue gradient (left→right) + const hGrad = ctx.createLinearGradient(0, 0, W, 0); + hGrad.addColorStop(0, '#fff'); + hGrad.addColorStop(1, `hsl(${hue},100%,50%)`); + ctx.fillStyle = hGrad; ctx.fillRect(0, 0, W, H); + // Transparent → black gradient (top→bottom) + const vGrad = ctx.createLinearGradient(0, 0, 0, H); + vGrad.addColorStop(0, 'transparent'); + vGrad.addColorStop(1, '#000'); + ctx.fillStyle = vGrad; ctx.fillRect(0, 0, W, H); + }, [hue]); + + const getPos = (e, canvas) => { + const r = canvas.getBoundingClientRect(); + const cx = (e.touches ? e.touches[0].clientX : e.clientX) - r.left; + const cy = (e.touches ? e.touches[0].clientY : e.clientY) - r.top; + return { + s: Math.max(0, Math.min(1, cx / r.width)), + v: Math.max(0, Math.min(1, 1 - cy / r.height)), + }; + }; + + const handle = (e) => { + e.preventDefault(); + const p = getPos(e, canvasRef.current); + onChange(p.s, p.v); + }; + + return ( +
+ { dragging.current = true; handle(e); }} + onMouseMove={e => { if (dragging.current) handle(e); }} + onMouseUp={() => { dragging.current = false; }} + onMouseLeave={() => { dragging.current = false; }} + onTouchStart={handle} onTouchMove={handle} + /> + {/* Cursor circle */} +
+
+ ); +} + +// ── Hue bar ─────────────────────────────────────────────────────────────────── + +function HueBar({ hue, onChange }) { + const barRef = useRef(null); + const dragging = useRef(false); + + const handle = (e) => { + e.preventDefault(); + const r = barRef.current.getBoundingClientRect(); + const cx = (e.touches ? e.touches[0].clientX : e.clientX) - r.left; + onChange(Math.max(0, Math.min(360, (cx / r.width) * 360))); + }; + + return ( +
+
{ dragging.current = true; handle(e); }} + onMouseMove={e => { if (dragging.current) handle(e); }} + onMouseUp={() => { dragging.current = false; }} + onMouseLeave={() => { dragging.current = false; }} + onTouchStart={handle} onTouchMove={handle} + /> +
+
+ ); +} + +// ── Custom HSV picker ───────────────────────────────────────────────────────── + +function CustomPicker({ initial, onSet, onBack }) { + const { h: ih, s: is, v: iv } = hexToHsv(initial); + const [hue, setHue] = useState(ih); + const [sat, setSat] = useState(is); + const [val, setVal] = useState(iv); + const [hexInput, setHexInput] = useState(initial); + const [hexError, setHexError] = useState(false); + + const current = hsvToHex(hue, sat, val); + + // Sync hex input when sliders change + useEffect(() => { setHexInput(current); setHexError(false); }, [current]); + + const handleHexInput = (e) => { + const v = e.target.value; + setHexInput(v); + if (isValidHex(v)) { + const { h, s, v: bv } = hexToHsv(v); + setHue(h); setSat(s); setVal(bv); + setHexError(false); + } else { + setHexError(true); + } + }; + + return ( +
+ { setSat(s); setVal(v); }} /> + + + {/* Preview + hex input */} +
+
+ + Chosen colour +
+ + {/* Actions */} +
+ + +
+
+ ); +} + +// ── ColourPicker card ───────────────────────────────────────────────────────── + +function ColourPicker({ label, value, onChange, preview }) { + const [mode, setMode] = useState('suggestions'); // 'suggestions' | 'custom' + + return ( +
+
{label}
+ + {/* Current colour preview */} +
+ {preview + ? preview(value) + :
+ } + {value} +
+ + {mode === 'suggestions' && ( + <> +
+ {COLOUR_SUGGESTIONS.map(hex => ( +
+ + + )} + + {mode === 'custom' && ( + { onChange(hex); setMode('suggestions'); }} + onBack={() => setMode('suggestions')} + /> + )} +
+ ); +} + +export default function BrandingModal({ onClose }) { + const toast = useToast(); + const [tab, setTab] = useState('general'); // 'general' | 'colours' + const [settings, setSettings] = useState({}); + const [appName, setAppName] = useState(''); + const [loading, setLoading] = useState(false); + const [resetting, setResetting] = useState(false); + const [showResetConfirm, setShowResetConfirm] = useState(false); + + const [colourTitle, setColourTitle] = useState(DEFAULT_TITLE_COLOR); + const [colourTitleDark, setColourTitleDark] = useState(DEFAULT_TITLE_DARK_COLOR); + const [colourPublic, setColourPublic] = useState(DEFAULT_PUBLIC_COLOR); + const [colourDm, setColourDm] = useState(DEFAULT_DM_COLOR); + const [savingColours, setSavingColours] = useState(false); + + useEffect(() => { + api.getSettings().then(({ settings }) => { + setSettings(settings); + setAppName(settings.app_name || 'jama'); + setColourTitle(settings.color_title || DEFAULT_TITLE_COLOR); + setColourTitleDark(settings.color_title_dark || DEFAULT_TITLE_DARK_COLOR); + setColourPublic(settings.color_avatar_public || DEFAULT_PUBLIC_COLOR); + setColourDm(settings.color_avatar_dm || DEFAULT_DM_COLOR); + }).catch(() => {}); + }, []); + + const notifySidebarRefresh = () => window.dispatchEvent(new Event('jama:settings-changed')); + + const handleSaveName = async () => { + if (!appName.trim()) return; + setLoading(true); + try { + await api.updateAppName(appName.trim()); + setSettings(prev => ({ ...prev, app_name: appName.trim() })); + toast('App name updated', 'success'); + notifySidebarRefresh(); + } catch (e) { + toast(e.message, 'error'); + } finally { + setLoading(false); + } + }; + + const handleLogoUpload = async (e) => { + const file = e.target.files?.[0]; + if (!file) return; + if (file.size > 1024 * 1024) return toast('Logo must be less than 1MB', 'error'); + try { + const { logoUrl } = await api.uploadLogo(file); + setSettings(prev => ({ ...prev, logo_url: logoUrl })); + toast('Logo updated', 'success'); + notifySidebarRefresh(); + } catch (e) { + toast(e.message, 'error'); + } + }; + + const handleSaveColours = async () => { + setSavingColours(true); + try { + await api.updateColors({ + colorTitle: colourTitle, + colorTitleDark: colourTitleDark, + colorAvatarPublic: colourPublic, + colorAvatarDm: colourDm, + }); + setSettings(prev => ({ + ...prev, + color_title: colourTitle, + color_title_dark: colourTitleDark, + color_avatar_public: colourPublic, + color_avatar_dm: colourDm, + })); + toast('Colours updated', 'success'); + notifySidebarRefresh(); + } catch (e) { + toast(e.message, 'error'); + } finally { + setSavingColours(false); + } + }; + + const handleReset = async () => { + setResetting(true); + try { + await api.resetSettings(); + const { settings: fresh } = await api.getSettings(); + setSettings(fresh); + setAppName(fresh.app_name || 'jama'); + setColourTitle(DEFAULT_TITLE_COLOR); + setColourTitleDark(DEFAULT_TITLE_DARK_COLOR); + setColourPublic(DEFAULT_PUBLIC_COLOR); + setColourDm(DEFAULT_DM_COLOR); + toast('Settings reset to defaults', 'success'); + notifySidebarRefresh(); + setShowResetConfirm(false); + } catch (e) { + toast(e.message, 'error'); + } finally { + setResetting(false); + } + }; + + return ( +
e.target === e.currentTarget && onClose()}> +
+
+

Branding

+ +
+ + {/* Tabs */} +
+ + +
+ + {tab === 'general' && ( + <> + {/* App Logo */} +
+
App Logo
+
+
+ logo +
+
+ +

+ Square format, max 1MB. Used in sidebar, login page and browser tab. +

+
+
+
+ + {/* App Name */} +
+
App Name
+
+ setAppName(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleSaveName()} /> + +
+
+ + {/* Reset */} +
+
Reset
+
+ {!showResetConfirm ? ( + + ) : ( +
+

+ This will reset the app name, logo and all colours to their install defaults. This cannot be undone. +

+
+ + +
+
+ )} + {settings.app_version && ( + v{settings.app_version} + )} +
+
+ + {settings.pw_reset_active === 'true' && ( +
+ ⚠️ + ADMPW_RESET is active. The default admin password is being reset on every restart. Set ADMPW_RESET=false in your environment variables to stop this. +
+ )} + + )} + + {tab === 'colours' && ( +
+
+
App Title Colour
+
+ + +
+
+ +
+ ( +
A
+ )} + /> +
+ +
+ ( +
B
+ )} + /> +
+ +
+ +
+
+ )} +
+
+ ); +} diff --git a/frontend/src/components/ChatWindow.css b/frontend/src/components/ChatWindow.css new file mode 100644 index 0000000..1df4e8b --- /dev/null +++ b/frontend/src/components/ChatWindow.css @@ -0,0 +1,164 @@ +.chat-window { + flex: 1; + display: flex; + flex-direction: column; + background: var(--surface-variant); + overflow: hidden; + min-width: 0; + min-height: 0; + height: 100%; +} + +.chat-window.empty { + align-items: center; + justify-content: center; +} + +.empty-state { + text-align: center; + color: var(--text-secondary); +} + +.empty-icon { + margin-bottom: 16px; + opacity: 0.3; +} + +.empty-state h3 { + font-size: 18px; + margin-bottom: 8px; + color: var(--text-primary); +} + +.empty-state p { font-size: 14px; } + +/* Header */ +.chat-header { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 16px; + background: white; + border-bottom: 1px solid var(--border); + min-height: 64px; + position: relative; + z-index: 10; +} + +.group-icon-sm { + width: 40px; + height: 40px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + font-size: 16px; + font-weight: 700; + color: white; + flex-shrink: 0; +} + +.chat-header-name { + font-size: 16px; + font-weight: 600; + color: var(--text-primary); +} + +.chat-header-sub { + font-size: 12px; + color: var(--text-secondary); +} + +/* Real name in brackets in DM header */ +.chat-header-real-name { + font-size: 12px; + font-weight: 400; + color: var(--text-tertiary); +} + +.readonly-badge { + font-size: 11px; + padding: 2px 8px; + border-radius: 10px; + background: #fff3e0; + color: #e65100; + font-weight: 500; +} + +/* Messages */ +.messages-container { + flex: 1; + min-height: 0; /* critical: allows flex child to shrink below content size */ + overflow-y: auto; + overflow-x: hidden; + padding: 16px; + display: flex; + flex-direction: column; + gap: 2px; + scroll-padding-bottom: 0; + overscroll-behavior: contain; + align-items: stretch; +} + +/* Cap message width and centre on wide screens */ +.messages-container > * { + max-width: 1024px; + width: 100%; + align-self: center; + box-sizing: border-box; +} + +.load-more-btn { + align-self: center; + font-size: 13px; + color: var(--primary); + padding: 8px 16px; + border-radius: 20px; + background: var(--primary-light); + margin-bottom: 8px; + transition: var(--transition); +} +.load-more-btn:hover { background: #d2e3fc; } + +/* Typing indicator */ +.typing-indicator { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + font-size: 13px; + color: var(--text-secondary); +} + +.dots { + display: flex; + gap: 3px; +} + +.dots span { + width: 5px; + height: 5px; + border-radius: 50%; + background: var(--text-tertiary); + animation: bounce 1.2s infinite; +} +.dots span:nth-child(2) { animation-delay: 0.2s; } +.dots span:nth-child(3) { animation-delay: 0.4s; } + +@keyframes bounce { + 0%, 60%, 100% { transform: translateY(0); } + 30% { transform: translateY(-5px); } +} + +/* Readonly bar */ +.readonly-bar { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 16px; + background: white; + border-top: 1px solid var(--border); + font-size: 14px; + color: var(--text-secondary); +} diff --git a/frontend/src/components/ChatWindow.jsx b/frontend/src/components/ChatWindow.jsx new file mode 100644 index 0000000..8fc3745 --- /dev/null +++ b/frontend/src/components/ChatWindow.jsx @@ -0,0 +1,319 @@ +import { useState, useEffect, useRef, useCallback } from 'react'; +import Message from './Message.jsx'; +import MessageInput from './MessageInput.jsx'; +import { api } from '../utils/api.js'; +import { useAuth } from '../contexts/AuthContext.jsx'; +import { useToast } from '../contexts/ToastContext.jsx'; +import { useSocket } from '../contexts/SocketContext.jsx'; +import './ChatWindow.css'; +import GroupInfoModal from './GroupInfoModal.jsx'; + +export default function ChatWindow({ group, onBack, onGroupUpdated, onDirectMessage, onlineUserIds = new Set() }) { + const { user: currentUser } = useAuth(); + const { socket } = useSocket(); + const { toast } = useToast(); + + const [messages, setMessages] = useState([]); + const [loading, setLoading] = useState(false); + const [hasMore, setHasMore] = useState(false); + const [typing, setTyping] = useState([]); + const [iconGroupInfo, setIconGroupInfo] = useState(''); + const [avatarColors, setAvatarColors] = useState({ public: '#1a73e8', dm: '#a142f4' }); + const [showInfo, setShowInfo] = useState(false); + const [replyTo, setReplyTo] = useState(null); + const [isMobile, setIsMobile] = useState(window.innerWidth < 768); + + const messagesEndRef = useRef(null); + const messagesContainerRef = useRef(null); + const typingTimers = useRef({}); + + useEffect(() => { + const onResize = () => setIsMobile(window.innerWidth < 768); + window.addEventListener('resize', onResize); + return () => window.removeEventListener('resize', onResize); + }, []); + + useEffect(() => { + api.getSettings().then(({ settings }) => { + setIconGroupInfo(settings.icon_groupinfo || ''); + setAvatarColors({ public: settings.color_avatar_public || '#1a73e8', dm: settings.color_avatar_dm || '#a142f4' }); + }).catch(() => {}); + const handler = () => api.getSettings().then(({ settings }) => { + setIconGroupInfo(settings.icon_groupinfo || ''); + setAvatarColors({ public: settings.color_avatar_public || '#1a73e8', dm: settings.color_avatar_dm || '#a142f4' }); + }).catch(() => {}); + window.addEventListener('jama:settings-updated', handler); + window.addEventListener('jama:settings-changed', handler); + return () => { + window.removeEventListener('jama:settings-updated', handler); + window.removeEventListener('jama:settings-changed', handler); + }; + }, []); + + const scrollToBottom = useCallback((smooth = false) => { + messagesEndRef.current?.scrollIntoView({ behavior: smooth ? 'smooth' : 'auto' }); + }, []); + + useEffect(() => { + if (!group) { setMessages([]); return; } + setMessages([]); + setHasMore(false); + setLoading(true); + api.getMessages(group.id) + .then(({ messages }) => { + setMessages(messages); + setHasMore(messages.length >= 50); + setTimeout(() => scrollToBottom(), 50); + }) + .catch(e => toast(e.message, 'error')) + .finally(() => setLoading(false)); + }, [group?.id]); + + // Socket events + useEffect(() => { + if (!socket || !group) return; + + const handleNew = (msg) => { + if (msg.group_id !== group.id) return; + setMessages(prev => { + if (prev.find(m => m.id === msg.id)) return prev; + return [...prev, msg]; + }); + setTimeout(() => scrollToBottom(true), 50); + }; + + const handleDeleted = ({ messageId }) => { + setMessages(prev => prev.map(m => + m.id === messageId ? { ...m, is_deleted: 1, content: null, image_url: null } : m + )); + }; + + const handleReaction = ({ messageId, reactions }) => { + setMessages(prev => prev.map(m => + m.id === messageId ? { ...m, reactions } : m + )); + }; + + const handleTypingStart = ({ userId: tid, user: tu }) => { + if (tid === currentUser?.id) return; + setTyping(prev => prev.find(t => t.userId === tid) + ? prev + : [...prev, { userId: tid, name: tu?.display_name || tu?.name || 'Someone' }]); + if (typingTimers.current[tid]) clearTimeout(typingTimers.current[tid]); + typingTimers.current[tid] = setTimeout(() => { + setTyping(prev => prev.filter(t => t.userId !== tid)); + }, 4000); + }; + + const handleTypingStop = ({ userId: tid }) => { + clearTimeout(typingTimers.current[tid]); + setTyping(prev => prev.filter(t => t.userId !== tid)); + }; + + const handleGroupUpdated = (updatedGroup) => { + if (updatedGroup.id === group.id) onGroupUpdated?.(); + }; + + socket.on('message:new', handleNew); + socket.on('message:deleted', handleDeleted); + socket.on('reaction:updated', handleReaction); + socket.on('typing:start', handleTypingStart); + socket.on('typing:stop', handleTypingStop); + socket.on('group:updated', handleGroupUpdated); + + return () => { + socket.off('message:new', handleNew); + socket.off('message:deleted', handleDeleted); + socket.off('reaction:updated', handleReaction); + socket.off('typing:start', handleTypingStart); + socket.off('typing:stop', handleTypingStop); + socket.off('group:updated', handleGroupUpdated); + }; + }, [socket, group?.id, currentUser?.id]); + + const handleLoadMore = async () => { + if (!hasMore || loading || messages.length === 0) return; + const container = messagesContainerRef.current; + const prevScrollHeight = container?.scrollHeight || 0; + setLoading(true); + try { + const oldest = messages[0]; + const { messages: older } = await api.getMessages(group.id, oldest.id); + setMessages(prev => [...older, ...prev]); + setHasMore(older.length >= 50); + requestAnimationFrame(() => { + if (container) container.scrollTop = container.scrollHeight - prevScrollHeight; + }); + } catch (e) { + toast(e.message, 'error'); + } finally { + setLoading(false); + } + }; + + const handleSend = async ({ content, imageFile, linkPreview, emojiOnly }) => { + if ((!content?.trim() && !imageFile) || !group) return; + const replyToId = replyTo?.id || null; + setReplyTo(null); + try { + if (imageFile) { + await api.uploadImage(group.id, imageFile, { replyToId, content: content?.trim() || '' }); + } else { + await api.sendMessage(group.id, { content: content.trim(), replyToId, linkPreview, emojiOnly }); + } + } catch (e) { + toast(e.message || 'Failed to send', 'error'); + } + }; + + const handleDelete = async (msgId) => { + try { + await api.deleteMessage(msgId); + } catch (e) { + toast(e.message || 'Could not delete', 'error'); + } + }; + + const handleReact = async (msgId, emoji) => { + try { + await api.toggleReaction(msgId, emoji); + } catch (e) { + toast(e.message || 'Could not react', 'error'); + } + }; + + const handleReply = (msg) => { + setReplyTo(msg); + }; + + const handleDirectMessage = (dmGroup) => { + onDirectMessage?.(dmGroup); + }; + + if (!group) { + return ( +
+
+
+ + + +
+

Select a conversation

+

Choose a channel or direct message to start chatting

+
+
+ ); + } + + const isDirect = !!group.is_direct; + const peerName = group.peer_display_name + ? <>{group.peer_display_name} ({group.peer_real_name}) + : group.peer_real_name || group.name; + const isOnline = isDirect && group.peer_id && (onlineUserIds instanceof Set ? onlineUserIds.has(Number(group.peer_id)) : false); + + return ( + <> +
+ {/* Header */} +
+ {isMobile && onBack && ( + + )} + + {isDirect && group.peer_avatar ? ( +
+ {group.name} + {isOnline && } +
+ ) : ( +
+ {group.type === 'public' ? '#' : isDirect ? (group.peer_real_name || group.name)[0]?.toUpperCase() : group.name[0]?.toUpperCase()} +
+ )} + +
+
+ {isDirect ? peerName : group.name} + {group.is_readonly ? read-only : null} +
+ {isDirect && isOnline &&
Online
} + {!isDirect && group.type === 'private' &&
Private group
} +
+ + +
+ + {/* Messages */} +
+ {hasMore && ( + + )} + + {messages.map((msg, i) => ( + + ))} + + {typing.length > 0 && ( +
+ {typing.map(t => t.name).join(', ')} {typing.length === 1 ? 'is' : 'are'} typing +
+
+ )} + +
+
+ + {/* Input */} + {group.is_readonly && currentUser?.role !== 'admin' ? ( +
+ + + + + This channel is read-only +
+ ) : ( + setReplyTo(null)} onTyping={() => {}} /> + )} +
+ {showInfo && ( + setShowInfo(false)} + onUpdated={(updatedGroup) => { setShowInfo(false); onGroupUpdated && onGroupUpdated(updatedGroup); }} + onBack={() => setShowInfo(false)} + /> + )} + + ); +} diff --git a/frontend/src/components/GlobalBar.jsx b/frontend/src/components/GlobalBar.jsx new file mode 100644 index 0000000..10e5c36 --- /dev/null +++ b/frontend/src/components/GlobalBar.jsx @@ -0,0 +1,51 @@ +import { useState, useEffect } from 'react'; +import { useSocket } from '../contexts/SocketContext.jsx'; +import { api } from '../utils/api.js'; + +export default function GlobalBar({ isMobile, showSidebar }) { + const { connected } = useSocket(); + const [settings, setSettings] = useState({ app_name: 'jama', logo_url: '' }); + const [isDark, setIsDark] = useState(() => document.documentElement.getAttribute('data-theme') === 'dark'); + + useEffect(() => { + api.getSettings().then(({ settings }) => setSettings(settings)).catch(() => {}); + const handler = () => api.getSettings().then(({ settings }) => setSettings(settings)).catch(() => {}); + window.addEventListener('jama:settings-changed', handler); + // Re-render when theme changes so title colour switches correctly + const themeObserver = new MutationObserver(() => { + setIsDark(document.documentElement.getAttribute('data-theme') === 'dark'); + }); + themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] }); + return () => { + window.removeEventListener('jama:settings-changed', handler); + themeObserver.disconnect(); + }; + }, []); + + const appName = settings.app_name || 'jama'; + const logoUrl = settings.logo_url; + const titleColor = (isDark ? settings.color_title_dark : settings.color_title) || null; + + // On mobile: show bar only when sidebar is visible (chat list view) + // On desktop: always show + if (isMobile && !showSidebar) return null; + + return ( +
+
+ {appName} + {appName} +
+ {!connected && ( + + + Offline + + )} +
+ ); +} diff --git a/frontend/src/components/GroupInfoModal.jsx b/frontend/src/components/GroupInfoModal.jsx new file mode 100644 index 0000000..15b8820 --- /dev/null +++ b/frontend/src/components/GroupInfoModal.jsx @@ -0,0 +1,259 @@ +import { useState, useEffect } from 'react'; +import { useAuth } from '../contexts/AuthContext.jsx'; +import { api } from '../utils/api.js'; +import { useToast } from '../contexts/ToastContext.jsx'; +import Avatar from './Avatar.jsx'; + +export default function GroupInfoModal({ group, onClose, onUpdated, onBack }) { + const { user } = useAuth(); + const toast = useToast(); + const [members, setMembers] = useState([]); + const [editing, setEditing] = useState(false); + const [newName, setNewName] = useState(group.name); + const [addSearch, setAddSearch] = useState(''); + const [addResults, setAddResults] = useState([]); + const [customName, setCustomName] = useState(group.owner_name_original ? group.name : ''); + const [savedCustomName, setSavedCustomName] = useState(group.owner_name_original ? group.name : ''); + const [savingCustom, setSavingCustom] = useState(false); + + const isDirect = !!group.is_direct; + const isOwner = group.owner_id === user.id; + const isAdmin = user.role === 'admin'; + const canManage = !isDirect && ((group.type === 'private' && isOwner) || (group.type === 'public' && isAdmin)); + const canRename = !isDirect && !group.is_default && ((group.type === 'public' && isAdmin) || (group.type === 'private' && isOwner)); + + useEffect(() => { + if (group.type === 'private') { + api.getMembers(group.id).then(({ members }) => setMembers(members)).catch(() => {}); + } + }, [group.id]); + + const handleCustomName = async () => { + setSavingCustom(true); + try { + const saved = customName.trim(); + await api.setCustomGroupName(group.id, saved); + setSavedCustomName(saved); + toast(saved ? 'Custom name saved' : 'Custom name removed', 'success'); + onUpdated(); + } catch (e) { + toast(e.message, 'error'); + } finally { + setSavingCustom(false); + } + }; + + useEffect(() => { + if (addSearch) { + api.searchUsers(addSearch).then(({ users }) => setAddResults(users)).catch(() => {}); + } + }, [addSearch]); + + const handleRename = async () => { + if (!newName.trim() || newName === group.name) { setEditing(false); return; } + try { + await api.renameGroup(group.id, newName.trim()); + toast('Renamed', 'success'); + onUpdated(); + setEditing(false); + } catch (e) { toast(e.message, 'error'); } + }; + + const handleLeave = async () => { + if (!confirm('Leave this message?')) return; + try { + await api.leaveGroup(group.id); + toast('Left message', 'success'); + onClose(); + if (isDirect) { + // For direct messages: socket group:deleted fired by server handles + // removing from sidebar and clearing active group — no manual refresh needed + } else { + onUpdated(); + if (onBack) onBack(); + } + } catch (e) { toast(e.message, 'error'); } + }; + + const handleTakeOwnership = async () => { + if (!confirm('Take ownership of this private group?')) return; + try { + await api.takeOwnership(group.id); + toast('Ownership taken', 'success'); + onUpdated(); + onClose(); + } catch (e) { toast(e.message, 'error'); } + }; + + const handleAdd = async (u) => { + try { + await api.addMember(group.id, u.id); + toast(`${u.name} added`, 'success'); + api.getMembers(group.id).then(({ members }) => setMembers(members)); + setAddSearch(''); + setAddResults([]); + } catch (e) { toast(e.message, 'error'); } + }; + + const handleRemove = async (member) => { + if (!confirm(`Remove ${member.name}?`)) return; + try { + await api.removeMember(group.id, member.id); + toast(`${member.name} removed`, 'success'); + setMembers(prev => prev.filter(m => m.id !== member.id)); + } catch (e) { toast(e.message, 'error'); } + }; + + const handleDelete = async () => { + if (!confirm('Delete this message? This cannot be undone.')) return; + try { + await api.deleteGroup(group.id); + toast('Deleted', 'success'); + onUpdated(); + onClose(); + if (onBack) onBack(); + } catch (e) { toast(e.message, 'error'); } + }; + + // For direct messages: only show Delete button (owner = remaining user after other left) + const canDeleteDirect = isDirect && isOwner; + const canDeleteRegular = !isDirect && (isOwner || (isAdmin && group.type === 'public')) && !group.is_default; + + return ( +
e.target === e.currentTarget && onClose()}> +
+
+

Message Info

+ +
+ + {/* Name */} +
+ {editing ? ( +
+ setNewName(e.target.value)} onKeyDown={e => e.key === 'Enter' && handleRename()} /> + + +
+ ) : ( +
+

{group.name}

+ {canRename && ( + + )} +
+ )} +
+ + {isDirect ? 'Direct message' : group.type === 'public' ? 'Public message' : 'Private message'} + + {!!group.is_readonly && Read-only} +
+
+ + {/* Custom name — any user can set their own display name for this group */} +
+ +
+ setCustomName(e.target.value)} + placeholder={group.owner_name_original || group.name} + onKeyDown={e => e.key === 'Enter' && handleCustomName()} + /> + {customName.trim() !== savedCustomName ? ( + + ) : savedCustomName ? ( + + ) : null} +
+ {group.owner_name_original && ( +

+ Showing as: {customName.trim() || group.owner_name_original} + {customName.trim() && ({group.owner_name_original})} +

+ )} +
+ + {/* Members — shown for private non-direct groups */} + {group.type === 'private' && !isDirect && ( +
+
+ Members ({members.length}) +
+
+ {members.map(m => ( +
+ + {m.name} + {m.id === group.owner_id && Owner} + {canManage && m.id !== group.owner_id && ( + + )} +
+ ))} +
+ {canManage && ( +
+ setAddSearch(e.target.value)} /> + {addResults.length > 0 && addSearch && ( +
+ {addResults.filter(u => !members.find(m => m.id === u.id)).map(u => ( + + ))} +
+ )} +
+ )} +
+ )} + + {/* Actions */} +
+ {/* Direct message: leave (if not already owner/last person) */} + {isDirect && !isOwner && ( + + )} + {/* Regular private: leave if not owner */} + {!isDirect && group.type === 'private' && !isOwner && ( + + )} + {/* Admin take ownership (non-direct only) */} + {!isDirect && isAdmin && group.type === 'private' && !isOwner && ( + + )} + {/* Delete */} + {(canDeleteDirect || canDeleteRegular) && ( + + )} +
+
+
+ ); +} diff --git a/frontend/src/components/HelpModal.jsx b/frontend/src/components/HelpModal.jsx new file mode 100644 index 0000000..c031f7d --- /dev/null +++ b/frontend/src/components/HelpModal.jsx @@ -0,0 +1,70 @@ +import { useState, useEffect } from 'react'; +import { marked } from 'marked'; +import { api } from '../utils/api.js'; + +// Configure marked for safe rendering +marked.setOptions({ breaks: true, gfm: true }); + +export default function HelpModal({ onClose, dismissed: initialDismissed }) { + const [content, setContent] = useState(''); + const [loading, setLoading] = useState(true); + const [dismissed, setDismissed] = useState(!!initialDismissed); + + useEffect(() => { + api.getHelp() + .then(({ content }) => setContent(content)) + .catch(() => setContent('# Getting Started\n\nHelp content could not be loaded.')) + .finally(() => setLoading(false)); + }, []); + + const handleDismissToggle = async (e) => { + const val = e.target.checked; + setDismissed(val); + try { + await api.dismissHelp(val); + } catch (_) {} + }; + + return ( +
e.target === e.currentTarget && onClose()}> +
+ + {/* Header */} +
+

Getting Started

+ +
+ + {/* Scrollable markdown content */} +
+ {loading ? ( +
Loading…
+ ) : ( +
+ )} +
+ + {/* Footer */} +
+ + +
+ +
+
+ ); +} diff --git a/frontend/src/components/ImageLightbox.jsx b/frontend/src/components/ImageLightbox.jsx new file mode 100644 index 0000000..24b63c1 --- /dev/null +++ b/frontend/src/components/ImageLightbox.jsx @@ -0,0 +1,85 @@ +import { useEffect, useRef } from 'react'; +import { createPortal } from 'react-dom'; + +export default function ImageLightbox({ src, onClose }) { + const overlayRef = useRef(null); + + // Close on Escape + useEffect(() => { + const handler = (e) => { if (e.key === 'Escape') onClose(); }; + window.addEventListener('keydown', handler); + // Prevent body scroll while open + document.body.style.overflow = 'hidden'; + return () => { + window.removeEventListener('keydown', handler); + document.body.style.overflow = ''; + }; + }, [onClose]); + + return createPortal( +
e.target === overlayRef.current && onClose()} + style={{ + position: 'fixed', inset: 0, zIndex: 9999, + background: 'rgba(0,0,0,0.92)', + display: 'flex', alignItems: 'center', justifyContent: 'center', + touchAction: 'pinch-zoom', + }} + > + {/* Close button */} + + + {/* Download button */} + + + + + + + + + {/* Image — fit to screen, browser handles pinch-zoom natively */} + Full size e.stopPropagation()} + /> +
, + document.body + ); +} diff --git a/frontend/src/components/Message.css b/frontend/src/components/Message.css new file mode 100644 index 0000000..aa59c8a --- /dev/null +++ b/frontend/src/components/Message.css @@ -0,0 +1,336 @@ +.date-separator { + display: flex; + align-items: center; + justify-content: center; + margin: 12px 0 8px; +} + +.date-separator span { + background: rgba(0,0,0,0.06); + padding: 4px 12px; + border-radius: 12px; + font-size: 12px; + color: var(--text-secondary); + font-weight: 500; +} + +.system-message { + text-align: center; + font-size: 12px; + color: var(--text-tertiary); + font-style: italic; + margin: 6px 0; + padding: 0 24px; +} + +[data-theme="dark"] .system-message { + color: var(--text-secondary); +} + +.msg-link { + color: var(--primary); + text-decoration: underline; + word-break: break-all; +} +.msg-link:hover { + opacity: 0.8; +} + +/* Own bubble (primary background) — link must be white */ +.msg-bubble.out .msg-link { + color: white; + text-decoration: underline; + opacity: 0.9; +} +.msg-bubble.out .msg-link:hover { + opacity: 1; +} + +/* Incoming bubble — link should be a dark/contrasting tone, not the same blue as bubble */ +.msg-bubble.in .msg-link { + color: var(--primary-dark, #1565c0); + text-decoration: underline; +} + +.message-wrapper { + display: flex; + align-items: flex-start; + gap: 8px; + padding: 1px 0; + position: relative; +} + +.message-wrapper.own { flex-direction: row-reverse; } +.message-wrapper.grouped { margin-top: 2px; } +.message-wrapper:not(.grouped) { margin-top: 10px; } + +.avatar-spacer { width: 32px; flex-shrink: 0; } + +.msg-avatar { flex-shrink: 0; } + +.message-body { + display: flex; + flex-direction: column; + max-width: 65%; + min-width: 0; +} + +.own .message-body { align-items: flex-end; } + +.msg-name { + font-size: calc(0.75rem * var(--font-scale)); + font-weight: 600; + color: var(--text-secondary); + margin-bottom: 3px; + padding: 0 12px; +} + +/* Reply preview */ +.reply-preview { + display: flex; + gap: 8px; + background: rgba(0,0,0,0.05); + border-radius: 8px 8px 0 0; + padding: 6px 10px; + margin-bottom: -4px; + max-width: 280px; +} + +.reply-bar { width: 3px; background: var(--primary); border-radius: 2px; flex-shrink: 0; } + +.reply-name { font-size: calc(0.6875rem * var(--font-scale)); font-weight: 600; color: var(--primary); } +.reply-text { font-size: calc(0.75rem * var(--font-scale)); color: var(--text-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 220px; } + +/* Bubble row */ +.msg-bubble-wrap { + position: relative; + display: flex; + align-items: flex-start; + gap: 6px; +} + +.own .msg-bubble-wrap { + position: relative; flex-direction: row-reverse; } + +/* Wrapper that holds the actions toolbar + bubble together */ +.msg-bubble-with-actions { + position: relative; + display: flex; + flex-direction: column; +} + +/* Actions toolbar — floats above the bubble */ +.msg-actions { + display: flex; + align-items: center; + gap: 2px; + background: white; + border-radius: 20px; + padding: 4px 6px; + box-shadow: var(--shadow-md); + position: absolute; + top: -36px; + z-index: 20; + white-space: nowrap; +} + +/* Own messages: toolbar anchors to the right edge of bubble */ +.msg-actions.actions-left { right: 0; } +/* Other messages: toolbar anchors to the left edge of bubble */ +.msg-actions.actions-right { left: 0; } + +.quick-emoji { + font-size: 16px; + padding: 4px; + border-radius: 50%; + transition: var(--transition); + cursor: pointer; + line-height: 1; +} +.quick-emoji:hover { background: var(--background); transform: scale(1.2); } + +.action-btn { + width: 28px; + height: 28px; + color: var(--text-secondary); +} +.action-btn:hover { color: var(--text-primary); } +.action-btn.danger:hover { color: var(--error); } + +/* Emoji picker — anchored relative to the toolbar */ +.emoji-picker-wrap { + position: absolute; + top: -360px; /* above the toolbar by default */ + z-index: 100; +} +.emoji-picker-wrap.picker-right { left: 0; } +.emoji-picker-wrap.picker-left { right: 0; } +/* When message is near top of window, open picker downward instead */ +.emoji-picker-wrap.picker-down { + top: 36px; +} + +/* Bubble */ +.msg-bubble { + padding: 8px 12px; + border-radius: 18px; + max-width: 100%; + word-break: break-word; + position: relative; +} + +@media (max-width: 767px) { + .msg-bubble { + user-select: none; + -webkit-user-select: none; + } +} + +.msg-bubble.out { + background: var(--primary); + color: white; + border-bottom-right-radius: 4px; +} + +.msg-bubble.in { + background: var(--bubble-in); + color: var(--text-primary); + border-bottom-left-radius: 4px; + box-shadow: var(--shadow-sm); +} + +.msg-bubble.deleted { + background: transparent !important; + border: 1px dashed var(--border); +} + +.deleted-text { font-size: calc(0.8125rem * var(--font-scale)); color: var(--text-tertiary); font-style: italic; } + +.msg-text { + font-size: calc(0.875rem * var(--font-scale)); + line-height: 1.5; + white-space: pre-wrap; +} + +.mention { + color: #1a5ca8; + font-weight: 600; + background: rgba(26,92,168,0.1); + border-radius: 3px; + padding: 0 2px; +} + +/* Sender bubble — primary colour is the background, so mention must contrast against it */ +.out .mention { + color: #ffffff; + background: rgba(255,255,255,0.22); +} + +.msg-image { + max-width: 240px; + max-height: 240px; + border-radius: 12px; + display: block; + cursor: pointer; + object-fit: cover; +} + +.msg-time { + font-size: calc(0.6875rem * var(--font-scale)); + color: var(--text-tertiary); + white-space: nowrap; + flex-shrink: 0; + padding-bottom: 4px; +} + +/* Reactions */ +.reactions { + display: flex; + flex-wrap: wrap; + gap: 4px; + margin-top: 4px; + padding: 0 4px; +} + +.reaction-btn { + display: flex; + align-items: center; + gap: 3px; + padding: 3px 8px; + border-radius: 12px; + background: var(--surface); + border: 1px solid var(--border); + font-size: calc(0.875rem * var(--font-scale)); + cursor: pointer; + transition: var(--transition); +} +.reaction-count { font-size: calc(0.75rem * var(--font-scale)); color: var(--text-secondary); } +.reaction-btn.active { background: var(--primary-light); border-color: var(--primary); } +.reaction-btn.active .reaction-count { color: var(--primary); } +.reaction-btn:hover { background: var(--primary-light); } +.reaction-remove { + font-size: 13px; + color: var(--primary); + font-weight: 700; + margin-left: 1px; + line-height: 1; + opacity: 0; + transition: opacity 0.15s; +} +.reaction-btn:hover .reaction-remove { opacity: 1; } + +/* Link preview */ +.link-preview { + display: flex; + gap: 10px; + background: rgba(0,0,0,0.06); + border-radius: 10px; + padding: 10px; + margin-top: 6px; + text-decoration: none; + max-width: 280px; + overflow: hidden; + transition: var(--transition); +} +.link-preview:hover { background: rgba(0,0,0,0.1); } + +.link-preview-img { + width: 60px; + height: 60px; + border-radius: 6px; + object-fit: cover; + flex-shrink: 0; +} + +.link-preview-content { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; + flex: 1; +} + +.link-site { font-size: 11px; color: var(--text-tertiary); text-transform: uppercase; letter-spacing: 0.5px; } +.link-title { font-size: 13px; font-weight: 600; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } +.link-desc { font-size: 12px; color: var(--text-secondary); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } + +.out .link-preview { background: rgba(255,255,255,0.15); } +.out .link-title { color: white; } +.out .link-desc { color: rgba(255,255,255,0.8); } + +/* Emoji-only messages: no bubble background, large size */ +.msg-bubble.emoji-only { + background: transparent !important; + border: none !important; + box-shadow: none !important; + padding: 2px 4px; +} +.msg-bubble.emoji-only::after { display: none; } + +.msg-text.emoji-msg { + font-size: 3em; + line-height: 1.1; + margin: 0; + user-select: text; +} + diff --git a/frontend/src/components/Message.jsx b/frontend/src/components/Message.jsx new file mode 100644 index 0000000..c51b187 --- /dev/null +++ b/frontend/src/components/Message.jsx @@ -0,0 +1,344 @@ +import { useState, useRef, useEffect } from 'react'; +import Avatar from './Avatar.jsx'; +import UserProfilePopup from './UserProfilePopup.jsx'; +import ImageLightbox from './ImageLightbox.jsx'; +import Picker from '@emoji-mart/react'; +import data from '@emoji-mart/data'; +import { parseTS } from '../utils/api.js'; +import './Message.css'; + +const QUICK_EMOJIS = ['👍', '❤️', '😂', '😮', '😢', '🙏']; + +function formatMsgContent(content) { + if (!content) return ''; + // First handle @mentions + let html = content.replace(/@\[([^\]]+)\]/g, (_, name) => `@${name}`); + // Then linkify bare URLs (not already inside a tag) + html = html.replace(/(https?:\/\/[^\s<>"]+)/g, (url) => { + // Trim trailing punctuation that's unlikely to be part of the URL + const trimmed = url.replace(/[.,!?;:)\]]+$/, ''); + const trailing = url.slice(trimmed.length); + return `${trimmed}${trailing}`; + }); + return html; +} + + +// Detect emoji-only messages for large rendering +function isEmojiOnly(str) { + if (!str || str.length > 12) return false; + const emojiRegex = /^(\p{Emoji_Presentation}|\p{Extended_Pictographic}|\uFE0F|\u200D|[\u{1F1E0}-\u{1F1FF}])+$/u; + return emojiRegex.test(str.trim()); +} + +export default function Message({ message: msg, prevMessage, currentUser, onReply, onDelete, onReact, onDirectMessage, isDirect, onlineUserIds = new Set() }) { + const [showActions, setShowActions] = useState(false); + const [showOptionsMenu, setShowOptionsMenu] = useState(false); + const longPressTimer = useRef(null); + const optionsMenuRef = useRef(null); + const [showEmojiPicker, setShowEmojiPicker] = useState(false); + const wrapperRef = useRef(null); + const pickerRef = useRef(null); + const avatarRef = useRef(null); + const [showProfile, setShowProfile] = useState(false); + const [lightboxSrc, setLightboxSrc] = useState(null); + const [pickerOpensDown, setPickerOpensDown] = useState(false); + + const isOwn = msg.user_id === currentUser.id; + const isDeleted = !!msg.is_deleted; + const isSystem = msg.type === 'system'; + + // These must be computed before any early returns that reference them + const showDateSep = !prevMessage || + parseTS(msg.created_at).toDateString() !== parseTS(prevMessage.created_at).toDateString(); + + const prevSameUser = !showDateSep && prevMessage && + prevMessage.user_id === msg.user_id && + prevMessage.type !== 'system' && msg.type !== 'system'; + + const canDelete = !msg.is_deleted && ( + msg.user_id === currentUser.id || + currentUser.role === 'admin' || + msg.group_owner_id === currentUser.id + ); + + // Close emoji picker when clicking outside + useEffect(() => { + if (!showEmojiPicker) return; + const handler = (e) => { + if (pickerRef.current && !pickerRef.current.contains(e.target)) { + setShowEmojiPicker(false); + } + }; + document.addEventListener('mousedown', handler); + return () => document.removeEventListener('mousedown', handler); + }, [showEmojiPicker]); + + // Close options menu on outside click + useEffect(() => { + if (!showOptionsMenu) return; + const close = (e) => { + if (optionsMenuRef.current && !optionsMenuRef.current.contains(e.target)) { + setShowOptionsMenu(false); + } + }; + document.addEventListener('mousedown', close); + document.addEventListener('touchstart', close); + return () => { + document.removeEventListener('mousedown', close); + document.removeEventListener('touchstart', close); + }; + }, [showOptionsMenu]); + + const handleReact = (emoji) => { + onReact(msg.id, emoji); + setShowEmojiPicker(false); + }; + + const handleCopy = () => { + if (!msg.content) return; + navigator.clipboard.writeText(msg.content).catch(() => {}); + }; + + const handleTogglePicker = () => { + if (!showEmojiPicker && wrapperRef.current) { + const rect = wrapperRef.current.getBoundingClientRect(); + setPickerOpensDown(rect.top < 400); + } + setShowEmojiPicker(p => !p); + }; + + // Long press for mobile action menu (DMs only) + const handleTouchStart = () => { + if (!isDirect) return; + longPressTimer.current = setTimeout(() => setShowOptionsMenu(true), 500); + }; + const handleTouchEnd = () => { + if (longPressTimer.current) clearTimeout(longPressTimer.current); + }; + + // Deleted messages are filtered out by ChatWindow, but guard here too + if (isDeleted) return null; + + // System messages render as a simple centred notice + if (isSystem) { + return ( + <> + {showDateSep && ( +
{formatDate(msg.created_at)}
+ )} +
{msg.content}
+ + ); + } + + const reactionMap = {}; + for (const r of (msg.reactions || [])) { + if (!reactionMap[r.emoji]) reactionMap[r.emoji] = { count: 0, users: [], hasMe: false }; + reactionMap[r.emoji].count++; + reactionMap[r.emoji].users.push(r.user_name); + if (r.user_id === currentUser.id) reactionMap[r.emoji].hasMe = true; + } + + const msgUser = { + id: msg.user_id, + name: msg.user_name, + display_name: msg.user_display_name, + avatar: msg.user_avatar, + role: msg.user_role, + status: msg.user_status, + hide_admin_tag: msg.user_hide_admin_tag, + about_me: msg.user_about_me, + allow_dm: msg.user_allow_dm, + }; + + return ( + <> + {showDateSep && ( +
+ {formatDate(msg.created_at)} +
+ )} + +
+ {!isOwn && !prevSameUser && ( +
setShowProfile(p => !p)} + onMouseEnter={e => e.currentTarget.style.boxShadow = '0 0 0 2px var(--primary)'} + onMouseLeave={e => e.currentTarget.style.boxShadow = 'none'} + > + + {!!(onlineUserIds instanceof Set ? onlineUserIds.has(Number(msg.user_id)) : false) && ( + + )} +
+ )} + {!isOwn && prevSameUser &&
} + +
+ {!isOwn && !prevSameUser && ( +
+ {msgUser.display_name || msgUser.name} + {msgUser.role === 'admin' && !msgUser.hide_admin_tag && Admin} + {msgUser.status !== 'active' && (inactive)} +
+ )} + + {/* Reply preview */} + {msg.reply_to_id && ( +
+
+
+
{msg.reply_user_display_name || msg.reply_user_name}
+
+ {msg.reply_is_deleted ? Deleted message + : msg.reply_image_url ? '📷 Image' + : msg.reply_content} +
+
+
+ )} + + {/* Bubble + actions together so actions hover above bubble */} +
+
setShowActions(true)} + onMouseLeave={() => { if (!showEmojiPicker && !showOptionsMenu) setShowActions(false); }} + onTouchStart={handleTouchStart} + onTouchEnd={handleTouchEnd} + onTouchMove={handleTouchEnd} + onContextMenu={isDirect ? (e => { e.preventDefault(); setShowOptionsMenu(true); }) : undefined} + > + {/* Actions toolbar — floats above the bubble, aligned to correct side */} + {!isDeleted && (showActions || showEmojiPicker) && ( +
+ {QUICK_EMOJIS.map(e => ( + + ))} + + + {msg.content && ( + + )} + {canDelete && ( + + )} + + {/* Emoji picker anchored to the toolbar */} + {showEmojiPicker && ( +
e.stopPropagation()} + > + handleReact(e.native)} theme="light" previewPosition="none" skinTonePosition="none" /> +
+ )} +
+ )} + +
+ {msg.image_url && ( + attachment setLightboxSrc(msg.image_url)} + /> + )} + {msg.content && ( + isEmojiOnly(msg.content) && !msg.image_url + ?

{msg.content}

+ :

+ )} + {msg.link_preview && } +

+
+ + {formatTime(msg.created_at)} + + +
+ + {Object.keys(reactionMap).length > 0 && ( +
+ {Object.entries(reactionMap).map(([emoji, { count, users, hasMe }]) => ( + + ))} +
+ )} +
+
+ {showProfile && ( + setShowProfile(false)} + onDirectMessage={onDirectMessage} + /> + )} + {lightboxSrc && ( + setLightboxSrc(null)} /> + )} + + ); +} + +function LinkPreview({ data: raw }) { + let d; + try { d = typeof raw === 'string' ? JSON.parse(raw) : raw; } catch { return null; } + if (!d?.title) return null; + + return ( + + {d.image && e.target.style.display = 'none'} />} +
+ {d.siteName && {d.siteName}} + {d.title} + {d.description && {d.description}} +
+
+ ); +} + +function formatTime(dateStr) { + return parseTS(dateStr).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); +} + +function formatDate(dateStr) { + const d = parseTS(dateStr); + const now = new Date(); + if (d.toDateString() === now.toDateString()) return 'Today'; + const yest = new Date(now); yest.setDate(yest.getDate() - 1); + if (d.toDateString() === yest.toDateString()) return 'Yesterday'; + return d.toLocaleDateString([], { weekday: 'long', month: 'long', day: 'numeric' }); +} diff --git a/frontend/src/components/MessageInput.css b/frontend/src/components/MessageInput.css new file mode 100644 index 0000000..94cfee5 --- /dev/null +++ b/frontend/src/components/MessageInput.css @@ -0,0 +1,249 @@ +.message-input-area { + background: white; + border-top: 1px solid var(--border); + padding: 12px 16px; + padding-bottom: calc(12px + env(safe-area-inset-bottom, 0px)); + display: flex; + flex-direction: column; + gap: 8px; + flex-shrink: 0; /* never compress — always visible above keyboard */ + position: relative; + z-index: 2; + /* Centre input content with max-width on wide screens */ + align-items: stretch; +} + +/* All direct children of the input area capped at 1024px and centred */ +.message-input-area > * { + max-width: 1024px; + width: 100%; + align-self: center; + box-sizing: border-box; +} + +.reply-bar-input { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + background: var(--primary-light); + border-radius: var(--radius); + border-left: 3px solid var(--primary); +} + +.reply-indicator { + display: flex; + align-items: center; + gap: 6px; + flex: 1; + overflow: hidden; + font-size: 13px; + color: var(--primary); +} + +.reply-preview-text { + color: var(--text-secondary); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: 200px; +} + +.img-preview-bar { + display: flex; + align-items: center; + gap: 12px; + padding: 8px; + background: var(--background); + border-radius: var(--radius); +} + +.img-preview { + width: 56px; + height: 56px; + object-fit: cover; + border-radius: var(--radius); +} + +.link-preview-bar { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 12px; + background: var(--background); + border-radius: var(--radius); + border: 1px solid var(--border); +} + +.link-prev-img { + width: 40px; + height: 40px; + object-fit: cover; + border-radius: 4px; + flex-shrink: 0; +} + +.mention-dropdown { + background: white; + border: 1px solid var(--border); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-lg); + overflow: hidden; + max-height: 200px; + overflow-y: auto; +} + +.mention-item { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 14px; + width: 100%; + font-size: 14px; + transition: var(--transition); + cursor: pointer; +} +.mention-item:hover, .mention-item.active { background: var(--primary-light); } + +.mention-avatar { + width: 28px; + height: 28px; + border-radius: 50%; + background: var(--primary); + color: white; + font-size: 12px; + font-weight: 600; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; +} + +.mention-role { + margin-left: auto; + font-size: 11px; + color: var(--text-tertiary); + text-transform: capitalize; +} + +.input-row { + display: flex; + align-items: flex-end; + gap: 8px; +} + +.input-action { + color: var(--text-secondary); + flex-shrink: 0; + margin-bottom: 2px; +} +.input-action:hover { color: var(--primary); } + +.input-wrap { + flex: 1; + min-width: 0; +} + +.msg-input { + width: 100%; + min-height: 40px; + max-height: calc(1.4em * 5 + 20px); /* 5 lines × line-height + padding */ + padding: 10px 14px; + border: 1px solid var(--border); + border-radius: 20px; + font-size: calc(0.875rem * var(--font-scale)); + line-height: 1.4; + font-family: var(--font); + color: var(--text-primary); + background: var(--surface-variant); + transition: border-color var(--transition); + overflow-y: hidden; + resize: none; +} +.msg-input:focus { outline: none; border-color: var(--primary); background: var(--surface-variant); } +.msg-input::placeholder { color: var(--text-tertiary); } + +.send-btn { + width: 40px; + height: 40px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + color: var(--text-tertiary); + transition: var(--transition); + background: var(--background); +} +.send-btn.active { + background: var(--primary); + color: white; +} +.send-btn.active:hover { background: var(--primary-dark); } +.send-btn:disabled { opacity: 0.4; cursor: default; } + +/* + attach button */ +.attach-wrap { + position: relative; + flex-shrink: 0; +} + +.attach-btn { + color: var(--primary); +} +.attach-btn:hover { + color: var(--primary-dark); +} + +/* Attach menu popup */ +.attach-menu { + position: absolute; + bottom: calc(100% + 8px); + left: 0; + background: white; + border: 1px solid var(--border); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-lg); + overflow: hidden; + z-index: 100; + min-width: 140px; +} + +.attach-item { + display: flex; + align-items: center; + gap: 10px; + padding: 11px 16px; + width: 100%; + font-size: 14px; + color: var(--text-primary); + transition: var(--transition); + white-space: nowrap; +} +.attach-item:hover { + background: var(--primary-light); + color: var(--primary); +} +.attach-item svg { + flex-shrink: 0; + color: var(--text-secondary); +} +.attach-item:hover svg { + color: var(--primary); +} + +/* Emoji picker popover — positioned above the input area */ +.emoji-input-picker { + position: absolute; + bottom: calc(100% + 4px); + left: 0; + z-index: 200; +} + +/* PC only: enforce minimum width on the input row so send button never disappears */ +@media (pointer: fine) and (hover: hover) { + .input-row { + min-width: 480px; + } +} + diff --git a/frontend/src/components/MessageInput.jsx b/frontend/src/components/MessageInput.jsx new file mode 100644 index 0000000..53e6637 --- /dev/null +++ b/frontend/src/components/MessageInput.jsx @@ -0,0 +1,388 @@ +import { useState, useRef, useCallback, useEffect } from 'react'; +import { api } from '../utils/api.js'; +import data from '@emoji-mart/data'; +import Picker from '@emoji-mart/react'; +import './MessageInput.css'; + +const URL_REGEX = /https?:\/\/[^\s]+/g; + +// Detect if a string is purely emoji characters (no other text) +function isEmojiOnly(str) { + const emojiRegex = /^(\p{Emoji_Presentation}|\p{Extended_Pictographic}|\uFE0F|\u200D|[\u{1F1E0}-\u{1F1FF}])+$/u; + return emojiRegex.test(str.trim()); +} + +export default function MessageInput({ group, replyTo, onCancelReply, onSend, onTyping, onlineUserIds = new Set() }) { + const [text, setText] = useState(''); + const [imageFile, setImageFile] = useState(null); + const [imagePreview, setImagePreview] = useState(null); + const [mentionSearch, setMentionSearch] = useState(''); + const [mentionResults, setMentionResults] = useState([]); + const [mentionIndex, setMentionIndex] = useState(-1); + const [showMention, setShowMention] = useState(false); + const [linkPreview, setLinkPreview] = useState(null); + const [loadingPreview, setLoadingPreview] = useState(false); + const [showAttachMenu, setShowAttachMenu] = useState(false); + const [showEmojiPicker, setShowEmojiPicker] = useState(false); + const inputRef = useRef(null); + const typingTimer = useRef(null); + const wasTyping = useRef(false); + const mentionStart = useRef(-1); + const fileInput = useRef(null); + const cameraInput = useRef(null); + const attachMenuRef = useRef(null); + const emojiPickerRef = useRef(null); + + // Close attach menu / emoji picker on outside click + useEffect(() => { + const handler = (e) => { + if (attachMenuRef.current && !attachMenuRef.current.contains(e.target)) { + setShowAttachMenu(false); + } + if (emojiPickerRef.current && !emojiPickerRef.current.contains(e.target)) { + setShowEmojiPicker(false); + } + }; + document.addEventListener('mousedown', handler); + return () => document.removeEventListener('mousedown', handler); + }, []); + + // Handle typing notification + const handleTypingChange = (value) => { + if (value && !wasTyping.current) { + wasTyping.current = true; + onTyping(true); + } + if (typingTimer.current) clearTimeout(typingTimer.current); + typingTimer.current = setTimeout(() => { + if (wasTyping.current) { + wasTyping.current = false; + onTyping(false); + } + }, 2000); + }; + + // Link preview — 5 second timeout, then abandon and enable Send + const previewTimeoutRef = useRef(null); + + const fetchPreview = useCallback(async (url) => { + setLoadingPreview(true); + setLinkPreview(null); + + if (previewTimeoutRef.current) clearTimeout(previewTimeoutRef.current); + const abandonTimer = setTimeout(() => { + setLoadingPreview(false); + }, 5000); + previewTimeoutRef.current = abandonTimer; + + try { + const { preview } = await api.getLinkPreview(url); + clearTimeout(abandonTimer); + if (preview) setLinkPreview(preview); + } catch { + clearTimeout(abandonTimer); + } + setLoadingPreview(false); + }, []); + + const handleChange = (e) => { + const val = e.target.value; + setText(val); + handleTypingChange(val); + + const el = e.target; + el.style.height = 'auto'; + const lineHeight = parseFloat(getComputedStyle(el).lineHeight); + const maxHeight = lineHeight * 5 + 20; + el.style.height = Math.min(el.scrollHeight, maxHeight) + 'px'; + el.style.overflowY = el.scrollHeight > maxHeight ? 'auto' : 'hidden'; + + const cur = e.target.selectionStart; + const lastAt = val.lastIndexOf('@', cur - 1); + if (lastAt !== -1) { + const between = val.slice(lastAt + 1, cur); + if (!between.includes(' ') && !between.includes('\n')) { + mentionStart.current = lastAt; + setMentionSearch(between); + setShowMention(true); + api.searchUsers(between, group?.id).then(({ users }) => { + setMentionResults(users); + setMentionIndex(0); + }).catch(() => {}); + return; + } + } + setShowMention(false); + + const urls = val.match(URL_REGEX); + if (urls && urls[0] !== linkPreview?.url) { + fetchPreview(urls[0]); + } else if (!urls) { + setLinkPreview(null); + } + }; + + const insertMention = (user) => { + const before = text.slice(0, mentionStart.current); + const after = text.slice(inputRef.current.selectionStart); + const name = user.display_name || user.name; + setText(before + `@[${name}] ` + after); + setShowMention(false); + setMentionResults([]); + inputRef.current.focus(); + }; + + const handleKeyDown = (e) => { + if (showMention && mentionResults.length > 0) { + if (e.key === 'ArrowDown') { e.preventDefault(); setMentionIndex(i => Math.min(i + 1, mentionResults.length - 1)); return; } + if (e.key === 'ArrowUp') { e.preventDefault(); setMentionIndex(i => Math.max(i - 1, 0)); return; } + if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); if (mentionIndex >= 0) insertMention(mentionResults[mentionIndex]); return; } + if (e.key === 'Escape') { setShowMention(false); return; } + } + + if (e.key === 'Enter' && !e.shiftKey) { + e.preventDefault(); + handleSend(); + } + }; + + const handleSend = async () => { + const trimmed = text.trim(); + if (!trimmed && !imageFile) return; + + const lp = linkPreview; + setText(''); + setLinkPreview(null); + setImageFile(null); + setImagePreview(null); + wasTyping.current = false; + onTyping(false); + if (inputRef.current) { + inputRef.current.style.height = 'auto'; + inputRef.current.style.overflowY = 'hidden'; + } + + const emojiOnly = !!trimmed && isEmojiOnly(trimmed); + await onSend({ content: trimmed || null, imageFile, linkPreview: lp, emojiOnly }); + }; + + // Insert emoji at cursor position in the textarea + const handleEmojiSelect = (emoji) => { + setShowEmojiPicker(false); + const el = inputRef.current; + const native = emoji.native; + + if (el) { + const start = el.selectionStart ?? 0; + const end = el.selectionEnd ?? 0; + const newText = text.slice(0, start) + native + text.slice(end); + setText(newText); + // Restore focus and move cursor after the inserted emoji + requestAnimationFrame(() => { + el.focus(); + const pos = start + native.length; + el.setSelectionRange(pos, pos); + // Resize textarea + el.style.height = 'auto'; + const lineHeight = parseFloat(getComputedStyle(el).lineHeight); + const maxHeight = lineHeight * 5 + 20; + el.style.height = Math.min(el.scrollHeight, maxHeight) + 'px'; + el.style.overflowY = el.scrollHeight > maxHeight ? 'auto' : 'hidden'; + }); + } else { + // No ref yet — just append + setText(prev => prev + native); + } + }; + + const compressImage = (file) => new Promise((resolve) => { + const MAX_PX = 1920; + const QUALITY = 0.82; + const isPng = file.type === 'image/png'; + const img = new Image(); + const url = URL.createObjectURL(file); + img.onload = () => { + URL.revokeObjectURL(url); + let { width, height } = img; + if (width <= MAX_PX && height <= MAX_PX) { + // already small + } else { + const ratio = Math.min(MAX_PX / width, MAX_PX / height); + width = Math.round(width * ratio); + height = Math.round(height * ratio); + } + const canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + const ctx = canvas.getContext('2d'); + if (!isPng) { + ctx.fillStyle = '#ffffff'; + ctx.fillRect(0, 0, width, height); + } + ctx.drawImage(img, 0, 0, width, height); + if (isPng) { + canvas.toBlob(blob => resolve(new File([blob], file.name, { type: 'image/png' })), 'image/png'); + } else { + canvas.toBlob(blob => resolve(new File([blob], file.name.replace(/\.[^.]+$/, '.jpg'), { type: 'image/jpeg' })), 'image/jpeg', QUALITY); + } + }; + img.src = url; + }); + + const handleImageSelect = async (e) => { + const file = e.target.files?.[0]; + if (!file) return; + const compressed = await compressImage(file); + setImageFile(compressed); + const reader = new FileReader(); + reader.onload = (e) => setImagePreview(e.target.result); + reader.readAsDataURL(compressed); + setShowAttachMenu(false); + }; + + // Detect mobile (touch device) + const isMobile = () => window.matchMedia('(pointer: coarse)').matches; + + return ( +
+ {/* Reply preview */} + {replyTo && ( +
+
+ + Replying to {replyTo.user_display_name || replyTo.user_name} + {replyTo.content?.slice(0, 60) || (replyTo.image_url ? '📷 Image' : '')} +
+ +
+ )} + + {/* Image preview */} + {imagePreview && ( +
+ preview + +
+ )} + + {/* Link preview */} + {linkPreview && ( +
+ {linkPreview.image && e.target.style.display='none'} />} +
+ {linkPreview.siteName && {linkPreview.siteName}} + {linkPreview.title} +
+ +
+ )} + + {/* Mention dropdown */} + {showMention && mentionResults.length > 0 && ( +
+ {mentionResults.map((u, i) => ( + + ))} +
+ )} + +
+ + {/* + button — attach menu trigger */} +
+ + + {showAttachMenu && ( +
+ {/* Photo from library */} + + {/* Camera — mobile only */} + {isMobile() && ( + + )} + {/* Emoji */} + +
+ )} +
+ + {/* Hidden file inputs */} + + + + {/* Emoji picker popover */} + {showEmojiPicker && ( +
+ +
+ )} + +
+