From 9da51a1e6b8ee59c5e2f5a71a37a412c6580a1b0 Mon Sep 17 00:00:00 2001 From: Musselman Date: Mon, 20 Nov 2023 22:10:40 -0600 Subject: [PATCH] Switch Repo to notatio/notatio --- .env.example | 16 + .gitignore | 43 +++ Dockerfile | 29 ++ Jenkinsfile | 70 ++++ LICENSE | 661 +++++++++++++++++++++++++++++++++ README.md | 105 ++++++ database.go | 131 +++++++ docker-compose.yaml | 31 ++ editor.go | 223 +++++++++++ editor_templates/Journal Entry | 32 ++ editor_templates/SMART Goal | 39 ++ export.go | 292 +++++++++++++++ go.mod | 24 ++ go.sum | 95 +++++ list.go | 326 ++++++++++++++++ main.go | 359 ++++++++++++++++++ static/build/editor.js | 393 ++++++++++++++++++++ static/favicon.ico | Bin 0 -> 1406 bytes tables.go | 114 ++++++ templates/edit.html | 181 +++++++++ templates/index.html | 357 ++++++++++++++++++ templates/kanban.html | 146 ++++++++ templates/list.html | 212 +++++++++++ templates/newuser.html | 24 ++ user.go | 200 ++++++++++ wait-for-postgres.sh | 14 + 26 files changed, 4117 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 Jenkinsfile create mode 100644 LICENSE create mode 100644 README.md create mode 100644 database.go create mode 100644 docker-compose.yaml create mode 100644 editor.go create mode 100644 editor_templates/Journal Entry create mode 100644 editor_templates/SMART Goal create mode 100644 export.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 list.go create mode 100644 main.go create mode 100644 static/build/editor.js create mode 100644 static/favicon.ico create mode 100644 tables.go create mode 100644 templates/edit.html create mode 100644 templates/index.html create mode 100644 templates/kanban.html create mode 100644 templates/list.html create mode 100644 templates/newuser.html create mode 100644 user.go create mode 100755 wait-for-postgres.sh diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..0445dbe --- /dev/null +++ b/.env.example @@ -0,0 +1,16 @@ +# .env.example +# Rename me to .env to use me + +# PostgreSQL settings +DB_HOST=postgres +PGPORT=5432 +DB_USER=postgres +POSTGRES_PASSWORD=your_postgres_password +DB_SSL_MODE=disable +# SSL mode Can be disable, allow, prefer, require, verify-ca, verify-full + +# Notatio admin user +ADMIN_USER=your_admin_user +ADMIN_PASS=your_admin_password +ADMIN_EMAIL=your_admin_email +ADMIN_NAME=your_display_name \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fc17052 --- /dev/null +++ b/.gitignore @@ -0,0 +1,43 @@ +# ---> Rust +# Generated by Cargo +# will have compiled files and executables +debug/ +target/ +uploads/ + +notatio + +# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries +# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html +Cargo.lock + +# These are backup files generated by rustfmt +**/*.rs.bk + +# MSVC Windows builds of rustc generate these, which store debugging information +*.pdb + +# ---> Go +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ + +# Go workspace file +go.work + +.env +notatio/ +notatio-uploads/ +.vscode/settings.json diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..7867820 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,29 @@ +# Stage 1: Build the Go application +FROM docker.io/golang:1.20-alpine as builder +RUN apk --no-cache add ca-certificates git +WORKDIR /build +COPY go.mod go.sum ./ +RUN go mod download + +COPY editor_templates/ editor_templates/ +COPY templates/ templates/ +COPY static/ static/ +COPY wait-for-postgres.sh ./ + +COPY . ./ +RUN go build -o /notatio + +# Stage 2: Create the final image +FROM alpine +WORKDIR / + +COPY --from=builder /notatio . + +COPY --from=builder /build/templates/ templates/ +COPY --from=builder /build/editor_templates/ editor_templates/ +COPY --from=builder /build/static/ static/ +COPY --from=builder /build/wait-for-postgres.sh ./wait-for-postgres.sh + +EXPOSE 9991 +CMD ["./notatio"] +LABEL name=notatio version=latest diff --git a/Jenkinsfile b/Jenkinsfile new file mode 100644 index 0000000..d4bfe00 --- /dev/null +++ b/Jenkinsfile @@ -0,0 +1,70 @@ +pipeline { + agent { + label 'podman' + } + tools { + go '1.21.1' + } + environment { + registry = "docker.io/notatio/notatio" + registryCredential = 'docker-hub-credentials' + podmanImage = '' + } + stages { + stage('Clone repository') { + steps { + git branch: 'main', credentialsId: 'codeberg-musselman-builder-jenkins', url: 'https://codeberg.org/Musselman/Notatio.git' + } + } + stage('Retrieve Git tag') { + steps { + script { + def tagOutput = sh(script: 'git describe --abbrev=0 --tags || true', returnStdout: true).trim() + if (tagOutput.isEmpty() || tagOutput.equals("fatal: No names found, cannot describe anything.")) { + TAG = 'latest' // Set a default tag if no tags are found + echo "No tags found, using default tag: ${TAG}" + } else { + TAG = tagOutput + echo "Latest tag found: ${TAG}" + } + } + } + } + stage('Build') { + steps { + echo 'Building..' + sh 'go build' + } + } + stage('Test') { + steps { + echo 'Testing..' + echo 'No Testing to do currently..' + } + } + stage('Building image') { + steps { + script { + sh "podman build -t notatio ." + } + } + } + stage('Push image') { + steps { + script { + withCredentials([usernamePassword(credentialsId: registryCredential, passwordVariable: 'REGISTRY_PASSWORD', usernameVariable: 'REGISTRY_USERNAME')]) { + sh "podman login -u $REGISTRY_USERNAME -p $REGISTRY_PASSWORD docker.io" + sh "podman push notatio $registry:${TAG}" + sh "podman logout $registry" + } + } + } + } + stage('Cleanup') { + steps { + sh "podman rmi -a -f" + } + } + } +} + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + 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 + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7cb6ce2 --- /dev/null +++ b/README.md @@ -0,0 +1,105 @@ +# Notatio + +![Build Status](https://jinkies.privacyquest.net/buildStatus/icon?job=Notatio%2Fmain) + +## 💡 About + +**Notatio is currently under heavy development, and as such there is the possibility breaking changes** + +Notatio is a self-hostable, containerized, web-based text editor. The main objective of the project is to create a platform independent text editor (and productivity management suite). I hope to develop this as an alterniative to propriatry software like obsidian and Notion.so which I have loved and used in the past. This software is currently being created as part of a Senior Capstone, but there are plans to continue developing it afterwards. + +## 🛣️ **Roadmap** + +#### In Progress + +- 🕓 Building Custom Text Editor +- 🕓 Add Kanban Board + + +#### Planned V1 Release + +- [ ] Flesh out File Management Operations +- [ ] NoSQL setup option + +#### Planned V1.1 Release + +- [ ] Collaborative Editing +- [ ] File Versiong + +#### Planned v1.2 Releaase + +- [ ] End to End Encryption + + + +## 💾 **Download** + +Downloading Notatio is simple! Just clone the repository using the command below: + +```bash +git clone https://codeberg.org/musselman/notatio +``` + +## 🚀 **Running** + +There are two ways to run Notatio. + +### 📦**Container (Recommended)** + +--- + +#### Docker + +Before running the Docker container, make sure to copy `.env.example` to `.env` and customize the environment variables to your preferences: + +```bash +cp .env.example .env +``` + +Launch the containers using the following command: + +```bash +docker-compose up -d +``` + +#### Podman (Alternative to Docker) + +1. Make sure you have Podman and Podman-Compose installed on your system. +2. Copy `.env.example` to `.env` and modify the environment variables as per your requirements. +3. Edit the docker-compose.yaml to have `:Z`'s at the end of volumes. This is to tell SELinux that the volumes should be labeled with the appropriate security context. +4. Launch the containers using the following command: + +```bash +podman-compose up -d +``` + +Please note that using Podman instead of Docker requires you to have Podman installed and properly configured on your system. The usage and setup of Podman may differ from Docker, so please consult the Podman documentation for further information. + +### 🛠️ Go Binary (Advanced) + +--- + +Note: This setup requires a running PostgreSQL database. Please set it up before proceeding. + +To run Notatio using the Go binary, follow the steps below: + +1. Build the Go binary. +2. Pass the necessary environment variables to the program, editing them to provide the required information for your database. + +Example command: + +```bash +DB_HOST=127.0.0.1 PGPORT=5432 DB_USER=postgres POSTGRES_PASSWORD=mysecretpassword DB_SSL_MODE=disable ADMIN_USER=admin_user ADMIN_PASS=admin_is_not_a_good_password! ./notatio +``` + +Please note that this method is more advanced and requires additional setup. + +## 🤝 Contributing + +As this is currently an accademic project I cannot accept contributions! If you are interested in doing so please reach out to me on or after December 7th. + + + +## 📄 License + +This project is licensed under the AGPL - see the [LICENSE](./LICENSE) file for details diff --git a/database.go b/database.go new file mode 100644 index 0000000..0254368 --- /dev/null +++ b/database.go @@ -0,0 +1,131 @@ +package main + +import ( + "fmt" + "path/filepath" + "strings" + "time" +) + +// insertFileIntoDatabase inserts a file into the database with the provided details. +func insertFileIntoDatabase(username, filename string, creationTime int64, lastEdited int64, lastOpened int64) error { + // Retrieve the user ID based on the username. + userID, err := getUserUUID(username) + if err != nil { + return err + } + + // Insert the file details into the database. + _, err = db.Exec("INSERT INTO files (user_id, filename, creation_time, last_edited, last_opened) VALUES ($1, $2, $3, $4, $5)", + userID, filename, time.Unix(creationTime, 0), time.Unix(lastEdited, 0), time.Unix(lastOpened, 0)) + return err +} + +// insertUserIntoDatabase inserts a user into the database with the provided details. +func insertUserIntoDatabase(username, hashedPassword string, accountType string, userUUID string, name string, email string) error { + // Insert the user details into the database. + _, err := db.Exec("INSERT INTO users (username, password, accountType, uuid, name, email) VALUES ($1, $2, $3, $4, $5, $6)", username, hashedPassword, accountType, userUUID, name, email) + return err +} + +// deleteFileFromDatabase deletes a file from the database for the specified user and filename. +func deleteFileFromDatabase(username, filename string) error { + // Retrieve the user UUID based on the username. + userUUID, err := getUserUUID(username) + if err != nil { + return err + } + + // Delete the file from the database. + _, err = db.Exec("DELETE FROM files WHERE user_id = $1 AND filename = $2", userUUID, filename) + return err +} + +// UpdateEditedTimestamp updates the last_edited timestamp for a file in the database. +func UpdateEditedTimestamp(username, filename string) error { + // Retrieve the user UUID based on the username. + userUUID, err := getUserUUID(username) + if err != nil { + return err + } + + // Update the last_edited timestamp for the file. + _, err = db.Exec("UPDATE files SET last_edited = $1 WHERE user_id = $2 AND filename = $3", time.Now(), userUUID, filename) + return err +} + +// getName retrieves the name of a user based on their username. +func getName(username string) (string, error) { + // Retrieve the user UUID based on the username. + userUUID, err := getUserUUID(username) + if err != nil { + return "", err + } + + // Retrieve the name of the user from the database. + var name string + err = db.QueryRow("SELECT name FROM users WHERE uuid = $1", userUUID).Scan(&name) + if err != nil { + return "", err + } + + return name, nil +} + +// updateFilename updates the filename for a file in the database. +func updateFilename(username, oldFilename, newFilename string) error { + // Retrieve the user UUID based on the username. + userUUID, err := getUserUUID(username) + if err != nil { + return err + } + + // Check if the new filename already exists. + var count int + err = db.QueryRow("SELECT COUNT(*) FROM files WHERE user_id = $1 AND filename = $2", userUUID, newFilename).Scan(&count) + if err != nil { + return err + } + + // If a file with the new filename already exists, append a number to the end. + if count > 0 { + countSuffix := 1 + updatedFilename := newFilename + extension := filepath.Ext(newFilename) + filenameWithoutExt := strings.TrimSuffix(newFilename, extension) + + // Keep incrementing the countSuffix until a unique filename is found. + for count > 0 { + updatedFilename = fmt.Sprintf("%s_%d%s", filenameWithoutExt, countSuffix, extension) + + // Check if the updatedFilename already exists. + err = db.QueryRow("SELECT COUNT(*) FROM files WHERE user_id = $1 AND filename = $2", userUUID, updatedFilename).Scan(&count) + if err != nil { + return err + } + + countSuffix++ + } + + newFilename = updatedFilename + } + + // Update the filename in the database. + _, err = db.Exec("UPDATE files SET filename = $1 WHERE user_id = $2 AND filename = $3", newFilename, userUUID, oldFilename) + return err +} + +// isUsernameTaken checks if a username is already taken. +func isUsernameTaken(username string) (bool, error) { + username = strings.ToLower(username) + userUUID, err := getUserUUID(username) + if err != nil { + // Username is not taken. + fmt.Println("Username not taken:", username) + return false, nil + } + + // Username is taken. + fmt.Println("Username taken by user with UUID:", userUUID) + return true, nil +} diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..c970727 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,31 @@ +version: '3' + +services: + notatio: + image: notatio/notatio + container_name: notatio + env_file: + - .env + volumes: + - ./notatio-uploads:/uploads + - ./editor_templates:/editor_templates + ports: + - "9991:9991" + command: ["./wait-for-postgres.sh", "postgres", "${PGPORT}", "./notatio"] + depends_on: + - postgres + networks: + - notatio-network + + postgres: + image: postgres + container_name: postgres + env_file: + - .env + networks: + - notatio-network + #ports: + # - "5432:5432" + +networks: + notatio-network: diff --git a/editor.go b/editor.go new file mode 100644 index 0000000..2ebbd0e --- /dev/null +++ b/editor.go @@ -0,0 +1,223 @@ +package main + +import ( + "fmt" + "io" + "log" + "net/http" + "os" + "path/filepath" + "strings" + + md "github.com/JohannesKaufmann/html-to-markdown" + "github.com/JohannesKaufmann/html-to-markdown/plugin" + "github.com/gomarkdown/markdown" + "github.com/microcosm-cc/bluemonday" +) + +type Template struct { + TemplateName string `json:"templateName"` + Filename string `json:"filename"` +} + +func EditFile(w http.ResponseWriter, r *http.Request) { + userSession, err := validateSession(w, r) + if err != nil { + handleError(w, "Error validating session", err) + return + } + + // Get template and filename from query parameters + templateName := r.URL.Query().Get("template") + filename := r.URL.Query().Get("filename") + filePath := filepath.Join(fileUploadPath, userSession.username, filename) + + // Read file content + fileContent, err := readFileContent(filePath) + if err != nil { + handleError(w, "Error reading file content", err) + return + } + + // Apply template content if specified + if templateName != "" { + templatePath := filepath.Join(templateFilePath, templateName) + templateContent, err := readFileContent(templatePath) + if err != nil { + handleError(w, "Error reading template content", err) + return + } + // overwrites file content. Could also change this to append. + //TODO: Give user setting to choose which method of usage. + fileContent = markdown.ToHTML([]byte(templateContent), nil, nil) + } + + // Sanitize file content + sanitizedContent := sanitizeHTML(fileContent) + + // Convert file content based on file type + if filepath.Ext(filename) == ".md" { + // Convert Markdown to HTML + htmlContent := markdown.ToHTML([]byte(sanitizedContent), nil, nil) + fileContent = []byte(htmlContent) + } else if filepath.Ext(filename) == ".html" { + // Sanitize HTML content to prevent any malicious code + fileContent = []byte(sanitizedContent) + } + + templates, err := getTemplateList() + if err != nil { + handleError(w, "Error getting template list", err) + return + } + // Update the Templates slice to assign the current filename + for i := range templates { + templates[i].Filename = filename + } + data := struct { + Filename string + FileContent string + Templates []Template // Update type to []Template + }{ + Filename: filename, + FileContent: string(fileContent), + Templates: templates, // Assign the template list + } + + renderTemplate(w, "edit.html", data) +} + +func SaveFile(w http.ResponseWriter, r *http.Request) { + userSession, err := validateSession(w, r) + if err != nil { + handleError(w, "Error validating session", err) + return + } + + // Get filename from query parameters + filename := r.URL.Query().Get("filename") + newFilename := r.FormValue("filename") // Retrieve the new filename from the form + filePath := filepath.Join(fileUploadPath, userSession.username, filename) + newFilePath := filepath.Join(fileUploadPath, userSession.username, newFilename) // Create the new file path + + // If the new filename is different from the expected filename + if newFilename != filename { + + // Check if the file with the new filename already exists + _, err = os.Stat(newFilePath) + if err == nil { + // File with new filename already exists, generate a new unique filename + count := 1 + extension := filepath.Ext(newFilename) + filenameWithoutExt := strings.TrimSuffix(newFilename, extension) + + // Keep incrementing the count until a unique filename is found + for err == nil { + newFilename = fmt.Sprintf("%s_%d%s", filenameWithoutExt, count, extension) + newFilePath = filepath.Join(fileUploadPath, userSession.username, newFilename) + _, err = os.Stat(newFilePath) + count++ + } + } else if !os.IsNotExist(err) { + // Error accessing the file, handle the error or return an error response + handleError(w, "Error: Unable to access file", err) + return + } + + err := updateFilename(userSession.username, filename, newFilename) + if err != nil { + handleError(w, "Error updating filename", err) + return + } + + err = os.Rename(filePath, newFilePath) // Rename the file to the new filename + if err != nil { + handleError(w, "Error renaming file", err) + return + } + } + + // Create or open the file + file, err := os.Create(newFilePath) + if err != nil { + handleError(w, "Error creating file", err) + return + } + defer file.Close() + + // Read the edited content from the request form + editedContent := r.FormValue("editor") + // Convert edited content from HTML to Markdown if the file extension is .md + if strings.HasSuffix(newFilename, ".md") { + editedContent = convertHTMLtoMarkdown(editedContent) + } + // Write the edited content to the file + _, err = file.WriteString(editedContent) + if err != nil { + handleError(w, "Error writing edited content to file", err) + return + } + + // Update the edited timestamp for the user and file + UpdateEditedTimestamp(userSession.username, newFilename) + + http.Redirect(w, r, "/home", http.StatusSeeOther) +} + +func handleError(w http.ResponseWriter, errMsg string, err error) { + log.Printf("%s: %v", errMsg, err) +} + +func readFileContent(filePath string) ([]byte, error) { + file, err := os.Open(filePath) + if err != nil { + return nil, err + } + defer file.Close() + + return io.ReadAll(file) +} + +func sanitizeHTML(htmlContent []byte) []byte { + return bluemonday.UGCPolicy().SanitizeBytes(htmlContent) +} + +func convertHTMLtoMarkdown(html string) string { + options := md.Options{ + EscapeMode: "disabled", + } + converter := md.NewConverter("", true, &options) + converter.Use(plugin.Table()) + converter.Use(plugin.Strikethrough("~~")) + markdown, err := converter.ConvertString(html) + if err != nil { + log.Fatal(err) + } + return markdown +} + +func getTemplateList() ([]Template, error) { + dir, err := os.Open(templateFilePath) + if err != nil { + return nil, err + } + defer dir.Close() + + fileInfos, err := dir.Readdir(-1) + if err != nil { + return nil, err + } + + templates := make([]Template, 0) + for _, fileInfo := range fileInfos { + if !fileInfo.IsDir() { + template := Template{ + TemplateName: fileInfo.Name(), + Filename: "", + } + templates = append(templates, template) + } + } + + return templates, nil +} diff --git a/editor_templates/Journal Entry b/editor_templates/Journal Entry new file mode 100644 index 0000000..99432a9 --- /dev/null +++ b/editor_templates/Journal Entry @@ -0,0 +1,32 @@ +## 1. Today's Thoughts and Feelings +- Take a moment to reflect on your thoughts and feelings from the day. +- Write down any emotions or mental states you experienced throughout the day. +- Consider any significant events or interactions that impacted your mood. + +## 2. Gratitude +- List three things you are grateful for today. +- This section can help shift your focus towards gratitude and positivity. + +## 3. Achievement(s) of the Day +- Identify and record at least one accomplishment or achievement from the day. +- It can be something big or small, as long as you see it as a noteworthy success. + +## 4. Lessons Learned +- Reflect on any lessons or insights you gained throughout the day. +- Identify specific areas where you grew or areas where you could improve. + +## 5. Challenges Faced +- Describe any challenges or obstacles you encountered. +- Consider how you handled these challenges and any lessons you learned from them. + +## 6. Self-Care Activities +- Record any self-care activities you engaged in today. +- This can include exercise, personal hobbies, relaxation techniques, etc. + +## 7. Goals and Intentions +- State your short-term goals or intentions for the next day or week. +- This section helps you set a positive and focused mindset for the future. + +## 8. Additional Notes/Reflections +- Use this space to write any additional thoughts, reflections, or insights. +- Capture any memorable moments or ideas that you want to remember. \ No newline at end of file diff --git a/editor_templates/SMART Goal b/editor_templates/SMART Goal new file mode 100644 index 0000000..154c0e4 --- /dev/null +++ b/editor_templates/SMART Goal @@ -0,0 +1,39 @@ +# Goal Statement + + Update me at the end! + +# About SMART goals + +### Specific [S] + + Define the specific details of your goal. + Who is involved? + What do you want to accomplish? + Where will it take place? + Why is it important to you? + +### Measurable [M] + + Establish measurable criteria to track your progress and determine when the goal is achieved. + How much or how many? + How will you know when the goal is accomplished? + What are the milestones or indicators of progress? + +### Achievable [A] + + Assess the feasibility and attainability of your goal. + What resources, skills, or support do you need to accomplish the goal? + Is the goal realistic considering your constraints and circumstances? + Break the goal down into smaller achievable steps if necessary. + +### Relevant [R] + + Ensure that your goal aligns with your values and overall objectives. + Why is this goal relevant to your current situation or future aspirations? + How does it contribute to your personal or professional growth? + +### Time-bound [T] + + Set a timeframe or deadline for achieving your goal. + When do you want to accomplish the goal? + Are there any intermediate deadlines or milestones to consider? \ No newline at end of file diff --git a/export.go b/export.go new file mode 100644 index 0000000..de44ba9 --- /dev/null +++ b/export.go @@ -0,0 +1,292 @@ +package main + +import ( + "archive/zip" + "fmt" + "io" + "log" + "net/http" + "os" + "path/filepath" + "strings" + "time" +) + +// bundleFilesToZip bundles the files in the specified folder to a zip file +func bundleFilesToZip(folderPath string, destination string) error { + // Create the zip file + zipFile, err := os.Create(destination) + if err != nil { + log.Printf("Error creating zip file: %v", err) + return err + } + defer zipFile.Close() // Close the zip file at the end of the function execution using defer + + // Create a new zip archive + archive := zip.NewWriter(zipFile) + defer archive.Close() + + // Traverse the files and directories in the specified folder path + err = filepath.WalkDir(folderPath, func(path string, d os.DirEntry, err error) error { + if err != nil { + return err + } + + // Get file/directory info + info, err := d.Info() + if err != nil { + return err + } + + // Get the file info header for the entry in the zip file + header, err := zip.FileInfoHeader(info) + if err != nil { + return err + } + + // Set the header name to be relative to the folder path + relativePath, err := filepath.Rel(folderPath, path) + if err != nil { + return err + } + header.Name = relativePath + + if info.IsDir() { + // Create the folder entry in the zip file + header.Name += "/" + header.Method = zip.Store + _, err = archive.CreateHeader(header) + if err != nil { + return err + } + } else { + // Create a file entry in the zip file + writer, err := archive.CreateHeader(header) + if err != nil { + return err + } + + // Open the source file for reading + srcFile, err := os.Open(path) + if err != nil { + return err + } + defer srcFile.Close() + + // Copy the file contents to the zip file + _, err = io.Copy(writer, srcFile) + if err != nil { + return err + } + } + + return nil + }) + + if err != nil { + log.Printf("Error bundling files to zip: %v", err) + return err + } + + return nil +} + +// deleteFolder deletes the folder at the specified path +func deleteFolder(folderPath string) error { + err := os.RemoveAll(folderPath) + if err != nil { + log.Printf("Error deleting folder: %v", err) + return err + } + + return nil +} + +// exportFiles exports the files in a folder to a zip file and serves it as a download +func exportFiles(w http.ResponseWriter, r *http.Request) { + // Get the user's session for the folder path + userSession, err := validateSession(w, r) + if err != nil { + // Handle the error as needed + return + } + username := userSession.username + dateTime := time.Now().Format("2006-01-02_15-04-05") // Format the current date and time as "YYYY-MM-DD_HH-MM-SS" + + // Get the folder path from the URL parameter + folderPath := r.URL.Query().Get("folder") + + // If no folder path is given, export the user's folder + if folderPath == "" { + folderPath = filepath.Join(fileUploadPath, userSession.username) + } + + // Create a temporary folder to store the exported files + tempFolder := filepath.Join(".", "temp") + err2 := makeFolder(tempFolder) + if err != nil { + http.Error(w, "Error creating temporary folder", http.StatusInternalServerError) + log.Println(err2) + return + } + + // Copy the user's folder to the temporary folder + err = copyFolder(folderPath, tempFolder) + if err != nil { + http.Error(w, "Error copying folder", http.StatusInternalServerError) + log.Println(err) + return + } + + // Convert HTML files to Markdown in the temporary folder + err = filepath.WalkDir(tempFolder, func(path string, d os.DirEntry, err error) error { + if err != nil { + return err + } + + if strings.HasSuffix(path, ".md") { + content, err := os.ReadFile(path) + if err != nil { + log.Printf("Error reading file: %v", err) + return err + } + + // Convert HTML to Markdown + markdown := convertHTMLtoMarkdown(string(content)) + + // Write the Markdown content back to the file + err = os.WriteFile(path, []byte(markdown), os.ModePerm) + if err != nil { + log.Printf("Error writing Markdown file: %v", err) + return err + } + } + + return nil + }) + + if err != nil { + http.Error(w, "Error converting HTML files to Markdown", http.StatusInternalServerError) + log.Println(err) + return + } + + // Generate a unique name for the zip file + zipFileName := username + "_" + dateTime + ".zip" + zipFilePath := filepath.Join(".", zipFileName) + + // Bundle the files in the temporary folder into a zip file + err = bundleFilesToZip(tempFolder, zipFilePath) + if err != nil { + http.Error(w, "Error bundling files to zip", http.StatusInternalServerError) + log.Println(err) + return + } + + // Delete the temporary folder + err = deleteFolder(tempFolder) + if err != nil { + log.Println(err) + } + + // Open the zip file for reading + zipFile, err := os.Open(zipFilePath) + if err != nil { + http.Error(w, "Error opening zip file", http.StatusInternalServerError) + log.Println(err) + return + } + defer zipFile.Close() + + // Set the response headers + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", zipFileName)) + + // Write the zip file contents to the response writer + _, err = io.Copy(w, zipFile) + if err != nil { + log.Println(err) + } + + // Delete the generated zip file + err = os.Remove(zipFilePath) + if err != nil { + // Log the error, but don't interrupt the response handling + log.Printf("Error deleting zip file: %v", err) + } +} + +// copyFolder copies the files and directories from the source path to the destination path +func copyFolder(source string, destination string) error { + // Traverse the files and directories in the specified folder path + err := filepath.WalkDir(source, func(path string, d os.DirEntry, err error) error { + if err != nil { + return err + } + + // Skip the source folder itself + if path == source { + return nil + } + + // Get the relative path within the source folder + relativePath, err := filepath.Rel(source, path) + if err != nil { + log.Printf("Error getting relative path: %v", err) + return err + } + + // Create the corresponding destination path + destPath := filepath.Join(destination, relativePath) + + if d.IsDir() { + // Create the directory in the destination + err := os.MkdirAll(destPath, os.ModePerm) + if err != nil { + log.Printf("Error creating destination folder: %v", err) + return err + } + } else { + // Copy the file from source to destination + err := copyFile(path, destPath) + if err != nil { + log.Printf("Error copying file: %v", err) + return err + } + } + + return nil + }) + + if err != nil { + log.Printf("Error copying folder: %v", err) + return err + } + + return nil +} + +// copyFile copies a file from the source path to the destination path +func copyFile(source string, destination string) error { + srcFile, err := os.Open(source) + if err != nil { + log.Printf("Error opening source file: %v", err) + return err + } + defer srcFile.Close() + + destFile, err := os.Create(destination) + if err != nil { + log.Printf("Error creating destination file: %v", err) + return err + } + defer destFile.Close() + + _, err = io.Copy(destFile, srcFile) + if err != nil { + log.Printf("Error copying file: %v", err) + return err + } + + return nil +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..2f15fbc --- /dev/null +++ b/go.mod @@ -0,0 +1,24 @@ +module notatio + +go 1.21 + +require ( + github.com/JohannesKaufmann/html-to-markdown v1.4.1 + github.com/google/uuid v1.3.1 + github.com/lib/pq v1.10.9 + golang.org/x/crypto v0.14.0 +) + +require ( + github.com/aymerick/douceur v0.2.0 // indirect + github.com/gorilla/css v1.0.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect +) + +require ( + github.com/PuerkitoBio/goquery v1.8.1 // indirect + github.com/andybalholm/cascadia v1.3.2 // indirect + github.com/gomarkdown/markdown v0.0.0-20230922112808-5421fefb8386 + github.com/microcosm-cc/bluemonday v1.0.26 + golang.org/x/net v0.17.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..fb437d3 --- /dev/null +++ b/go.sum @@ -0,0 +1,95 @@ +github.com/JohannesKaufmann/html-to-markdown v1.4.1 h1:CMAl6hz2MRfs03ZGAwYqQTC43Egi3vbc9SVo6nEKUE0= +github.com/JohannesKaufmann/html-to-markdown v1.4.1/go.mod h1:1zaDDQVWTRwNksmTUTkcVXqgNF28YHiEUIm8FL9Z+II= +github.com/PuerkitoBio/goquery v1.8.1 h1:uQxhNlArOIdbrH1tr0UXwdVFgDcZDrZVdcpygAcwmWM= +github.com/PuerkitoBio/goquery v1.8.1/go.mod h1:Q8ICL1kNUJ2sXGoAhPGUdYDJvgQgHzJsnnd3H7Ho5jQ= +github.com/andybalholm/cascadia v1.3.1 h1:nhxRkql1kdYCc8Snf7D5/D3spOX+dBgjA6u8x004T2c= +github.com/andybalholm/cascadia v1.3.1/go.mod h1:R4bJ1UQfqADjvDa4P6HZHLh/3OxWWEqc0Sk8XGwHqvA= +github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss= +github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU= +github.com/aymerick/douceur v0.2.0 h1:Mv+mAeH1Q+n9Fr+oyamOlAkUNPWPlA8PPGR0QAaYuPk= +github.com/aymerick/douceur v0.2.0/go.mod h1:wlT5vV2O3h55X9m7iVYN0TBM0NH/MmbLnd30/FjWUq4= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gomarkdown/markdown v0.0.0-20230922112808-5421fefb8386 h1:EcQR3gusLHN46TAD+G+EbaaqJArt5vHhNpXAa12PQf4= +github.com/gomarkdown/markdown v0.0.0-20230922112808-5421fefb8386/go.mod h1:JDGcbDT52eL4fju3sZ4TeHGsQwhG9nbDV21aMyhwPoA= +github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= +github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gorilla/css v1.0.0 h1:BQqNyPTi50JCFMTw/b67hByjMVXZRwGha6wxVGkeihY= +github.com/gorilla/css v1.0.0/go.mod h1:Dn721qIggHpt4+EFCcTLTU/vk5ySda2ReITrtgBl60c= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/microcosm-cc/bluemonday v1.0.26 h1:xbqSvqzQMeEHCqMi64VAs4d8uy6Mequs3rQ0k/Khz58= +github.com/microcosm-cc/bluemonday v1.0.26/go.mod h1:JyzOCs9gkyQyjs+6h10UEVSe02CGwkhd72Xdqh78TWs= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/sebdah/goldie/v2 v2.5.3/go.mod h1:oZ9fp0+se1eapSRjfYbsV/0Hqhbuu3bJVvKI/NNtssI= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/sergi/go-diff v1.2.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yuin/goldmark v1.5.5/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/yuin/goldmark v1.5.6 h1:COmQAWTCcGetChm3Ig7G/t8AFAN00t+o8Mt4cf7JpwA= +github.com/yuin/goldmark v1.5.6/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= +golang.org/x/crypto v0.14.0 h1:wBqGXzWJW6m1XrIKlAH0Hs1JJ7+9KBwnIO8v66Q9cHc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.9.0/go.mod h1:d48xBJpPfHeWQsugry2m+kC02ZBRGRgulfHnEXEuWns= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.14.0 h1:BONx9s002vGdD9umnlX1Po8vOZmrgH34qlHcD1MfK14= +golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= +golang.org/x/net v0.17.0 h1:pVaXccu2ozPjCXewfr1S7xza/zcXTity9cCdXQYSjIM= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.7.0/go.mod h1:P32HKFT3hSsZrRxla30E9HqToFYAQPCMs/zFMBUFqPY= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= diff --git a/list.go b/list.go new file mode 100644 index 0000000..49da836 --- /dev/null +++ b/list.go @@ -0,0 +1,326 @@ +package main + +import ( + "database/sql" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "os" + "path/filepath" + "strings" + "time" +) + +func ListFiles(w http.ResponseWriter, r *http.Request) { + userSession, err := validateSession(w, r) + if err != nil { + // Handle the error as needed + handleInternalServerError(w, err) + return + } + + userFolder := filepath.Join(fileUploadPath, userSession.username) + + successParam := r.URL.Query().Get("success") + successMessage := "" + if successParam == "1" { + successMessage = "Upload was successful!" + } + if successParam == "2" { + successMessage = "File creation was successful!" + } + + // Open the user's directory + userDir, err := os.Open(userFolder) + if err != nil { + if os.IsNotExist(err) { + // Directory does not exist, create it + log.Println(userSession.username + "'s directory does not exist. Creating it!") + createUserFolder(userSession.username) + // Open the newly created user directory + userDir, err = os.Open(userFolder) + if err != nil { + log.Printf("Error opening user directory: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + } else { + // Other error occurred while opening the directory + log.Printf("Error opening user directory: %v", err) + // Handle the error as needed + handleInternalServerError(w, err) + return + } + } + defer userDir.Close() + + // Read the names of files in the directory + fileNames, err := userDir.Readdirnames(-1) + if err != nil { + log.Printf("Error reading file names in directory: %v", err) + // Handle the error as needed + handleInternalServerError(w, err) + return + } + + type File struct { + Filename string + CreationTime int64 + LastEdited int64 + } + + var files []File + for _, fileName := range fileNames { + if strings.HasSuffix(fileName, ".html") || strings.HasSuffix(fileName, ".md") { + file := File{ + Filename: fileName, + } + + userUUID, err := getUserUUID(userSession.username) + if err != nil { + log.Printf("Error getting user UUID: %v", err) + // Handle the error as needed + handleInternalServerError(w, err) + return + } + + err = db.QueryRow("SELECT EXTRACT(epoch FROM creation_time)::bigint, EXTRACT(epoch FROM last_edited)::bigint FROM files WHERE user_id = $1 AND filename = $2", + userUUID, fileName).Scan(&file.CreationTime, &file.LastEdited) + + if err == sql.ErrNoRows { + // No rows found, handle the case as needed + log.Printf("No rows found for file: %s", fileName) + currentTime := time.Now().Unix() + + err = insertFileIntoDatabase(userSession.username, fileName, currentTime, currentTime, currentTime) + if err != nil { + log.Printf("Error inserting file into the database: %v", err) + // Handle the error as needed + handleInternalServerError(w, err) + return + } + http.Redirect(w, r, "/home", http.StatusSeeOther) + // Redirect or do something else + return + } else if err != nil { + log.Printf("Error retrieving file timestamps from the database: %v", err) + log.Printf("Asking %s to create a new file", userSession.username) + http.Redirect(w, r, "/welcome", http.StatusSeeOther) + return + } + + files = append(files, file) + } + } + + name, err := getName(userSession.username) + if err != nil { + log.Printf("Error retrieving preferred name from the database: %v", err) + } + + data := struct { + Username string + Files []File + SuccessMessage string + }{ + Username: name, + Files: files, + SuccessMessage: successMessage, + } + + renderTemplate(w, "list.html", data) +} + +func UploadFile(w http.ResponseWriter, r *http.Request) { + userSession, err := validateSession(w, r) + if err != nil { + // Handle the error as needed + return + } + + if r.Method == http.MethodPost { + reader, err := r.MultipartReader() + if err != nil { + log.Printf("Error creating multipart reader: %v", err) + http.Error(w, "Bad Request", http.StatusBadRequest) + return + } + + for { + part, err := reader.NextPart() + if err == io.EOF { + break + } + if err != nil { + log.Printf("Error reading part: %v", err) + http.Error(w, "Bad Request", http.StatusBadRequest) + return + } + + // Check the file extension to allow only .md or .html files + fileExt := filepath.Ext(part.FileName()) + if fileExt != ".md" && fileExt != ".html" { + log.Printf("Invalid file format: %s", part.FileName()) + http.Error(w, "Invalid File Format. Only .md and .html files are allowed.", http.StatusBadRequest) + return + } + + userFolder := filepath.Join(fileUploadPath, userSession.username) + + // Generate a unique filename by appending sequential numbers if needed + filename := part.FileName() + count := 1 + for { + filePath := filepath.Join(userFolder, filename) + if _, err := os.Stat(filePath); os.IsNotExist(err) { + break + } + filename = fmt.Sprintf("%s_%d%s", strings.TrimSuffix(part.FileName(), filepath.Ext(part.FileName())), count, filepath.Ext(part.FileName())) + count++ + } + + // Save the file to disk in the user's folder + filePath := filepath.Join(userFolder, filename) + destFile, err := os.Create(filePath) + if err != nil { + log.Printf("Error creating destination file: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + defer destFile.Close() + + _, err = io.Copy(destFile, part) + if err != nil { + log.Printf("Error saving file to disk: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + // Insert the file record into the database with creation time + currentTime := time.Now().Unix() + err = insertFileIntoDatabase(userSession.username, filename, currentTime, currentTime, currentTime) + if err != nil { + log.Printf("Error inserting file into database: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + http.Redirect(w, r, "/home?success=1", http.StatusSeeOther) + + } + } +} + +func createNewFile(w http.ResponseWriter, r *http.Request) { + userSession, err := validateSession(w, r) + if err != nil { + // Handle the error as needed + return + } + + // Parse the form data to obtain the filename + if err := r.ParseForm(); err != nil { + http.Error(w, "Bad Request", http.StatusBadRequest) + return + } + + filename := r.FormValue("newFileName") + // Ensure the file has the ".md" extension + if !strings.HasSuffix(filename, ".md") { + filename += ".md" + } + + // Construct the file path + userFolder := filepath.Join(fileUploadPath, userSession.username) + filePath := filepath.Join(userFolder, filename) + + // Check if the file already exists + if _, err := os.Stat(filePath); !os.IsNotExist(err) { + // File with the same name already exists + http.Error(w, "File already exists", http.StatusConflict) + return + } + + // Create and open the file for writing + file, err := os.Create(filePath) + if err != nil { + log.Printf("Error creating file: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + defer file.Close() + + // Insert the file record into the database with creation time + currentTime := time.Now().Unix() + + err = insertFileIntoDatabase(userSession.username, filename, currentTime, currentTime, currentTime) + if err != nil { + log.Printf("Error inserting file into the database: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + // Redirect to editing the newly created file + http.Redirect(w, r, "/edit?filename="+filename, http.StatusSeeOther) +} + +func DeleteFiles(w http.ResponseWriter, r *http.Request) { + userSession, err := validateSession(w, r) + if err != nil { + // Handle the error as needed + return + } + + if r.Method == http.MethodPost { + // Parse the JSON request body to get the list of files to delete + var request struct { + Files []string `json:"files"` + } + // Print the list of files to delete + for _, filename := range request.Files { + fmt.Println("File to delete:", filename) + } + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + http.Error(w, "Bad Request", http.StatusBadRequest) + return + } + + // Delete each selected file from the database and the filesystem + for _, filename := range request.Files { + userFolder := filepath.Join(fileUploadPath, userSession.username) + filePath := filepath.Join(userFolder, filename) + + // Delete the file from the database + if err := deleteFileFromDatabase(userSession.username, filename); err != nil { + // Handle the error as needed + log.Printf("Error deleting file record: %v", err) + } + + // Delete the file from the filesystem + if err := os.Remove(filePath); err != nil { + // Handle the error as needed + log.Printf("Error deleting file from filesystem: %v", err) + } + } + + // Send a success response + w.WriteHeader(http.StatusOK) + } +} + +func makeFolder(folderPath string) error { + err := os.MkdirAll(folderPath, os.ModePerm) + if err != nil { + return err + } + return nil +} + +func createUserFolder(username string) { + userFolder := filepath.Join(fileUploadPath, username) + err := makeFolder(userFolder) + if err != nil { + log.Printf("Error creating user folder: %v", err) + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..8eb995f --- /dev/null +++ b/main.go @@ -0,0 +1,359 @@ +package main + +import ( + "database/sql" + "encoding/json" + "fmt" + "log" + "net/http" + "os" + "strings" + "text/template" + "time" + + "github.com/google/uuid" + _ "github.com/lib/pq" + "golang.org/x/crypto/bcrypt" +) + +// Varibles, constants and basic structures + +const ( + hashCost = 16 + sessionLength = 12000 * time.Second +) + +var ( + db *sql.DB + sessions = make(map[string]session) + fileUploadPath = "./uploads" + templateFilePath = "./editor_templates" + templates = template.Must(template.ParseGlob("templates/*.html")) +) + +type session struct { + username string + expiry time.Time + sessionUUID string +} + +type Credentials struct { + Password string `json:"password"` + Username string `json:"username"` +} + +type File struct { + ID int + UserID uuid.UUID + Filename string + CreationTime int64 + LastEdited int64 + LastOpened int64 +} + +func main() { + // Retrieve Environment variables + dbName := "notatio" + dbHost := getEnvVariable("DB_HOST") + dbPort := getEnvVariable("PGPORT") + dbUser := getEnvVariable("DB_USER") + dbPassword := getEnvVariable("POSTGRES_PASSWORD") + dbSSLMode := getEnvVariable("DB_SSL_MODE") + + db = connectToDatabase(dbHost, dbPort, dbUser, dbPassword, dbUser, dbSSLMode) + defer db.Close() + + missingParam := "" + switch { + case dbHost == "": + missingParam = "DB_HOST" + case dbPort == "": + missingParam = "PGPORT" + case dbUser == "": + missingParam = "DB_USER" + case dbPassword == "": + missingParam = "POSTGRES_PASSWORD" + } + + if missingParam != "" { + log.Printf("Error: Required PostgreSQL connection environment variable '%s' is not provided.\n", missingParam) + log.Println("Exiting...") + os.Exit(10) + } + + exists := checkDatabaseExists(db, dbName) + + if !exists { + createDatabase(db, dbName) + } + + db = connectToNotatioDatabase(dbHost, dbPort, dbUser, dbPassword, dbName, dbSSLMode) + defer db.Close() + + adminUsername := getEnvVariable("ADMIN_USER") + adminPassword := getEnvVariable("ADMIN_PASS") + adminName := getEnvVariable("ADMIN_NAME") + adminEmail := getEnvVariable("ADMIN_EMAIL") + + createUserTable() + createFilesTable() + createTableDB() + + createUser(adminUsername, adminPassword, adminName, adminEmail) + log.Println("Done with database checks, starting webserver!") + + // Start webserver + initHTTPServer() + +} + +// Web server initializer +func initHTTPServer() { + http.HandleFunc("/", AboutPage) + http.HandleFunc("/signup", Signup) + http.HandleFunc("/login", Login) + http.HandleFunc("/home", ListFiles) + http.HandleFunc("/refresh", Refresh) + http.HandleFunc("/logout", Logout) + http.HandleFunc("/upload", UploadFile) + http.HandleFunc("/edit", EditFile) + http.HandleFunc("/save", SaveFile) + http.HandleFunc("/create", createNewFile) + http.HandleFunc("/welcome", newUser) + http.HandleFunc("/delete", DeleteFiles) + http.HandleFunc("/export", exportFiles) + http.HandleFunc("/checkusername", handleUsernameCheck) + http.HandleFunc("/kanban", kanban) + http.HandleFunc("/update-task-status", updateTaskStatus) + + http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) + + // Start the server on port 9991 + fmt.Println("Starting HTTP server on port 9991...") + log.Fatal(http.ListenAndServe(":9991", nil)) +} + +func renderTemplate(w http.ResponseWriter, templateName string, data interface{}) { + err := templates.ExecuteTemplate(w, templateName, data) + if err != nil { + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + log.Printf("Error rendering template %s: %v", templateName, err) + } +} + +func handleUsernameCheck(w http.ResponseWriter, r *http.Request) { + // Get the username from the query parameter + username := r.URL.Query().Get("username") + // Check if the username is taken (example function) + isTaken, err := isUsernameTaken(username) + if err != nil { + log.Fatal(err) + } + + // Create a response map to store the availability status + response := map[string]bool{ + "available": isTaken, + } + + // Convert the response to JSON format + jsonResponse, err := json.Marshal(response) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Set the content type as JSON + w.Header().Set("Content-Type", "application/json") + + // Write the JSON response to the response writer + w.Write(jsonResponse) +} + +func handleInternalServerError(w http.ResponseWriter, err error) { + log.Printf("Error: %v", err) +} + +func AboutPage(w http.ResponseWriter, r *http.Request) { + renderTemplate(w, "index.html", nil) +} + +func newUser(w http.ResponseWriter, r *http.Request) { + renderTemplate(w, "newuser.html", nil) +} + +func Refresh(w http.ResponseWriter, r *http.Request) { + userSession, err := validateSession(w, r) + if err != nil { + // Handle the error as needed + return + } + + // Create a new session token for the current user + newSessionToken := uuid.NewString() + expiresAt := time.Now().Add(sessionLength) + + // Store the token in the session map, along with the user whom it represents + sessions[newSessionToken] = session{ + username: userSession.username, + expiry: expiresAt, + } + + // Delete the older session token + delete(sessions, userSession.sessionUUID) + + // Set the new token as the user's `session_token` cookie + http.SetCookie(w, &http.Cookie{ + Name: "session_token", + Value: newSessionToken, + Expires: expiresAt, + }) + + log.Printf("Session refreshed for user: %s", userSession.username) + + // Redirect to the home page + http.Redirect(w, r, "/home", http.StatusSeeOther) +} + +func (s session) isSessionExpired() bool { + return s.expiry.Before(time.Now()) +} + +func validateSession(w http.ResponseWriter, r *http.Request) (session, error) { + sessionCookie, err := r.Cookie("session_token") + if err != nil { + log.Printf("Error getting session cookie: %v", err) + http.Redirect(w, r, "/?login", http.StatusSeeOther) // Redirect to the login page + return session{}, err + } + + sessionToken := sessionCookie.Value + userSession, exists := sessions[sessionToken] + if !exists { + log.Printf("Session not found for token: %s", sessionToken) + http.Redirect(w, r, "/?login", http.StatusSeeOther) // Redirect to the login page + return session{}, fmt.Errorf("session not found") + } + + if userSession.isSessionExpired() { + delete(sessions, sessionToken) + log.Printf("Session expired for user: %s", userSession.username) + http.Redirect(w, r, "/?login", http.StatusSeeOther) // Redirect to the login page + return session{}, fmt.Errorf("session expired") + } + + return userSession, nil +} + +func createUserTable() { + // Create User Table + createUserTable := ` + CREATE TABLE IF NOT EXISTS users ( + id SERIAL PRIMARY KEY, + username VARCHAR(255) UNIQUE NOT NULL, + password VARCHAR(255) NOT NULL, + accounttype VARCHAR(255) NOT NULL, + uuid VARCHAR(255) NOT NULL, + name VARCHAR(255) NOT NULL, + email VARCHAR(255) NOT NULL + );` + + _, err := db.Exec(createUserTable) + if err != nil { + log.Fatal(err) + } + +} + +func createFilesTable() { + // Create File Table + createFileTable := ` + CREATE TABLE IF NOT EXISTS files ( + id SERIAL PRIMARY KEY, + user_id UUID NOT NULL, + filename VARCHAR(255) NOT NULL, + creation_time TIMESTAMP NOT NULL, + last_edited TIMESTAMP NOT NULL, + last_opened TIMESTAMP NOT NULL + );` + + _, err := db.Exec(createFileTable) + if err != nil { + log.Fatal(err) + } +} + +func getEnvVariable(name string) string { + value := os.Getenv(name) + if value == "" { + log.Printf("Error: Required environment variable '%s' is not provided.\n", name) + log.Println("Exiting...") + os.Exit(10) + } + return value +} + +func connectToDatabase(dbHost, dbPort, dbUser, dbPassword, dbName, dbSSLMode string) *sql.DB { + dbConnectionString := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s", dbHost, dbPort, dbUser, dbPassword, dbName, dbSSLMode) + db, err := sql.Open("postgres", dbConnectionString) + if err != nil { + // Handle the error appropriately + panic(err) + } + return db +} + +func checkDatabaseExists(db *sql.DB, dbName string) bool { + var exists bool + row := db.QueryRow("SELECT EXISTS (SELECT 1 FROM pg_database WHERE datname = $1)", dbName) + if err := row.Scan(&exists); err != nil { + log.Fatal(err) + } + return exists +} + +func createDatabase(db *sql.DB, dbName string) { + log.Println("Notatio database does not exist. Creating Database...") + _, err := db.Exec("CREATE DATABASE notatio") + if err != nil { + log.Fatal(err) + } +} + +func connectToNotatioDatabase(dbHost, dbPort, dbUser, dbPassword, dbName, dbSSLMode string) *sql.DB { + dbConnectionString := fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=%s", dbHost, dbPort, dbUser, dbPassword, dbName, dbSSLMode) + db, err := sql.Open("postgres", dbConnectionString) + if err != nil { + // Handle the error appropriately + panic(err) + } + return db +} + +func createUser(adminUsername string, adminPassword string, adminName string, adminEmail string) { + adminUsername = strings.ToLower(adminUsername) + if adminUsername != "" && adminPassword != "" && adminName != "" && adminEmail != "" { + // Check if the admin user already exists in the database + _, adminExists := getUserFromDatabase(adminUsername) + if !adminExists { + // Admin user doesn't exist, create it + hashedPassword, err := bcrypt.GenerateFromPassword([]byte(adminPassword), hashCost) + if err != nil { + log.Printf("Error hashing admin password: %v", err) + // Handle the error appropriately + } else { + // Generate a UUID for the admin user + adminUUID := uuid.New() + createUserFolder(adminUsername) + // Insert the admin user into the database with the hashed password and UUID + if err := insertUserIntoDatabase(adminUsername, string(hashedPassword), "admin", adminUUID.String(), adminName, adminEmail); err != nil { + log.Printf("Error inserting admin user into database: %v", err) + // Handle the error appropriately + } else { + log.Printf("Admin user created and added to the database: %s", adminUsername) + } + } + } else { + log.Printf("Admin user already exists in the database: %s", adminUsername) + } + } +} diff --git a/static/build/editor.js b/static/build/editor.js new file mode 100644 index 0000000..a887a5e --- /dev/null +++ b/static/build/editor.js @@ -0,0 +1,393 @@ +document.addEventListener('DOMContentLoaded', function () { + formatAllTables(); + document.body.addEventListener("click", focusOnEditor); + +}); + +function formatAllTables() { + var tables = document.getElementsByTagName('table'); + for (var i = 0; i < tables.length; i++) + formatTable(tables[i]); +} + +function formatText(tag, data) { + if (tag === 'heading') { + var headingTag = document.createElement(data); + var selection = window.getSelection(); + var range = selection.getRangeAt(0); + headingTag.appendChild(range.extractContents()); + range.insertNode(headingTag); + } else { + document.execCommand(tag, false, data); + } +} + +function formatTable(table) { + // Add Bootstrap classes to the table + table.classList.add('table', 'table-striped', 'table-hover'); + + // Add Bootstrap classes to the table header cells + var headerCells = table.getElementsByTagName('th'); + for (var i = 0; i < headerCells.length; i++) { + headerCells[i].classList.add(''); + } + + // Add Bootstrap classes to the table rows + var rows = table.getElementsByTagName('tr'); + for (var i = 0; i < rows.length; i++) { + rows[i].classList.add(''); + + // Add event listener to the last cell of each row + var cells = rows[i].getElementsByTagName('td'); + var lastCell = cells[cells.length - 1]; + lastCell.addEventListener('keydown', function (event) { + if (event.key === 'Enter') { + // Check if it's the last cell in the last row + var lastRow = rows[rows.length - 1]; + if (this.parentNode === lastRow && this === lastRow.lastElementChild) { + event.preventDefault(); + var newParagraph = document.createElement('p'); + newParagraph.textContent = '\u00A0'; // Insert a non-breaking space to maintain table structure + table.parentNode.insertBefore(newParagraph, table.nextSibling); + document.getElementById('editor').focus(); + } + } + }); + } + + // Add Bootstrap classes to the table data cells + var cells = table.getElementsByTagName('td'); + for (var i = 0; i < cells.length; i++) { + cells[i].classList.add('align-middle'); + } +} + +function saveForm() { + console.log("Saving file"); + + var editedContent = document.getElementById("editor").innerHTML; + var editedFilename = document.getElementById("filename").innerText; + + // Set the editor content as the value of the editor-form-content textarea + document.getElementById("editor-form-content").value = editedContent; + document.getElementById("filename-form-content").value = editedFilename; + + // Submit the form + document.getElementById("save-form").submit(); +} + +function confirmOverwrite() { + if (confirm("Are you sure you want to overwrite the file contents?")) { + document.getElementById("template-modal").style.display = "block"; + // Close the modal when the close button or outside of the modal is clicked + window.addEventListener("click", function (e) { + if (e.target == document.getElementById("template-modal")) { + document.getElementById("template-modal").style.display = "none"; + } + }); + } +} + +function confirmDeletion() { + if (confirm("Are you sure you want to delete {{.Filename}}?")) { + const filename = "{{.Filename}}"; + deleteFile(filename); + } +} + +// Function to focus on the editor when body is clicked +function focusOnEditor() { + // Check if the clicked element is inside the body div + if (event.target === document.body) { // Set the cursor position in the editor + setCursorPosition(document.getElementById("editor")); + } +} +// Add event listener to the body element + +function redirectToTemplate(templateURL) { + window.location.href = templateURL; +} + +function editFileName() { + var fileNameElement = document.getElementById("filename"); + var fileName = fileNameElement.innerText.trim(); + var extension = fileName.substring(fileName.lastIndexOf(".")); + + // Remove the file extension + fileName = fileName.replace(extension, ""); + + // Allow editing the filename + fileNameElement.contentEditable = "true"; + fileNameElement.innerText = fileName; + fileNameElement.focus(); + + // Disable the enter key to prevent adding new lines + fileNameElement.addEventListener("keydown", function (event) { + if (event.keyCode == 13) { + event.preventDefault(); + fileNameElement.blur(); + } + }); + + // Update the filename when the user finishes editing + fileNameElement.onblur = function () { + fileName = fileNameElement.innerText.trim(); + + // Add the file extension back + fileName += extension; + + fileNameElement.innerText = fileName; + fileNameElement.contentEditable = "false"; + fileNameElement.removeEventListener("keydown"); + }; +} + +// Show the table size modal +function addTable() { + document.getElementById("tableModal").style.display = "block"; + return +} +function createTable() { + var tableRowsInput = document.getElementById('tableRows'); + var tableColumnsInput = document.getElementById('tableColumns'); + + var tableRows = parseInt(tableRowsInput.value); + var tableColumns = parseInt(tableColumnsInput.value); + + if (!isNaN(tableRows) && !isNaN(tableColumns)) { + // Create a new table-responsive div + var tableResponsiveDiv = document.createElement('div'); + tableResponsiveDiv.classList.add('table-responsive'); + + // Create a new table element + var table = document.createElement('table'); + table.classList.add('table', 'table-striped', 'table-bordered'); + + // Create the table header + var thead = document.createElement('thead'); + var headerRow = document.createElement('tr'); + for (var j = 0; j < tableColumns; j++) { + var headerCell = document.createElement('th'); + var headerText = document.createTextNode('Header ' + (j + 1)); + headerCell.appendChild(headerText); + headerRow.appendChild(headerCell); + } + thead.appendChild(headerRow); + + // Create the table body + var tbody = document.createElement('tbody'); + for (var i = 0; i < tableRows; i++) { + var row = document.createElement('tr'); + for (var j = 0; j < tableColumns; j++) { + var cell = document.createElement('td'); + var cellText = document.createTextNode('Cell ' + (i + 1) + '-' + (j + 1)); + cell.appendChild(cellText); + row.appendChild(cell); + } + tbody.appendChild(row); + } + + // Append the thead and tbody to the table + table.appendChild(thead); + table.appendChild(tbody); + + // Append the table to the table-responsive div + tableResponsiveDiv.appendChild(table); + + // Insert the table-responsive div into the editor + var editor = document.getElementById('editor'); + editor.appendChild(tableResponsiveDiv); + + // Create a new
element + var paragraphDiv = document.createElement('div'); + + // Create a new

element + var paragraph = document.createElement('p'); + + // Set the text content of the paragraph + var paragraphText = document.createTextNode(''); + paragraph.appendChild(paragraphText); + + // Append the paragraph to the paragraph div + paragraphDiv.appendChild(paragraph); + + // Insert the paragraph div after the table-responsive div + editor.appendChild(paragraphDiv); + + // Reset the modal inputs + tableRowsInput.value = '3'; + tableColumnsInput.value = '3'; + + // Close the modal + document.getElementById('tableModal').style.display = 'none'; + } +} + + + +function addVideo() { + var url = prompt("Enter the video URL:"); + + if (url !== null) { + var videoElement = document.createElement('video'); + videoElement.controls = true; + videoElement.src = url; + document.getElementById('editor').appendChild(videoElement); + + var paragraphElement = document.createElement('p'); + paragraphElement.textContent = 'Type your text here'; + + document.getElementById('editor').appendChild(paragraphElement); + } +} + +function deleteFile(filename) { + // Send a POST request to the server to delete the specified file + fetch("/delete", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ files: [filename] }), + }) + .then(response => { + if (response.ok) { + window.location.replace("/home"); + } else { + // Handle the error, e.g., display an error message + console.error("Error deleting file"); + } + }) + .catch(error => { + console.error("Error deleting file:", error); + }); +} + +function insertLink() { + var url = prompt('Enter the URL:'); + + // Check if the URL is null or empty + if (url === null || url === '') { + console.log('URL is empty. Aborting link creation.'); + return; + } + + var label = ''; + + // Get the user's selection + var selection = window.getSelection(); + + // Check if the user has made a selection + if (selection.rangeCount > 0) { + var range = selection.getRangeAt(0); + + // Get the selected text + var selectedText = range.toString().trim(); + + // Prompt for the label only if there is no selection + if (selectedText.length === 0) { + label = prompt('Please enter the Link Text:'); + } else { + label = selectedText; + } + } + + // Check if the URL or label is empty + if (url === '' || label === '') { + console.log('URL or label is empty. Aborting link creation.'); + return; + } + + // Create the link HTML + var val = '' + label + ''; + + // Insert the link HTML at the current selection or caret position + document.execCommand('insertHTML', false, val); +} + +function undo() { + document.execCommand('undo', false, null); +} + +function redo() { + document.execCommand('redo', false, null); +} + +function selectAll() { + document.execCommand('selectAll', false, null); +} + +function insertImage() { + var url = prompt('Enter the image URL:'); + if (url !== null) { + document.execCommand('insertImage', false, url); + } +} + +function setCursorPosition(element) { + var range = document.createRange(); + range.selectNodeContents(element); + range.collapse(false); + var selection = window.getSelection(); + selection.removeAllRanges(); + selection.addRange(range); +} + +document.addEventListener('keydown', function (event) { + if ((event.ctrlKey || event.metaKey)) { + switch (event.key.toLowerCase()) { + case 'b': + event.preventDefault(); + formatText('bold'); + break; + case 'i': + event.preventDefault(); + formatText('italic'); + break; + case 'u': + event.preventDefault(); + formatText('underline'); + break; + case 'l': + event.preventDefault(); + insertLink(); + break; + case 'z': + event.preventDefault(); + undo(); + break; + case 'y': + event.preventDefault(); + redo(); + break; + case 'd': + event.preventDefault(); + confirmDeletion(); + break; + case 'p': + event.preventDefault(); + insertImage(); + break; + case 't': + event.preventDefault(); + confirmOverwrite(); + break; + case 's': + event.preventDefault(); + saveForm(); + break; + case 'f': + event.preventDefault(); + formatText('removeFormat'); + break; + case 'T': + event.preventDefault(); + addTable(); + break; + case 'm': + event.preventDefault(); + addVideo(); + break; + } + } +}); diff --git a/static/favicon.ico b/static/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..424bbf2632297ef51e728a94c1ecd1df1f4b9275 GIT binary patch literal 1406 zcmeHHI}U&EIoi6h0@Z}!ickc1BnMP;gQ*8 zCbKWgOBg`#ab0k2<6r?Z084@re8T8SiFB*K->*kVio4Aeio2Z{Bvy+#1pAo|l4qrq zcwE-F?R^L%&}?f(T|l)g$X0T&S(*tn6Zn$}Xss(ZC9f)43(?8)!#GJ< + + + + Edit File + + + + + + + + + + + + + + +

+
+
+
+

Editing File:

+

{{.Filename}}

+
+
+
+ +
+
+
+
+ + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + + +
+
+
+
+
+
+ +
+
+
+
+
+ + +
+ {{.FileContent}}
+
+
+
+ + + + + + + \ No newline at end of file diff --git a/templates/index.html b/templates/index.html new file mode 100644 index 0000000..daa1bcf --- /dev/null +++ b/templates/index.html @@ -0,0 +1,357 @@ + + + + + Notatio + + + + + + + + + + + + +
+
+

+ Welcome to Notatio, an open source, web-based text editor written in the powerful Go programming language. +

+

+ Notatio provides a user-friendly interface combined with robust features, making it the perfect choice for + developers, writers, and anyone who interacts with text on a daily basis. +

+

Notatio is alpha software! Do no use it as your daily driver!

+ +

Text Editor Comparison

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeaturesNotion.soObsidianMDNotatio
Web-Based
Open Source
Does not push paid plans
Uses Open File Formats
Sleek and Intuitive Interface
Collaborative EditingPlanned
Syntax HighlightingPlanned
+
+ + + +
+ + + + + + + + + \ No newline at end of file diff --git a/templates/kanban.html b/templates/kanban.html new file mode 100644 index 0000000..6183cfe --- /dev/null +++ b/templates/kanban.html @@ -0,0 +1,146 @@ + + + + + + + + + Kanban Board + + + +
+

Kanban Board

+
+
+ + +
+
+ + +
+
+ + +
+ + +
+

Tasks:

+
+
+

To Do

+
+ {{ range .Tasks }} + {{ if eq .Status "todo" }} +
+
+
{{ .Title }}
+

{{ .Description }}

+

Status: {{ .Status }}

+
+
+ {{ end }} + {{ end }} +
+
+
+

In Progress

+
+ {{ range .Tasks }} + {{ if eq .Status "in_progress" }} +
+
+
{{ .Title }}
+

{{ .Description }}

+

Status: {{ .Status }}

+
+
+ {{ end }} + {{ end }} +
+
+
+

Done

+
+ {{ range .Tasks }} + {{ if eq .Status "done" }} +
+
+
{{ .Title }}
+

{{ .Description }}

+

Status: {{ .Status }}

+
+
+ {{ end }} + {{ end }} +
+
+
+
+ + + + + diff --git a/templates/list.html b/templates/list.html new file mode 100644 index 0000000..3b625d5 --- /dev/null +++ b/templates/list.html @@ -0,0 +1,212 @@ + + + + + List Files + + + + + + +
+

Welcome, {{.Username}}!

+ + + + + + + + + +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+ + + + + + + + + + + + + {{range .Files}} + + + + + + {{end}} + +
File NameCreation TimeLast Edited
+ {{.Filename}} + + + + +
+
+ + + + + + + + \ No newline at end of file diff --git a/templates/newuser.html b/templates/newuser.html new file mode 100644 index 0000000..8b9d67d --- /dev/null +++ b/templates/newuser.html @@ -0,0 +1,24 @@ + + + + + + + + +

Welcome to Notatio!

+

Before you begin creating your first file we want to give you a few tips!

+ Although E2EE is planned, It is not implemented yet so DO NOT store sensitive information. + (The admins can read it) + Use unique and meaningful file names, dates often dont convey what the file holds, nor does temp or document 1. + + Back up your files often if you are using a public instance! You never know If the admin will take the service + down. +

Enter the name of your first file:

+
+

+ +
+ + + \ No newline at end of file diff --git a/user.go b/user.go new file mode 100644 index 0000000..e483974 --- /dev/null +++ b/user.go @@ -0,0 +1,200 @@ +package main + +import ( + "database/sql" + "encoding/json" + "fmt" + "log" + "net/http" + "strings" + "time" + + "github.com/google/uuid" + "golang.org/x/crypto/bcrypt" +) + +func Login(w http.ResponseWriter, r *http.Request) { + var creds Credentials + err := r.ParseMultipartForm(0) + if err != nil { + log.Printf("Error parsing form: %v", err) + http.Error(w, "Bad Request", http.StatusBadRequest) + return + } + + log.Println(r.FormValue("username")) + creds.Username = strings.ToLower(r.FormValue("username")) + creds.Password = r.FormValue("password") + + // Retrieve the hashed password from the database + hashedPassword, userExists := getUserFromDatabase(creds.Username) + if !userExists { + errorMessage := creds.Username + " does not exist" + log.Println(errorMessage) + w.WriteHeader(http.StatusUnauthorized) + json.NewEncoder(w).Encode(map[string]interface{}{ + "error": "Incorrect username or password", + }) + return + } + + // Compare the stored hashed password with the provided password + err = bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(creds.Password)) + if err != nil { + errorMessage := "Incorrect username or password" + log.Println(errorMessage) + w.WriteHeader(http.StatusUnauthorized) + json.NewEncoder(w).Encode(map[string]interface{}{ + "error": errorMessage, + }) + return + } + + // Create a new session token + sessionToken := uuid.NewString() + expiresAt := time.Now().Add(sessionLength) + + // Store the token in the session map + sessions[sessionToken] = session{ + username: creds.Username, + expiry: expiresAt, + } + + // Set the session token as a cookie + http.SetCookie(w, &http.Cookie{ + Name: "session_token", + Value: sessionToken, + Expires: expiresAt, + }) + + log.Printf("User logged in: %s", creds.Username) + + // Send JSON response indicating successful login + w.WriteHeader(http.StatusOK) + json.NewEncoder(w).Encode(map[string]interface{}{ + "message": "Login successful", + }) +} + +func getUserFromDatabase(username string) (string, bool) { + var hashedPassword string + err := db.QueryRow("SELECT password FROM users WHERE username = $1", username).Scan(&hashedPassword) + if err == sql.ErrNoRows { + // User not found + return "", false + } else if err != nil { + log.Printf("Error retrieving user from the database: %v", err) + return "", false + } + + return hashedPassword, true +} + +func getUserUUID(username string) (string, error) { + var uuid string + err := db.QueryRow("SELECT uuid FROM users WHERE username = $1", username).Scan(&uuid) + if err != nil { + if err == sql.ErrNoRows { + // User not found + return "", fmt.Errorf("user not found: %s", username) + } + return "", err + } + return uuid, nil +} + +func Logout(w http.ResponseWriter, r *http.Request) { + // Get the session token from the request cookies + sessionCookie, err := r.Cookie("session_token") + if err != nil { + log.Printf("Error getting session cookie: %v", err) + http.Error(w, "Unauthorized", http.StatusUnauthorized) + return + } + + sessionToken := sessionCookie.Value + + // Remove the user's session from the session map + delete(sessions, sessionToken) + + log.Printf("User logged out") + + // Set the user's `session_token` cookie to an empty value and an immediate expiry time + http.SetCookie(w, &http.Cookie{ + Name: "session_token", + Value: "", + Expires: time.Now(), + }) + + // Redirect to the index page + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func Signup(w http.ResponseWriter, r *http.Request) { + // Check if the request method is POST + if r.Method == http.MethodPost { + var creds Credentials + err := r.ParseForm() + if err != nil { + log.Printf("Error parsing form: %v", err) + http.Error(w, "Bad Request", http.StatusBadRequest) + return + } + + creds.Username = strings.ToLower(r.FormValue("username")) + creds.Password = r.FormValue("password") + name := r.FormValue("name") + email := r.FormValue("email") + // Check if the username is already taken + if _, userExists := getUserFromDatabase(creds.Username); userExists { + log.Printf("Username already exists: %s", creds.Username) + http.Error(w, "Username Already Taken", http.StatusConflict) + return + } + + // Hash the user's password + hashedPassword, err := bcrypt.GenerateFromPassword([]byte(creds.Password), hashCost) + if err != nil { + log.Printf("Error hashing password: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + // Generate a UUID for the user + userUUID := uuid.New() + + // Store the user in the database with the generated UUID + if err := insertUserIntoDatabase(creds.Username, string(hashedPassword), string("normal"), userUUID.String(), name, email); err != nil { + log.Printf("Error inserting user into database: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + return + } + + // Create a new session token + sessionToken := uuid.NewString() + expiresAt := time.Now().Add(sessionLength) + + // Store the token in the session map + sessions[sessionToken] = session{ + username: creds.Username, + expiry: expiresAt, + sessionUUID: userUUID.String(), + } + + // Set the session token as a cookie + http.SetCookie(w, &http.Cookie{ + Name: "session_token", + Value: sessionToken, + Expires: expiresAt, + }) + + log.Printf("User signed up and added to database: %s", creds.Username) + + createUserFolder(creds.Username) + + // Redirect to the new user page + http.Redirect(w, r, "/welcome", http.StatusSeeOther) + return + } + +} diff --git a/wait-for-postgres.sh b/wait-for-postgres.sh new file mode 100755 index 0000000..def3f6e --- /dev/null +++ b/wait-for-postgres.sh @@ -0,0 +1,14 @@ +#!/bin/sh + +host="$1" +port="$2" +shift 2 +cmd="$@" + +until nc -z -v -w1 "$host" "$port"; do + >&2 echo "PostgreSQL is unavailable - sleeping" + sleep 5 +done + +>&2 echo "PostgreSQL is up - executing command" +exec $cmd