├── .github └── workflows │ └── build.yml ├── .gitignore ├── .vscode ├── launch.json ├── settings.json └── tasks.json ├── LICENSE ├── README.md ├── README_zh_cn.md ├── assets ├── appicon.png ├── assets.go ├── hugo.toml ├── icon2.png └── themes.zip ├── backend ├── app.go ├── conf.go ├── deploy │ ├── aws.go │ ├── azure.go │ ├── cos.go │ ├── deploy_test.go │ ├── git.go │ ├── netlify.go │ └── oss.go ├── deploys.go ├── fileloader.go ├── hugo.go ├── hugo_test.go ├── model.go └── util │ ├── utils.go │ └── utils_test.go ├── build ├── README.md ├── appicon.png ├── darwin │ ├── Info.dev.plist │ └── Info.plist └── windows │ ├── info.json │ ├── installer │ ├── project.nsi │ └── wails_tools.nsh │ └── wails.exe.manifest ├── doc ├── deploy │ └── cos.md └── images │ ├── 1.png │ ├── 2.png │ └── 3.png ├── frontend ├── README.md ├── components.json ├── index.html ├── jsconfig.json ├── package-lock.json ├── package.json ├── package.json.md5 ├── postcss.config.js ├── src │ ├── assets │ │ └── react.svg │ ├── components │ │ ├── page │ │ │ ├── editor │ │ │ │ └── page.jsx │ │ │ ├── home.jsx │ │ │ ├── settings │ │ │ │ ├── app.jsx │ │ │ │ ├── deploy │ │ │ │ │ ├── cos.jsx │ │ │ │ │ ├── git.jsx │ │ │ │ │ ├── layout.jsx │ │ │ │ │ ├── netlify.jsx │ │ │ │ │ └── oss.jsx │ │ │ │ ├── page.jsx │ │ │ │ └── site.jsx │ │ │ ├── style.css │ │ │ ├── test.jsx │ │ │ └── util.js │ │ └── ui │ │ │ ├── badge.jsx │ │ │ ├── button.jsx │ │ │ ├── card.jsx │ │ │ ├── checkbox.jsx │ │ │ ├── form.jsx │ │ │ ├── input.jsx │ │ │ ├── label.jsx │ │ │ ├── select.jsx │ │ │ ├── separator.jsx │ │ │ ├── sheet.jsx │ │ │ ├── sonner.jsx │ │ │ ├── tabs.jsx │ │ │ └── taginput.jsx │ ├── index.css │ ├── lib │ │ └── utils.js │ └── main.jsx ├── tailwind.config.js ├── vite.config.js └── yarn.lock ├── go.mod ├── go.sum ├── main.go └── wails.json /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Swallow build 2 | 3 | on: 4 | push: 5 | tags: 6 | - v* 7 | 8 | permissions: 9 | contents: read 10 | 11 | jobs: 12 | prepare: 13 | name: Prepare release environment 14 | runs-on: ubuntu-latest 15 | steps: 16 | - run: env 17 | build-gui: 18 | name: Build gui 19 | needs: prepare 20 | strategy: 21 | fail-fast: false 22 | matrix: 23 | include: 24 | - os: windows-latest 25 | platform: windows/amd64 26 | output: Swallow.exe 27 | - os: macos-latest 28 | platform: darwin/universal 29 | # wails bug, mac 的 output file 不生效, 先用这个保证能用 30 | output: Swallow 31 | - os: ubuntu-latest 32 | platform: linux/amd64 33 | output: Swallow-linux 34 | runs-on: ${{ matrix.os }} 35 | steps: 36 | - uses: actions/checkout@v3 37 | with: 38 | submodules: recursive 39 | - name: Setup NodeJS 40 | uses: actions/setup-node@v3 41 | with: 42 | node-version: 18 43 | - uses: rangwea/wails-build-action@v1 44 | with: 45 | build-name: ${{ matrix.output }} 46 | build-platform: ${{ matrix.platform }} 47 | go-version: 1.22.x 48 | package: false 49 | - if: runner.os == 'macOS' 50 | shell: bash 51 | run: | 52 | rm -rf ./build/bin/${{ matrix.output }}.app.zip 53 | zip -q -r -j ./build/bin/${{matrix.output}}.app.zip ./build/bin/${{matrix.output}}.app 54 | rm -rf ./build/bin/${{ matrix.output }}.app 55 | 56 | - uses: actions/upload-artifact@v2 57 | with: 58 | name: target 59 | path: build/bin/* 60 | 61 | collect-release: 62 | name: Collect and release 63 | needs: [build-gui] 64 | runs-on: ubuntu-latest 65 | permissions: 66 | contents: write 67 | steps: 68 | - uses: actions/checkout@v3 69 | with: 70 | fetch-depth: 0 71 | - uses: actions/download-artifact@v3 72 | with: 73 | name: target 74 | path: target 75 | - working-directory: target 76 | run: | 77 | ls -al target && ls -R target/ 78 | rm -rf Swallow-amd64-installer.exe 79 | rm -rf Swallow.pkg 80 | mv Swallow.app.zip Swallow-darwin.app.zip 81 | - run: ls -al target && ls -R target/ && file target/ 82 | - uses: actions/upload-artifact@v3 83 | with: 84 | name: target-release 85 | path: target/* 86 | 87 | # release assets 88 | - name: Create release 89 | id: create_release 90 | uses: softprops/action-gh-release@v1 91 | if: startsWith(github.ref, 'refs/tags/') 92 | with: 93 | files: target/* -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/bin 2 | node_modules 3 | frontend/dist 4 | frontend/wailsjs 5 | backend/logs 6 | backend/db 7 | .DS_Store 8 | logs 9 | .idea -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Wails: Production swallows", 6 | "type": "go", 7 | "request": "launch", 8 | "mode": "exec", 9 | "program": "${workspaceFolder}/build/bin/swallows", 10 | "preLaunchTask": "build", 11 | "cwd": "${workspaceFolder}" 12 | }, 13 | { 14 | "name": "Wails: Debug swallows", 15 | "type": "go", 16 | "request": "launch", 17 | "mode": "exec", 18 | "program": "${workspaceFolder}/build/bin/swallows", 19 | "preLaunchTask": "build debug", 20 | "cwd": "${workspaceFolder}" 21 | }, 22 | { 23 | "name": "Wails: Dev swallows", 24 | "type": "go", 25 | "request": "launch", 26 | "mode": "exec", 27 | "program": "${workspaceFolder}/build/bin/swallows", 28 | "preLaunchTask": "build dev", 29 | "cwd": "${workspaceFolder}" 30 | } 31 | ] 32 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.wordWrapColumn": 150 3 | } -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "type": "shell", 7 | "options": { 8 | "cwd": "${workspaceFolder}", 9 | "env": { 10 | "CGO_ENABLED": "1" 11 | } 12 | }, 13 | "osx": { 14 | "options": { 15 | "env": { 16 | "CGO_CFLAGS": "-mmacosx-version-min=10.13", 17 | "CGO_LDFLAGS": "-framework UniformTypeIdentifiers -mmacosx-version-min=10.13" 18 | } 19 | } 20 | }, 21 | "windows": { 22 | "options": { 23 | "env": { 24 | "CGO_ENABLED": "0" 25 | } 26 | } 27 | }, 28 | "command": "go", 29 | "args": [ 30 | "build", 31 | "-tags", 32 | "production,desktop", 33 | "-gcflags", 34 | "all=-N -l", 35 | "-o", 36 | "build/bin/swallows" 37 | ] 38 | }, 39 | { 40 | "label": "build debug", 41 | "type": "shell", 42 | "options": { 43 | "cwd": "${workspaceFolder}", 44 | "env": { 45 | "CGO_ENABLED": "1" 46 | } 47 | }, 48 | "osx": { 49 | "options": { 50 | "env": { 51 | "CGO_CFLAGS": "-mmacosx-version-min=10.13", 52 | "CGO_LDFLAGS": "-framework UniformTypeIdentifiers -mmacosx-version-min=10.13" 53 | } 54 | } 55 | }, 56 | "windows": { 57 | "options": { 58 | "env": { 59 | "CGO_ENABLED": "0" 60 | } 61 | } 62 | }, 63 | "command": "go", 64 | "args": [ 65 | "build", 66 | "-tags", 67 | "production,desktop,debug", 68 | "-gcflags", 69 | "all=-N -l", 70 | "-o", 71 | "build/bin/swallows" 72 | ] 73 | }, 74 | { 75 | "label": "build dev", 76 | "type": "shell", 77 | "options": { 78 | "cwd": "${workspaceFolder}", 79 | "env": { 80 | "CGO_ENABLED": "1" 81 | } 82 | }, 83 | "osx": { 84 | "options": { 85 | "env": { 86 | "CGO_CFLAGS": "-mmacosx-version-min=10.13", 87 | "CGO_LDFLAGS": "-framework UniformTypeIdentifiers -mmacosx-version-min=10.13" 88 | } 89 | } 90 | }, 91 | "windows": { 92 | "options": { 93 | "env": { 94 | "CGO_ENABLED": "0" 95 | } 96 | } 97 | }, 98 | "command": "go", 99 | "args": [ 100 | "build", 101 | "-tags", 102 | "dev", 103 | "-gcflags", 104 | "all=-N -l", 105 | "-o", 106 | "build/bin/swallows" 107 | ] 108 | } 109 | ] 110 | } 111 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Swallow

2 | 3 |

4 |
5 |

6 | 7 |

8 | A cool static blog client. 9 |

10 | 11 |

12 | 13 | GitHub 14 | 15 | 16 | For 17 | 18 | 19 | wails 20 | 21 | 22 | wails 23 | 24 |

25 | 26 |
27 | 28 | 29 | 30 | [English](README.md) · [简体中文](README_zh_cn.md) 31 | 32 | 33 | 34 |
35 | 36 | ## About 37 | 38 | Swallow is a simple gui desktop application for Hugo, so it is also a cool static blog client. 39 | 40 | Swallow was being developed with Go using Wails. 41 | 42 | ## Feature 43 | 44 | - Simple article list management, you can search articles by titles and tags. 45 | - Simple and cool Markdown editor, syntax highlighting, tags settings, Markdown preview, copy to insert pictures, drag and drop to insert pictures and file selector to insert pictures. 46 | - Full platform support for Windows, MacOS and Linux. 47 | - Preview site on local. 48 | - Remote deployment to Github. 49 | - [Hugo Theme](https://themes.gohugo.io/),choose the look you like. Multiple built-in themes. 50 | 51 | ![](./doc/images/1.png) 52 | ![](./doc/images/2.png) 53 | ![](./doc/images/3.png) 54 | 55 | ## Roadmap 56 | 57 | - Picture Bed 58 | - More remote deployment methods 59 | 60 | ## Deveplop 61 | 62 | If you also love programming, you are welcome to contribute code. 63 | 64 | #### Enviroment 65 | 66 | - [GO](https://go.dev/doc/install) 67 | - [Node](https://nodejs.org/en/learn/getting-started/how-to-install-nodejs) 68 | - [Wails](https://wails.io/docs/next/gettingstarted/installation) 69 | 70 | > As Swallow is mainly developed based on the Wails framework, the environment can be installed following the [installation tutorial of Wails](https://wails.io/docs/next/gettingstarted/installation), which includes the installation of Go and NPM. 71 | 72 | ``` 73 | git clone git@github.com:rangwea/swallow-wails.git 74 | cd swallow-wails 75 | wails dev 76 | ``` 77 | 78 | ## Story 79 | 80 | The project first author is a backend programmer mainly using Java and Python. He has worked on backend, middleware, and big data development. He likes to write small tools, so he taught himself some frontend knowledge. 81 | 82 | The original intention of this project was to create a simple GUI wrapper for Hugo for a friend who is new to the field, allowing him to use Hugo to create his own blog. 83 | 84 | There have been many explorations in the early stages of the project, resulting in multiple implementations of Swallow. Interested parties can follow the different implementations of Swallow for learning and discussion. 85 | 86 | - [swallos-wails](https://github.com/rangwea/swallow-wails): Base on [wails](https://wails.io/) framework using Go. 87 | - [swallow-pywebview](https://github.com/rangwea/swallow-pywebview): Base on [pywebview](https://pywebview.flowrl.com/) using Python,the frontend base on [alpinejs](https://alpinejs.dev/) and [tailwindcss](https://tailwindcss.com/)。 88 | - [swallow-pyside](https://github.com/rangwea/swallow-pyside): Base on [Pyside](https://doc.qt.io/qtforpython-6/). 89 | -------------------------------------------------------------------------------- /README_zh_cn.md: -------------------------------------------------------------------------------- 1 |

Swallow

2 | 3 |

4 |
5 |

6 | 7 |

8 | A cool static blog client. 9 |

10 | 11 |

12 | 13 | GitHub 14 | 15 | 16 | For 17 | 18 | 19 | wails 20 | 21 | 22 | wails 23 | 24 |

25 | 26 |
27 | 28 | 29 | 30 | [English](README.md) · [简体中文](README_zh_cn.md) 31 | 32 | 33 | 34 |
35 | 36 | ## About 37 | 38 | `Swallow` 是一个静态博客客户端,它是一个 `Hugo` gui 工具。你可以使用 Swallow 创建、写作自己的博客。 39 | 40 | Swallow 使用 Go 语言的 GUI 框架 [Wails](https://wails.io/) 开发。 41 | 42 | ## 特性 43 | 44 | - 简单的文章列表管理,可以根据标题、标签搜索文章 45 | - 简单又酷的 Markdown 编辑器,语法高亮,标签设置、Markdown预览,复制插入图片、拖拽插入图片和文件选择器插入图片 46 | - Windows、MacOS 和 Linux 全平台支持 47 | - 本地预览站点 48 | - Github 远程部署 49 | - [Hugo 主题](https://themes.gohugo.io/),选择你喜欢的样子。内置多款主题。 50 | 51 | ![](./doc/images/1.png) 52 | ![](./doc/images/2.png) 53 | ![](./doc/images/3.png) 54 | 55 | ## Roadmap 56 | 57 | - 图床 58 | - 支持更多远程部署 59 | 60 | ## 开发 61 | 62 | 如果你也喜欢编程,欢迎贡献代码 63 | 64 | #### 环境要求 65 | 66 | - [GO 环境](https://go.dev/doc/install) 67 | - [Node 环境](https://nodejs.org/en/learn/getting-started/how-to-install-nodejs) 68 | - [Wails 安装](https://wails.io/docs/next/gettingstarted/installation) 69 | 70 | > 因为 Swallow 主要基于 wails 框架开发,环境可以参考 [wails 的安装教程](https://wails.io/docs/next/gettingstarted/installation),其中包括了 Go 和 NPM 的环境安装。 71 | 72 | ``` 73 | git clone git@github.com:rangwea/swallow-wails.git 74 | cd swallow-wails 75 | wails dev 76 | ``` 77 | 78 | ## 故事 79 | 80 | 作者是一名后端程序员,主要开发语言是 Java 和 Python,做过后台、中间件和大数据开发。平时喜欢写写小工具,所以自学了一点前端知识。 81 | 这个项目的初衷是给一位小白朋友做一个简单的 Hugo GUI 封装,让他能够使用 Hugo 来创建自己的博客。 82 | 项目前期做过很多探索,所以 Swallow 有多个不同版本的实现,有兴趣的可以关注 Swallow 的不同实现,作为学习和讨论。 83 | 84 | - [swallos-wails](https://github.com/rangwea/swallow-wails): 基于 Go 的 [wails](https://wails.io/) 框架开发。 85 | - [swallow-pywebview](https://github.com/rangwea/swallow-pywebview): 基于 Python 的 [pywebview](https://pywebview.flowrl.com/) 框架开发,前端使用 [alpinejs](https://alpinejs.dev/) 和 [tailwindcss](https://tailwindcss.com/)。 86 | - [swallow-pyside](https://github.com/rangwea/swallow-pyside): 基于 [Pyside](https://doc.qt.io/qtforpython-6/) 开发。 87 | -------------------------------------------------------------------------------- /assets/appicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rangwea/swallow/2d3dca6ed2d84d13d8a48c97c873d71adebb02f1/assets/appicon.png -------------------------------------------------------------------------------- /assets/assets.go: -------------------------------------------------------------------------------- 1 | package assets 2 | 3 | import "embed" 4 | 5 | //go:embed hugo.toml themes.zip 6 | var Asserts embed.FS 7 | -------------------------------------------------------------------------------- /assets/hugo.toml: -------------------------------------------------------------------------------- 1 | baseURL = "http://localhost:1313/" 2 | languageCode = "zh-cn" 3 | defaultContentLanguage = "zh" 4 | title = "swallow" 5 | description = "this is my first blogs" 6 | theme = "mini" 7 | copyright = "" 8 | buildFuture = true 9 | 10 | [menu] 11 | main = [ 12 | { identifier = "home", name = "Home", url = "/", weight = 1 }, 13 | { identifier = "articles", name = "Articles", url = "/post", weight = 2 }, 14 | { identifier = "categories", name = "Categories", url = "/categories", weight = 3 }, 15 | { identifier = "tags", name = "Tags", url = "/tags", weight = 4 }, 16 | { identifier = "about", name = "About", url = "/about", weight = 5 }, 17 | ] 18 | 19 | [params] 20 | hiddenPostSummaryInHomePage = true 21 | 22 | [params.author] 23 | name = "swallow" 24 | -------------------------------------------------------------------------------- /assets/icon2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rangwea/swallow/2d3dca6ed2d84d13d8a48c97c873d71adebb02f1/assets/icon2.png -------------------------------------------------------------------------------- /assets/themes.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rangwea/swallow/2d3dca6ed2d84d13d8a48c97c873d71adebb02f1/assets/themes.zip -------------------------------------------------------------------------------- /backend/app.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | import ( 4 | "context" 5 | "encoding/json" 6 | "fmt" 7 | "os" 8 | "os/user" 9 | "path" 10 | "strconv" 11 | "strings" 12 | "time" 13 | 14 | "github.com/pkg/errors" 15 | "github.com/rangwea/swallows/backend/util" 16 | 17 | "github.com/jmoiron/sqlx" 18 | _ "github.com/mattn/go-sqlite3" 19 | rt "github.com/wailsapp/wails/v2/pkg/runtime" 20 | ) 21 | 22 | var AppHome string 23 | var DB *sqlx.DB 24 | 25 | const InitSql = `CREATE TABLE IF NOT EXISTS t_article( 26 | id INTEGER PRIMARY KEY autoincrement, 27 | title VARCHAR NOT NULL, 28 | tags VARCHAR, 29 | create_time DATETIME, 30 | update_time DATETIME 31 | ); 32 | CREATE INDEX IF NOT EXISTS idx_t_article_title ON t_article(title); 33 | CREATE INDEX IF NOT EXISTS idx_t_article_tags ON t_article(tags); 34 | CREATE INDEX IF NOT EXISTS idx_t_article_create_time ON t_article(create_time); 35 | CREATE INDEX IF NOT EXISTS idx_t_article_update_time ON t_article(update_time);` 36 | 37 | // App struct 38 | type App struct { 39 | ctx context.Context 40 | } 41 | 42 | // NewApp creates a new App application struct 43 | func NewApp() *App { 44 | return &App{} 45 | } 46 | 47 | // Startup is called when the app starts. The context is saved 48 | func (a *App) Startup(ctx context.Context) { 49 | a.ctx = ctx 50 | 51 | defer func() { 52 | if r := recover(); r != nil { 53 | rt.MessageDialog(a.ctx, rt.MessageDialogOptions{ 54 | Type: rt.ErrorDialog, 55 | Message: fmt.Sprintf("app crashed:\n%s", r), 56 | }) 57 | rt.Quit(a.ctx) 58 | } 59 | }() 60 | 61 | // initialize 62 | initialize() 63 | } 64 | 65 | func initialize() { 66 | // global cons init 67 | initAppHome() 68 | 69 | // db init 70 | initDB() 71 | 72 | // component init 73 | Conf.Initialize() 74 | Hugo.Initialize() 75 | } 76 | 77 | func initAppHome() { 78 | u, err := user.Current() 79 | if err != nil { 80 | panic(err) 81 | } 82 | AppHome = path.Join(u.HomeDir, ".swallow") 83 | if e, _ := util.PathExists(AppHome); !e { 84 | if err = os.Mkdir(AppHome, os.ModePerm); err != nil { 85 | panic(fmt.Errorf("make app home dir fail", err)) 86 | } 87 | } 88 | } 89 | 90 | func initDB() { 91 | DB = sqlx.MustOpen("sqlite3", path.Join(AppHome, "db")) 92 | DB.MustExec(InitSql) 93 | } 94 | 95 | const ( 96 | CodeSuccess = 1 97 | CodeError = 0 98 | ) 99 | 100 | type R struct { 101 | Code int `json:"code"` 102 | Msg string `json:"msg"` 103 | Data interface{} `json:"data"` 104 | } 105 | 106 | type AppConf struct { 107 | ActivedDeploy ConfType `json:"activedDeploy"` 108 | } 109 | 110 | const confTypeApp ConfType = "app" 111 | 112 | const SiteImagePath = "/static/images" 113 | 114 | func (a *App) SitePreview() *R { 115 | err := Hugo.Preview() 116 | if err != nil { 117 | return fail(err) 118 | } 119 | err = util.OpenBrowser("http://localhost:1313/") 120 | if err != nil { 121 | return fail(err) 122 | } 123 | return success(nil) 124 | } 125 | 126 | func (a *App) SiteDeploy() *R { 127 | err := Hugo.Build() 128 | if err != nil { 129 | return fail(err) 130 | } 131 | 132 | ac, err := getAppConf() 133 | if err != nil { 134 | return fail(errors.Wrap(err, "get app conf fail")) 135 | } 136 | if ac == nil || ac.ActivedDeploy == "" { 137 | return fail(errors.New("please set server config")) 138 | } 139 | 140 | err = Deployers.Deploy(ac.ActivedDeploy, Hugo.PublicDir) 141 | if err != nil { 142 | return fail(errors.Wrap(err, "deploy fail")) 143 | } 144 | 145 | return success(nil) 146 | } 147 | 148 | func (a *App) ArticleList(search string, page int) *R { 149 | where := "" 150 | if search != "" { 151 | where += " where title like ? or tags like ?" 152 | search = "%" + search + "%" 153 | } 154 | 155 | offset := page * 10 156 | countSql := "select count(id) from t_article " + where 157 | pageSql := "select * from t_article " + where + " order by update_time desc limit 10 offset " + strconv.Itoa(offset) 158 | 159 | r := make(map[string]interface{}) 160 | count := 0 161 | l := []Article{} 162 | r["total"] = &count 163 | r["list"] = &l 164 | 165 | DB.Get(&count, countSql, search, search) 166 | 167 | if count == 0 { 168 | return success(r) 169 | } 170 | 171 | err := DB.Select(&l, pageSql, search, search) 172 | if err != nil { 173 | return fail(err) 174 | } 175 | 176 | return success(r) 177 | } 178 | 179 | func (a *App) ArticleSave(aid string, meta Meta, content string) *R { 180 | n := time.Now().Format("2006-01-02 15:04:05") 181 | meta.Lastmod = n 182 | if meta.Date == "" { 183 | meta.Date = n 184 | } 185 | 186 | if aid != AboutAid { 187 | // common article need save db 188 | err := saveArticleToDB(&aid, meta) 189 | if err != nil { 190 | return fail(err) 191 | } 192 | } 193 | 194 | err := Hugo.WriteArticle(aid, meta, content) 195 | if err != nil { 196 | return fail(err) 197 | } 198 | 199 | return success(aid) 200 | } 201 | 202 | func (a *App) ArticleGet(aid string) *R { 203 | meta, content, err := Hugo.ReadArticle(aid) 204 | if err != nil { 205 | return fail(err) 206 | } 207 | data := map[string]interface{}{ 208 | "meta": meta, 209 | "content": content, 210 | } 211 | return success(data) 212 | } 213 | 214 | func (a *App) ArticleRemove(aids []string) *R { 215 | _, err := DB.Exec(fmt.Sprintf("delete from t_article where id in(%s)", strings.Join(aids[:], ","))) 216 | if err != nil { 217 | return fail(err) 218 | } 219 | for _, aid := range aids { 220 | Hugo.DeleteArticle(aid) 221 | } 222 | return success(nil) 223 | } 224 | 225 | func (a *App) ArticleInsertImage(aid string) *R { 226 | selection, err := rt.OpenFileDialog(a.ctx, rt.OpenDialogOptions{ 227 | Title: "Select Image", 228 | Filters: []rt.FileFilter{ 229 | { 230 | DisplayName: "Images (*.png;*.jpg;*.gif;*.jpeg)", 231 | Pattern: "*.png;*.jpg;*.gif;*.jpeg", 232 | }, 233 | }, 234 | }) 235 | if err != nil { 236 | return fail(err) 237 | } 238 | 239 | imageDir := Hugo.GetArticleImageDir(aid) 240 | os.Mkdir(imageDir, os.ModePerm) 241 | 242 | localPath, sitePath := Hugo.GenArticleImagePath(aid) 243 | err = util.CopyFile(selection, localPath) 244 | if err != nil { 245 | return fail(err) 246 | } 247 | 248 | return success(sitePath) 249 | } 250 | 251 | func (a *App) ArticleInsertImageBlob(aid int, blob string) *R { 252 | var file []byte 253 | if err := json.Unmarshal([]byte(blob), &file); err != nil { 254 | return fail(err) 255 | } 256 | 257 | aida := strconv.Itoa(aid) 258 | 259 | imageDir := Hugo.GetArticleImageDir(aida) 260 | os.Mkdir(imageDir, os.ModePerm) 261 | 262 | localPath, sitePath := Hugo.GenArticleImagePath(aida) 263 | err := os.WriteFile(localPath, file, os.ModePerm) 264 | if err != nil { 265 | return fail(err) 266 | } 267 | 268 | return success(sitePath) 269 | } 270 | 271 | func (a *App) SiteConfigGet() *R { 272 | c, err := Hugo.ReadConfig() 273 | if err != nil { 274 | return fail(err) 275 | } 276 | return success(c) 277 | } 278 | 279 | func (a *App) SiteConfigSave(c Config) *R { 280 | err := Hugo.WriteConfig(c) 281 | if err != nil { 282 | return fail(err) 283 | } 284 | return success(nil) 285 | } 286 | 287 | func (a *App) SiteConfigGetStr() *R { 288 | c, err := Hugo.ReadConfigStr() 289 | if err != nil { 290 | return fail(err) 291 | } 292 | return success(c) 293 | } 294 | 295 | func (a *App) SiteConfigSaveStr(c []byte) *R { 296 | err := Hugo.WriteConfigStr(c) 297 | if err != nil { 298 | return fail(err) 299 | } 300 | return success(nil) 301 | } 302 | 303 | func (a *App) ConfGet(t ConfType) *R { 304 | v, err := Conf.Read(t) 305 | if err != nil { 306 | return fail(err) 307 | } 308 | var r map[string]interface{} 309 | json.Unmarshal(v, &r) 310 | return success(r) 311 | } 312 | 313 | func (a *App) ConfSave(t ConfType, v string) *R { 314 | appConf, err := getAppConf() 315 | if err != nil { 316 | return fail(err) 317 | } 318 | appConf.ActivedDeploy = t 319 | appConfBytes, err := json.Marshal(appConf) 320 | if err != nil { 321 | return fail(errors.New("app conf marshal error")) 322 | } 323 | Conf.Write(confTypeApp, string(appConfBytes)) 324 | 325 | err = Conf.Write(t, v) 326 | if err != nil { 327 | return fail(err) 328 | } 329 | return success(nil) 330 | } 331 | 332 | func (a *App) ConfGetThemes() *R { 333 | ts, err := Hugo.GetThemes() 334 | if err != nil { 335 | return fail(err) 336 | } 337 | return success(ts) 338 | } 339 | 340 | func (a *App) SelectConfImage(img string) *R { 341 | selection, err := rt.OpenFileDialog(a.ctx, rt.OpenDialogOptions{ 342 | Title: "Select Image", 343 | Filters: []rt.FileFilter{ 344 | { 345 | DisplayName: "Images (*.png;*.jpg;*.gif;*.jpeg;*.ico)", 346 | Pattern: "*.png;*.jpg;*.gif;*.jpeg;*.ico", 347 | }, 348 | }, 349 | }) 350 | if err != nil { 351 | return fail(err) 352 | } 353 | 354 | p := path.Join(Hugo.ImageDir, img) 355 | // remove old 356 | os.Remove(p) 357 | 358 | // copy conf image 359 | err = util.CopyFile(selection, p) 360 | if err != nil { 361 | return fail(err) 362 | } 363 | 364 | return success(nil) 365 | } 366 | 367 | func (a *App) GetSiteImageConf(imgPath string) *R { 368 | avatar := "" 369 | _, err := os.Stat(Hugo.ImageDir + "/avatar.png") 370 | if !os.IsNotExist(err) { 371 | avatar = SiteImagePath + "/avatar.png" 372 | } 373 | 374 | favicon := "" 375 | _, err = os.Stat(Hugo.ImageDir + "/favicon.ico") 376 | if !os.IsNotExist(err) { 377 | favicon = SiteImagePath + "/favicon.ico" 378 | } 379 | return success(map[string]string{ 380 | "avatar": avatar, 381 | "favicon": favicon, 382 | }) 383 | } 384 | 385 | func saveArticleToDB(aidpr *string, meta Meta) error { 386 | title := meta.Title 387 | createTime := meta.Date 388 | tags := strings.Join(meta.Tags, ",") 389 | updateTime := meta.Lastmod 390 | 391 | aid := *aidpr 392 | 393 | if aid == "" { 394 | r, err := DB.Exec("insert into t_article(title, tags, create_time, update_time) values(?,?,?,?)", 395 | title, tags, createTime, updateTime) 396 | if err != nil { 397 | return err 398 | } 399 | nid, err := r.LastInsertId() 400 | if err != nil { 401 | return err 402 | } 403 | *aidpr = strconv.FormatInt(nid, 10) 404 | } else { 405 | id, err := strconv.Atoi(aid) 406 | if err != nil { 407 | return err 408 | } 409 | _, err = DB.Exec("update t_article set title=?, tags=?, update_time=? where id=?", 410 | title, tags, updateTime, id) 411 | if err != nil { 412 | return err 413 | } 414 | } 415 | return nil 416 | } 417 | 418 | func getAppConf() (c *AppConf, err error) { 419 | cs, err := Conf.Read(confTypeApp) 420 | if err != nil { 421 | return 422 | } 423 | c = &AppConf{} 424 | if cs == nil { 425 | return 426 | } 427 | err = json.Unmarshal(cs, c) 428 | return 429 | } 430 | 431 | func success(data interface{}) *R { 432 | return &R{Code: CodeSuccess, Msg: "success", Data: data} 433 | } 434 | 435 | func fail(err error) *R { 436 | return &R{Code: CodeError, Msg: err.Error()} 437 | } 438 | -------------------------------------------------------------------------------- /backend/conf.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | import ( 4 | "fmt" 5 | "os" 6 | "path" 7 | 8 | "github.com/rangwea/swallows/backend/util" 9 | ) 10 | 11 | type ConfType string 12 | 13 | var Conf = _conf{} 14 | 15 | type _conf struct { 16 | DIR string 17 | } 18 | 19 | func (conf *_conf) Initialize() { 20 | conf.DIR = path.Join(AppHome, "conf") 21 | 22 | // init 23 | err := os.Mkdir(conf.DIR, os.ModePerm) 24 | if err != nil && !os.IsExist(err) { 25 | panic(fmt.Errorf("mk config dir fail", err)) 26 | return 27 | } 28 | } 29 | 30 | func (conf *_conf) Read(t ConfType) (v []byte, err error) { 31 | filePath := conf.getFile(t) 32 | if existed, _ := util.PathExists(filePath); !existed { 33 | return 34 | } 35 | 36 | v, err = os.ReadFile(filePath) 37 | if err != nil { 38 | return 39 | } 40 | 41 | return 42 | } 43 | 44 | func (conf *_conf) Write(t ConfType, v string) error { 45 | filePath := conf.getFile(t) 46 | if existed, _ := util.PathExists(filePath); !existed { 47 | os.Create(filePath) 48 | } 49 | 50 | err := os.WriteFile(filePath, []byte(v), os.ModePerm) 51 | return err 52 | } 53 | 54 | func (conf *_conf) getFile(t ConfType) string { 55 | return path.Join(conf.DIR, fmt.Sprintf("%s.json", t)) 56 | } 57 | -------------------------------------------------------------------------------- /backend/deploy/aws.go: -------------------------------------------------------------------------------- 1 | // Amazon S3 2 | // See doc: https://aws.github.io/aws-sdk-go-v2/docs/ 3 | package deploy 4 | 5 | import ( 6 | "context" 7 | "io" 8 | "os" 9 | "reflect" 10 | 11 | "github.com/aws/aws-sdk-go-v2/aws" 12 | "github.com/aws/aws-sdk-go-v2/config" 13 | "github.com/aws/aws-sdk-go-v2/credentials" 14 | "github.com/aws/aws-sdk-go-v2/service/s3" 15 | "github.com/rangwea/swallows/backend/util" 16 | ) 17 | 18 | type Aws struct { 19 | AccountID string `json:"accountId"` 20 | AccessKeyID string `json:"accessKeyID"` 21 | SecretAccessKey string `json:"secretAccessKey"` 22 | Bucket string `json:"bucket"` 23 | } 24 | 25 | type AwsDeployer struct { 26 | } 27 | 28 | func (d *AwsDeployer) Deploy(publicDir string, ci interface{}) (err error) { 29 | c := ci.(Aws) 30 | 31 | cfg, err := config.LoadDefaultConfig(context.Background(), config.WithCredentialsProvider(credentials.StaticCredentialsProvider{ 32 | Value: aws.Credentials{ 33 | AccountID: c.AccountID, 34 | AccessKeyID: c.AccessKeyID, 35 | SecretAccessKey: c.SecretAccessKey, 36 | }, 37 | })) 38 | if err != nil { 39 | return nil 40 | } 41 | 42 | client := s3.NewFromConfig(cfg) 43 | 44 | output, err := client.ListObjectsV2(context.Background(), &s3.ListObjectsV2Input{ 45 | Bucket: aws.String("my-bucket"), 46 | }) 47 | if err != nil { 48 | return err 49 | } 50 | 51 | remoteFiles := make(map[string]*string) 52 | for _, object := range output.Contents { 53 | remoteFiles[*object.Key] = object.ETag 54 | } 55 | 56 | localFiles, err := util.GetLocalFilesMD5(publicDir) 57 | if err != nil { 58 | return 59 | } 60 | 61 | for k, v := range localFiles { 62 | if *remoteFiles[k] != v { 63 | var f *os.File 64 | f, err = os.Open(k) 65 | if err != nil { 66 | return 67 | } 68 | defer f.Close() 69 | _, err = client.UploadPart(context.Background(), &s3.UploadPartInput{ 70 | Key: &k, 71 | Bucket: &c.Bucket, 72 | Body: io.Reader(f), 73 | }) 74 | if err != nil { 75 | return 76 | } 77 | } 78 | } 79 | 80 | for k := range remoteFiles { 81 | if _, ok := localFiles[k]; !ok { 82 | _, err = client.DeleteObject(context.Background(), &s3.DeleteObjectInput{ 83 | Bucket: &c.Bucket, 84 | Key: &k, 85 | }) 86 | if err != nil { 87 | return 88 | } 89 | } 90 | } 91 | 92 | return 93 | } 94 | 95 | func (d *AwsDeployer) ConfType() reflect.Type { 96 | return reflect.TypeOf(Cos{}) 97 | } 98 | -------------------------------------------------------------------------------- /backend/deploy/azure.go: -------------------------------------------------------------------------------- 1 | // Microsoft Azure Blob Storage 2 | // See doc:https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-go?tabs=roles-azure-portal 3 | package deploy 4 | 5 | import ( 6 | "context" 7 | "fmt" 8 | "os" 9 | "reflect" 10 | 11 | "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob" 12 | "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blockblob" 13 | "github.com/rangwea/swallows/backend/util" 14 | ) 15 | 16 | type Azure struct { 17 | Account string `json:"account"` 18 | AccessToken string `json:"accessToken"` 19 | Container string `json:"container"` 20 | } 21 | 22 | type AzureDeployer struct { 23 | } 24 | 25 | func (d *AzureDeployer) Deploy(publicDir string, ci interface{}) (err error) { 26 | c := ci.(Azure) 27 | 28 | url := fmt.Sprintf("https://%s.blob.core.windows.net/?%s", c.Account, c.AccessToken) 29 | 30 | client, err := azblob.NewClientWithNoCredential(url, nil) 31 | if err != nil { 32 | return err 33 | } 34 | 35 | remoteFiles := make(map[string]*string) 36 | pager := client.NewListBlobsFlatPager(c.Container, nil) 37 | for pager.More() { 38 | var resp azblob.ListBlobsFlatResponse 39 | resp, err = pager.NextPage(context.Background()) 40 | if err != nil { 41 | return err 42 | } 43 | for _, blob := range resp.Segment.BlobItems { 44 | remoteFiles[*blob.Name] = blob.Metadata["md5"] 45 | } 46 | } 47 | 48 | localFiles, err := util.GetLocalFilesMD5(publicDir) 49 | if err != nil { 50 | return 51 | } 52 | 53 | for k, v := range localFiles { 54 | if *remoteFiles[k] != v { 55 | var f *os.File 56 | f, err = os.Open(k) 57 | if err != nil { 58 | return 59 | } 60 | defer f.Close() 61 | _, err = client.UploadFile(context.Background(), c.Container, k, f, &blockblob.UploadFileOptions{ 62 | Metadata: map[string]*string{"md5": &v}, 63 | }) 64 | if err != nil { 65 | return 66 | } 67 | } 68 | } 69 | 70 | for k := range remoteFiles { 71 | if _, ok := localFiles[k]; !ok { 72 | _, err = client.DeleteBlob(context.Background(), c.Container, k, nil) 73 | if err != nil { 74 | return 75 | } 76 | } 77 | } 78 | 79 | return 80 | } 81 | 82 | func (d *AzureDeployer) ConfType() reflect.Type { 83 | return reflect.TypeOf(Cos{}) 84 | } 85 | -------------------------------------------------------------------------------- /backend/deploy/cos.go: -------------------------------------------------------------------------------- 1 | package deploy 2 | 3 | import ( 4 | "context" 5 | "net/http" 6 | "net/url" 7 | "path" 8 | "reflect" 9 | 10 | "github.com/rangwea/swallows/backend/util" 11 | "github.com/tencentyun/cos-go-sdk-v5" 12 | ) 13 | 14 | type Cos struct { 15 | SecretId string `json:"secretId"` 16 | SecretKey string `json:"secretKey"` 17 | Region string `json:"region"` 18 | Bucket string `json:"bucket"` 19 | } 20 | 21 | type CosDeployer struct { 22 | } 23 | 24 | func (d *CosDeployer) Deploy(publicDir string, ci interface{}) (err error) { 25 | c := ci.(*Cos) 26 | u, err := url.Parse("https://" + c.Bucket + ".cos." + c.Region + ".myqcloud.com/") 27 | if err != nil { 28 | return err 29 | } 30 | b := &cos.BaseURL{BucketURL: u} 31 | client := cos.NewClient(b, &http.Client{ 32 | Transport: &cos.AuthorizationTransport{ 33 | SecretID: c.SecretId, 34 | SecretKey: c.SecretKey, 35 | }}) 36 | 37 | ctx := context.Background() 38 | 39 | v, _, err := client.Bucket.Get(ctx, &cos.BucketGetOptions{}) 40 | if err != nil { 41 | return 42 | } 43 | 44 | remoteFiles := make(map[string]string) 45 | for _, item := range v.Contents { 46 | var r *cos.Response 47 | r, err = client.Object.Head(ctx, item.Key, nil) 48 | if err != nil { 49 | return err 50 | } 51 | remoteFiles[item.Key] = r.Header.Get("x-cos-hash-crc64ecma") 52 | } 53 | 54 | localFiles, err := util.GetLocalFilesCRC64(publicDir) 55 | if err != nil { 56 | return 57 | } 58 | 59 | for k, v := range localFiles { 60 | if remoteFiles[k] != v { 61 | _, err = client.Object.PutFromFile(context.Background(), k, path.Join(publicDir, k), nil) 62 | if err != nil { 63 | return 64 | } 65 | } 66 | } 67 | 68 | for k := range remoteFiles { 69 | if _, ok := localFiles[k]; !ok { 70 | _, err = client.Object.Delete(context.Background(), k) 71 | if err != nil { 72 | return 73 | } 74 | } 75 | } 76 | 77 | return 78 | } 79 | 80 | func (d *CosDeployer) ConfType() reflect.Type { 81 | return reflect.TypeOf(Cos{}) 82 | } 83 | -------------------------------------------------------------------------------- /backend/deploy/deploy_test.go: -------------------------------------------------------------------------------- 1 | package deploy 2 | 3 | import "testing" 4 | 5 | func AwsDeploy(t *testing.T) { 6 | deployer := &AwsDeployer{} 7 | deployer.Deploy("", &Aws{}) 8 | } 9 | 10 | func TestCosDeploy(t *testing.T) { 11 | deployer := &CosDeployer{} 12 | err := deployer.Deploy("", &Cos{ 13 | SecretId: "", 14 | SecretKey: "", 15 | Region: "", 16 | Bucket: "", 17 | }) 18 | println(err) 19 | } 20 | 21 | func TestOssDeploy(t *testing.T) { 22 | deployer := &OssDeployer{} 23 | err := deployer.Deploy("", &Oss{ 24 | AccessKeyID: "", 25 | AccessKeySecret: "", 26 | Region: "", 27 | Bucket: "", 28 | }) 29 | println(err) 30 | } 31 | -------------------------------------------------------------------------------- /backend/deploy/git.go: -------------------------------------------------------------------------------- 1 | package deploy 2 | 3 | import ( 4 | "github.com/go-git/go-git/v5" 5 | "github.com/go-git/go-git/v5/config" 6 | "github.com/go-git/go-git/v5/plumbing/object" 7 | "github.com/go-git/go-git/v5/plumbing/transport/http" 8 | "reflect" 9 | "time" 10 | ) 11 | 12 | type Github struct { 13 | Repository string `json:"repository"` 14 | Email string `json:"email"` 15 | Username string `json:"username"` 16 | Token string `json:"token"` 17 | Cname string `json:"cname"` 18 | } 19 | 20 | type GitDeployer struct { 21 | } 22 | 23 | func (d *GitDeployer) Deploy(publicDir string, c interface{}) (err error) { 24 | github := c.(Github) 25 | 26 | _, err = git.PlainInit(publicDir, false) 27 | if err != nil { 28 | return 29 | } 30 | 31 | r, err := git.PlainOpen(publicDir) 32 | if err != nil { 33 | return 34 | } 35 | w, err := r.Worktree() 36 | if err != nil { 37 | return 38 | } 39 | _, err = w.Add(".") 40 | if err != nil { 41 | return 42 | } 43 | _, err = w.Commit("deploy", &git.CommitOptions{ 44 | Author: &object.Signature{ 45 | Email: github.Email, 46 | When: time.Now(), 47 | }, 48 | }) 49 | if err != nil { 50 | return 51 | } 52 | 53 | _, err = r.CreateRemote(&config.RemoteConfig{ 54 | Name: "origin", 55 | URLs: []string{github.Repository}, 56 | }) 57 | if err != nil { 58 | return 59 | } 60 | 61 | err = r.Push(&git.PushOptions{ 62 | RemoteName: "origin", 63 | Force: true, 64 | Auth: &http.BasicAuth{ 65 | Username: github.Username, 66 | Password: github.Token, 67 | }, 68 | }) 69 | if err != nil { 70 | return 71 | } 72 | return 73 | } 74 | 75 | func (d *GitDeployer) ConfType() reflect.Type { 76 | return reflect.TypeOf(Github{}) 77 | } 78 | -------------------------------------------------------------------------------- /backend/deploy/netlify.go: -------------------------------------------------------------------------------- 1 | package deploy 2 | 3 | import ( 4 | "context" 5 | "github.com/go-openapi/runtime" 6 | "github.com/go-openapi/strfmt" 7 | netlify "github.com/netlify/open-api/go/porcelain" 8 | nc "github.com/netlify/open-api/go/porcelain/context" 9 | "reflect" 10 | ) 11 | 12 | type Netlify struct { 13 | SiteId string `json:"siteId"` 14 | Token string `json:"token"` 15 | } 16 | 17 | type NetlifyDeployer struct { 18 | } 19 | 20 | func (d *NetlifyDeployer) Deploy(publicDir string, ci interface{}) (err error) { 21 | c := ci.(Netlify) 22 | 23 | client := netlify.Default 24 | authInfoWriter := runtime.ClientAuthInfoWriterFunc(func(r runtime.ClientRequest, 25 | _ strfmt.Registry) error { 26 | err := r.SetHeaderParam("Authorization", "Bearer "+c.Token) 27 | if err != nil { 28 | return err 29 | } 30 | return nil 31 | }) 32 | ctx := nc.WithAuthInfo(context.Background(), authInfoWriter) 33 | _, err = client.DeploySite(ctx, netlify.DeployOptions{ 34 | SiteID: c.SiteId, 35 | Dir: publicDir, 36 | }) 37 | if err != nil { 38 | return 39 | } 40 | 41 | return 42 | } 43 | 44 | func (d *NetlifyDeployer) ConfType() reflect.Type { 45 | return reflect.TypeOf(Netlify{}) 46 | } 47 | -------------------------------------------------------------------------------- /backend/deploy/oss.go: -------------------------------------------------------------------------------- 1 | package deploy 2 | 3 | import ( 4 | "path" 5 | "reflect" 6 | 7 | "github.com/aliyun/aliyun-oss-go-sdk/oss" 8 | "github.com/rangwea/swallows/backend/util" 9 | ) 10 | 11 | type Oss struct { 12 | AccessKeyID string `json:"secretId"` 13 | AccessKeySecret string `json:"secretKey"` 14 | Region string `json:"region"` 15 | Bucket string `json:"bucket"` 16 | } 17 | 18 | type OssDeployer struct { 19 | } 20 | 21 | func (d *OssDeployer) Deploy(publicDir string, ci interface{}) (err error) { 22 | c := ci.(*Oss) 23 | 24 | client, err := oss.New("oss-cn-hangzhou.aliyuncs.com", c.AccessKeyID, c.AccessKeySecret, oss.Region(c.Region)) 25 | if err != nil { 26 | return 27 | } 28 | 29 | bucket, err := client.Bucket(c.Bucket) 30 | if err != nil { 31 | return 32 | } 33 | 34 | remoteFiles := make(map[string]string) 35 | marker := "" 36 | for { 37 | lsRes, err := bucket.ListObjects(oss.Marker(marker)) 38 | if err != nil { 39 | return err 40 | } 41 | for _, item := range lsRes.Objects { 42 | h, err := bucket.GetObjectDetailedMeta(item.Key) 43 | if err != nil { 44 | return nil 45 | } 46 | remoteFiles[item.Key] = h.Get("x-oss-hash-crc64ecma") 47 | } 48 | if lsRes.IsTruncated { 49 | marker = lsRes.NextMarker 50 | } else { 51 | break 52 | } 53 | } 54 | 55 | localFiles, err := util.GetLocalFilesCRC64(publicDir) 56 | if err != nil { 57 | return 58 | } 59 | 60 | for k, v := range localFiles { 61 | if remoteFiles[k] != v { 62 | err = bucket.PutObjectFromFile(k, path.Join(publicDir, k)) 63 | if err != nil { 64 | return 65 | } 66 | } 67 | } 68 | 69 | for k := range remoteFiles { 70 | if _, ok := localFiles[k]; !ok { 71 | err = bucket.DeleteObject(k) 72 | if err != nil { 73 | return 74 | } 75 | } 76 | } 77 | 78 | return 79 | } 80 | 81 | func (d *OssDeployer) ConfType() reflect.Type { 82 | return reflect.TypeOf(Oss{}) 83 | } 84 | -------------------------------------------------------------------------------- /backend/deploys.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/rangwea/swallows/backend/deploy" 6 | "reflect" 7 | ) 8 | 9 | var Deployers = _deployers{} 10 | 11 | type deployer interface { 12 | Deploy(publicDir string, c interface{}) (err error) 13 | 14 | ConfType() reflect.Type 15 | } 16 | 17 | const ( 18 | GITHUB ConfType = "github" 19 | COS ConfType = "cos" 20 | OSS ConfType = "oss" 21 | Netlify ConfType = "netlify" 22 | ) 23 | 24 | // all deployers 25 | var deployers = map[ConfType]deployer{ 26 | GITHUB: &deploy.GitDeployer{}, 27 | COS: &deploy.CosDeployer{}, 28 | OSS: &deploy.OssDeployer{}, 29 | Netlify: &deploy.NetlifyDeployer{}, 30 | } 31 | 32 | type _deployers struct { 33 | } 34 | 35 | func (d *_deployers) Deploy(t ConfType, publicDir string) error { 36 | c, err := Conf.Read(t) 37 | if err != nil { 38 | return err 39 | } 40 | 41 | deployer := deployers[t] 42 | conf := reflect.New(deployer.ConfType()).Interface() 43 | err = json.Unmarshal(c, &conf) 44 | if err != nil { 45 | return err 46 | } 47 | 48 | err = deployer.Deploy(publicDir, conf) 49 | 50 | return nil 51 | } 52 | -------------------------------------------------------------------------------- /backend/fileloader.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "os" 7 | "path" 8 | "strings" 9 | ) 10 | 11 | type FileLoader struct { 12 | http.Handler 13 | } 14 | 15 | func NewFileLoader() *FileLoader { 16 | return &FileLoader{} 17 | } 18 | 19 | func (h *FileLoader) ServeHTTP(res http.ResponseWriter, req *http.Request) { 20 | var err error 21 | 22 | var readFilePath string 23 | if strings.HasPrefix(req.URL.Path, SiteImagePath) { 24 | // site image 25 | readFilePath = path.Join(Hugo.SitePath, req.URL.Path) 26 | } 27 | 28 | if readFilePath == "" { 29 | res.WriteHeader(http.StatusBadRequest) 30 | res.Write([]byte(fmt.Sprintf("Could not load file %s", readFilePath))) 31 | return 32 | } 33 | 34 | fileData, err := os.ReadFile(readFilePath) 35 | if err != nil { 36 | res.WriteHeader(http.StatusBadRequest) 37 | res.Write([]byte(fmt.Sprintf("Could not load file %s", readFilePath))) 38 | } 39 | 40 | res.Write(fileData) 41 | } 42 | -------------------------------------------------------------------------------- /backend/hugo.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "fmt" 7 | "net/http" 8 | "os" 9 | "path" 10 | "strconv" 11 | "strings" 12 | "sync/atomic" 13 | "time" 14 | 15 | "github.com/rangwea/swallows/backend/util" 16 | 17 | "github.com/gohugoio/hugo/config" 18 | "github.com/gohugoio/hugo/config/allconfig" 19 | "github.com/gohugoio/hugo/create/skeletons" 20 | "github.com/gohugoio/hugo/deps" 21 | "github.com/gohugoio/hugo/hugofs" 22 | "github.com/gohugoio/hugo/hugolib" 23 | "github.com/gohugoio/hugo/livereload" 24 | "github.com/pkg/errors" 25 | "golang.org/x/exp/slog" 26 | 27 | "github.com/BurntSushi/toml" 28 | cp "github.com/otiai10/copy" 29 | ) 30 | 31 | const AboutAid string = "about" 32 | 33 | type _hugo struct { 34 | PublicDir string 35 | SitePath string 36 | ImageDir string 37 | hugo string 38 | articleDir string 39 | articleImgDir string 40 | themeDir string 41 | aboutDir string 42 | aboutFile string 43 | cnameFile string 44 | configFile string 45 | server *http.Server 46 | serverRunning atomic.Bool 47 | } 48 | 49 | var Hugo = _hugo{} 50 | 51 | type Meta struct { 52 | Title string `json:"title"` 53 | Tags []string `json:"tags"` 54 | Description string `json:"description"` 55 | Date string `json:"date"` 56 | Lastmod string `json:"lastmod"` 57 | } 58 | 59 | type Config struct { 60 | Title string `json:"title"` 61 | Description string `json:"description"` 62 | DefaultContentLanguage string `json:"defaultContentLanguage"` 63 | Theme string `json:"theme"` 64 | Copyright string `json:"copyright"` 65 | Params *ConfigParams `json:"params"` 66 | } 67 | 68 | type ConfigParams struct { 69 | Author *ConfigAuthor `json:"author"` 70 | } 71 | 72 | type ConfigAuthor struct { 73 | Name string `json:"name"` 74 | } 75 | 76 | func (h *_hugo) Initialize() { 77 | slog.Info("init hugo start") 78 | h.hugo = path.Join(AppHome, "hugo") 79 | h.SitePath = path.Join(AppHome, "site") 80 | h.articleDir = path.Join(h.SitePath, "content", "post") 81 | h.articleImgDir = path.Join(h.articleDir, "images") 82 | h.ImageDir = path.Join(h.SitePath, "static", "images") 83 | h.cnameFile = path.Join(h.SitePath, "static", "CNAME") 84 | h.themeDir = path.Join(h.SitePath, "themes") 85 | h.aboutDir = path.Join(h.SitePath, "content", AboutAid) 86 | h.aboutFile = path.Join(h.SitePath, "content", AboutAid, "index.md") 87 | h.configFile = path.Join(h.SitePath, "hugo.toml") 88 | h.PublicDir = path.Join(h.SitePath, "public") 89 | 90 | h.NewSite() 91 | 92 | h.server = &http.Server{Addr: ":1313"} 93 | http.Handle("/", http.FileServer(http.Dir(path.Join(h.SitePath, "public")))) 94 | livereload.Initialize() 95 | http.HandleFunc("/livereload.js", livereload.ServeJS) 96 | http.HandleFunc("/livereload", livereload.Handler) 97 | 98 | slog.Info("init hugo done") 99 | } 100 | 101 | func (h *_hugo) NewSite() { 102 | slog.Info("start new site") 103 | if existed, _ := util.PathExists(h.SitePath); existed { 104 | slog.Info("site existed") 105 | return 106 | } 107 | 108 | // call hugo to create site 109 | err := skeletons.CreateSite(h.SitePath, hugofs.Os, false, "toml") 110 | if err != nil { 111 | panic(fmt.Errorf("copy config fail, %w", err)) 112 | } 113 | 114 | // copy config file 115 | os.Remove(h.configFile) 116 | err = util.CopyAsset("hugo.toml", h.configFile) 117 | if err != nil { 118 | panic(fmt.Errorf("copy config fail, %w", err)) 119 | } 120 | slog.Info("copy config file") 121 | 122 | err = h.setWorkingDirConfig() 123 | if err != nil { 124 | panic(fmt.Errorf("set workingDir config fail, %w", err)) 125 | } 126 | 127 | // copy theme zip file 128 | themeCopyDstPath := path.Join(AppHome, "themes.zip") 129 | err = util.CopyAsset("themes.zip", themeCopyDstPath) 130 | if err != nil { 131 | panic(fmt.Errorf("copy themes.zip fail, %w", err)) 132 | } 133 | // unzip 134 | err = util.UnZip(themeCopyDstPath, h.SitePath) 135 | if err != nil { 136 | panic(fmt.Errorf("unzip themes file fail, %w", err)) 137 | } 138 | // remove zip 139 | os.Remove(themeCopyDstPath) 140 | slog.Info("unzip theme file") 141 | 142 | os.Mkdir(h.articleDir, os.ModePerm) 143 | os.Mkdir(h.articleImgDir, os.ModePerm) 144 | os.Mkdir(h.ImageDir, os.ModePerm) 145 | os.Create(h.cnameFile) 146 | // create about post 147 | os.Mkdir(h.aboutDir, os.ModePerm) 148 | os.Create(h.aboutFile) 149 | 150 | slog.Info("new site success") 151 | } 152 | 153 | func (h *_hugo) Build() (err error) { 154 | configs, err := allconfig.LoadConfig(allconfig.ConfigSourceDescriptor{ 155 | Fs: hugofs.Os, Filename: path.Join(h.SitePath, "hugo.toml"), 156 | }) 157 | if err != nil { 158 | slog.Error("load hugo build config fail", err) 159 | return 160 | } 161 | 162 | fs := hugofs.NewFrom(hugofs.Os, config.BaseConfig{WorkingDir: h.SitePath, PublishDir: "public"}) 163 | s, err := hugolib.NewHugoSites(deps.DepsCfg{Configs: configs, Fs: fs}) 164 | if err != nil { 165 | slog.Error("new hugo sites fail", err) 166 | return 167 | } 168 | 169 | // copy static 170 | t, err := h.getCurrentTheme() 171 | if err != nil { 172 | return errors.Wrap(err, "get current theme fail") 173 | } 174 | err = cp.Copy(path.Join(h.themeDir, t, "static"), h.PublicDir) 175 | if err != nil { 176 | return errors.Wrap(err, "copy theme static file fail") 177 | } 178 | 179 | // build 180 | err = s.Build(hugolib.BuildCfg{ErrRecovery: true}) 181 | if err != nil { 182 | slog.Error("hugo site build fail", err) 183 | return 184 | } 185 | return 186 | } 187 | 188 | func (h *_hugo) Preview() error { 189 | err := h.Build() 190 | if err != nil { 191 | return err 192 | } 193 | if h.serverRunning.Swap(true) { 194 | return nil 195 | } 196 | go func() { 197 | err := h.server.ListenAndServe() 198 | if !errors.Is(err, http.ErrServerClosed) { 199 | slog.Error("preview server fail", err) 200 | } 201 | slog.Info("preview running") 202 | }() 203 | return nil 204 | } 205 | 206 | func (h *_hugo) ClosePreview() error { 207 | if h.serverRunning.Swap(false) { 208 | slog.Info("close preview server") 209 | return h.server.Close() 210 | } 211 | return nil 212 | } 213 | 214 | func (h *_hugo) WriteArticle(aid string, meta Meta, content string) error { 215 | buf := new(bytes.Buffer) 216 | err := toml.NewEncoder(buf).Encode(meta) 217 | if err != nil { 218 | slog.Error("encode meta fail", err) 219 | return err 220 | } 221 | metaString := "+++\n" + buf.String() + "+++\n" 222 | content = metaString + content 223 | 224 | var articleF string 225 | if aid == AboutAid { 226 | // about file 227 | articleF = h.aboutFile 228 | } else { 229 | // common article file 230 | adir := path.Join(h.articleDir, aid) 231 | if e, _ := util.PathExists(adir); !e { 232 | err = os.MkdirAll(adir, os.ModePerm) 233 | if err != nil { 234 | return err 235 | } 236 | } 237 | articleF = path.Join(adir, "index.md") 238 | } 239 | 240 | err = os.WriteFile(articleF, []byte(content), os.ModePerm) 241 | if err != nil { 242 | slog.Error("write article fail", err) 243 | return err 244 | } 245 | return nil 246 | } 247 | 248 | func (h *_hugo) ReadArticle(aid string) (meta Meta, content string, err error) { 249 | var p string 250 | if aid == AboutAid { 251 | p = h.aboutFile // about file 252 | } else { 253 | p = path.Join(h.articleDir, aid, "index.md") // common article file 254 | } 255 | a, err := os.ReadFile(p) 256 | if err != nil { 257 | slog.Error("read article fail", err) 258 | return Meta{}, "", err 259 | } 260 | m, c := h.SplitMetaAndContent(string(a)) 261 | meta = Meta{} 262 | _, err = toml.Decode(m, &meta) 263 | if err != nil { 264 | slog.Error("decode meta fail when reading article", err) 265 | return Meta{}, "", err 266 | } 267 | return meta, c, nil 268 | } 269 | 270 | func (h *_hugo) DeleteArticle(aid string) error { 271 | p := path.Join(h.articleDir, aid) 272 | err := os.RemoveAll(p) 273 | if err != nil { 274 | slog.Error("remove article file fail", err) 275 | return err 276 | } 277 | return nil 278 | } 279 | 280 | func (h *_hugo) GetArticleImageDir(aid string) string { 281 | return path.Join(h.SitePath, "/static/images", aid) 282 | } 283 | 284 | func (h *_hugo) GenArticleImagePath(aid string) (localPath string, sitePath string) { 285 | filename := strconv.FormatInt(time.Now().UnixNano(), 10) + ".png" 286 | sitePath = path.Join("/static/images", aid, filename) 287 | localPath = path.Join(h.SitePath, sitePath) 288 | return localPath, sitePath 289 | } 290 | 291 | func (h *_hugo) ReadConfig() (c Config, err error) { 292 | b, err := os.ReadFile(h.configFile) 293 | if err != nil { 294 | slog.Error("read config fail", err) 295 | return Config{}, err 296 | } 297 | r := Config{} 298 | _, err = toml.Decode(string(b), &r) 299 | if err != nil { 300 | slog.Error("decode config fail", err) 301 | return Config{}, err 302 | } 303 | return r, nil 304 | } 305 | 306 | func (h *_hugo) WriteConfig(c Config) error { 307 | b, err := os.ReadFile(h.configFile) 308 | if err != nil { 309 | return err 310 | } 311 | old := make(map[string]interface{}) 312 | _, err = toml.Decode(string(b), &old) 313 | if err != nil { 314 | slog.Error("decode config fail", err) 315 | return err 316 | } 317 | 318 | old["title"] = c.Title 319 | old["description"] = c.Description 320 | old["defaultContentLanguage"] = c.DefaultContentLanguage 321 | old["theme"] = c.Theme 322 | old["copyright"] = c.Copyright 323 | oldParams := old["params"].(map[string]interface{}) 324 | oldAuthor := oldParams["author"].(map[string]interface{}) 325 | oldAuthor["name"] = c.Params.Author.Name 326 | oldParams["author"] = oldAuthor 327 | old["params"] = oldParams 328 | 329 | buf := new(bytes.Buffer) 330 | err = toml.NewEncoder(buf).Encode(old) 331 | if err != nil { 332 | slog.Error("encode config fail", err) 333 | return err 334 | } 335 | 336 | err = os.WriteFile(h.configFile, buf.Bytes(), os.ModePerm) 337 | if err != nil { 338 | slog.Error("write config fail", err) 339 | return err 340 | } 341 | 342 | return nil 343 | } 344 | 345 | func (h *_hugo) ReadConfigStr() (c []byte, err error) { 346 | c, err = os.ReadFile(h.configFile) 347 | if err != nil { 348 | slog.Error("read config fail", err) 349 | return 350 | } 351 | return 352 | } 353 | 354 | func (h *_hugo) WriteConfigStr(c []byte) (err error) { 355 | err = os.WriteFile(h.configFile, c, os.ModePerm) 356 | if err != nil { 357 | slog.Error("write config fail", err) 358 | return 359 | } 360 | return 361 | } 362 | 363 | func (h *_hugo) SplitMetaAndContent(article string) (meta string, content string) { 364 | var lines []string 365 | sc := bufio.NewScanner(strings.NewReader(article)) 366 | for sc.Scan() { 367 | lines = append(lines, sc.Text()) 368 | } 369 | if len(lines) == 0 { 370 | return "", "" 371 | } 372 | 373 | inMeta := false 374 | // the index of second +++ 375 | var secondCodeMark int 376 | for i, line := range lines { 377 | if !inMeta && strings.HasPrefix(line, "+++") { 378 | inMeta = true 379 | continue 380 | } 381 | if inMeta && strings.HasPrefix(line, "+++") { 382 | secondCodeMark = i 383 | continue 384 | } 385 | } 386 | 387 | meta = strings.Join(lines[1:secondCodeMark], "\n") 388 | content = strings.Join(lines[secondCodeMark+1:], "\n") 389 | 390 | return meta, content 391 | } 392 | 393 | func (h *_hugo) GetThemes() (themes []string, err error) { 394 | es, err := os.ReadDir(h.themeDir) 395 | if err != nil { 396 | return 397 | } 398 | for _, e := range es { 399 | themes = append(themes, e.Name()) 400 | } 401 | return 402 | } 403 | 404 | func (h *_hugo) setWorkingDirConfig() error { 405 | b, err := os.ReadFile(h.configFile) 406 | if err != nil { 407 | slog.Error("read config fail", err) 408 | return err 409 | } 410 | c := make(map[string]interface{}) 411 | _, err = toml.Decode(string(b), &c) 412 | if err != nil { 413 | slog.Error("decode config fail", err) 414 | return err 415 | } 416 | 417 | c["workingDir"] = h.SitePath 418 | 419 | buf := new(bytes.Buffer) 420 | err = toml.NewEncoder(buf).Encode(c) 421 | if err != nil { 422 | slog.Error("encode config fail", err) 423 | return err 424 | } 425 | err = os.WriteFile(h.configFile, buf.Bytes(), os.ModePerm) 426 | if err != nil { 427 | slog.Error("write config fail", err) 428 | return err 429 | } 430 | return nil 431 | } 432 | 433 | func (h *_hugo) getCurrentTheme() (string, error) { 434 | c, err := h.ReadConfig() 435 | if err != nil { 436 | return "", err 437 | } 438 | return c.Theme, nil 439 | } 440 | -------------------------------------------------------------------------------- /backend/hugo_test.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | import ( 4 | "fmt" 5 | "github.com/rangwea/swallows/backend/util" 6 | "log" 7 | "os" 8 | "testing" 9 | ) 10 | 11 | func before() { 12 | AppHome = "" 13 | if e, _ := util.PathExists(AppHome); !e { 14 | if err := os.Mkdir(AppHome, os.ModePerm); err != nil { 15 | log.Fatal("make app home dir fail", err) 16 | } 17 | } 18 | Hugo.Initialize() 19 | } 20 | 21 | func TestInit(t *testing.T) { 22 | before() 23 | } 24 | 25 | func TestBuild(t *testing.T) { 26 | before() 27 | err := Hugo.Build() 28 | if err != nil { 29 | fmt.Println(err) 30 | } 31 | } 32 | 33 | func TestPreview(t *testing.T) { 34 | before() 35 | err := Hugo.Preview() 36 | if err != nil { 37 | fmt.Println(err) 38 | } 39 | } 40 | 41 | func TestWriteArticle(t *testing.T) { 42 | before() 43 | err := Hugo.WriteArticle("1", Meta{Title: "第一篇", 44 | Tags: []string{"t1", "t2"}, 45 | Description: "描述1", 46 | Date: "2023-09-22 17:00:21", 47 | Lastmod: "2023-09-22 17:00:21", 48 | }, 49 | "哈哈哈,我的第一篇博客") 50 | fmt.Println(err) 51 | } 52 | 53 | func TestReadArticle(t *testing.T) { 54 | before() 55 | meta, content, err := Hugo.ReadArticle("1") 56 | fmt.Printf("%v\n%v\n%v\n", meta, content, err) 57 | } 58 | 59 | func TestSplitMetaAndContent(t *testing.T) { 60 | before() 61 | m, c := Hugo.SplitMetaAndContent(`+++ 62 | aaaa 63 | +++ 64 | bbbb 65 | cccc 66 | dddd 67 | `) 68 | fmt.Printf("%v;%v\n", m, c) 69 | } 70 | 71 | func TestReadConfig(t *testing.T) { 72 | before() 73 | config, err := Hugo.ReadConfig() 74 | fmt.Printf("%v\n%v\n", config, err) 75 | } 76 | 77 | func TestWriteConfig(t *testing.T) { 78 | before() 79 | config := Config{ 80 | Title: "Title", 81 | Description: "Description", 82 | Theme: "stack", 83 | Copyright: "copyright", 84 | Params: &ConfigParams{ 85 | Author: &ConfigAuthor{ 86 | Name: "wikia1", 87 | }, 88 | }, 89 | } 90 | err := Hugo.WriteConfig(config) 91 | fmt.Printf("%v\n%v\n", config, err) 92 | } 93 | -------------------------------------------------------------------------------- /backend/model.go: -------------------------------------------------------------------------------- 1 | package backend 2 | 3 | import ( 4 | "strings" 5 | "time" 6 | ) 7 | 8 | type LocalTime time.Time 9 | 10 | func (c *LocalTime) UnmarshalJSON(b []byte) error { 11 | value := strings.Trim(string(b), `"`) //get rid of " 12 | if value == "" || value == "null" { 13 | return nil 14 | } 15 | 16 | t, err := time.Parse("2006-01-02 15:04:05", value) //parse time 17 | if err != nil { 18 | return err 19 | } 20 | 21 | *c = LocalTime(t) //set result using the pointer 22 | return nil 23 | } 24 | 25 | func (c LocalTime) MarshalJSON() ([]byte, error) { 26 | return []byte(`"` + time.Time(c).Format("2006-01-02") + `"`), nil 27 | } 28 | 29 | type Article struct { 30 | Id int64 `json:"id"` 31 | Title string `json:"title"` 32 | Tags string `json:"tags"` 33 | Description string `json:"description"` 34 | CreateTime LocalTime `json:"createTime" db:"create_time"` 35 | UpdateTime LocalTime `json:"updateTime" db:"update_time"` 36 | } 37 | -------------------------------------------------------------------------------- /backend/util/utils.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "archive/zip" 5 | "crypto/md5" 6 | "fmt" 7 | "hash/crc64" 8 | "io" 9 | "os" 10 | "os/exec" 11 | "path" 12 | "path/filepath" 13 | "runtime" 14 | "strconv" 15 | "strings" 16 | 17 | "github.com/rangwea/swallows/assets" 18 | ) 19 | 20 | var commands = map[string]string{ 21 | "windows": "start", 22 | "darwin": "open", 23 | "linux": "xdg-open", 24 | } 25 | 26 | func OpenBrowser(uri string) error { 27 | run, ok := commands[runtime.GOOS] 28 | if !ok { 29 | return fmt.Errorf("don't know how to open things on %s platform", runtime.GOOS) 30 | } 31 | 32 | cmd := exec.Command(run, uri) 33 | return cmd.Start() 34 | } 35 | 36 | func PathExists(path string) (bool, error) { 37 | _, err := os.Stat(path) 38 | if err == nil { 39 | return true, nil 40 | } 41 | if os.IsNotExist(err) { 42 | return false, nil 43 | } 44 | return false, err 45 | } 46 | 47 | func CopyAsset(src string, dst string, fileModel ...os.FileMode) (err error) { 48 | hb, err := assets.Asserts.ReadFile(src) 49 | if err != nil { 50 | return 51 | } 52 | fm := os.ModePerm 53 | if fileModel != nil { 54 | fm = fileModel[0] 55 | } 56 | err = os.WriteFile(dst, hb, fm) 57 | if err != nil { 58 | return err 59 | } 60 | return nil 61 | } 62 | 63 | func CopyFile(src string, dst string, fileModel ...os.FileMode) (err error) { 64 | hb, err := os.ReadFile(src) 65 | if err != nil { 66 | return 67 | } 68 | fm := os.ModePerm 69 | if fileModel != nil { 70 | fm = fileModel[0] 71 | } 72 | err = os.WriteFile(dst, hb, fm) 73 | if err != nil { 74 | return err 75 | } 76 | return nil 77 | } 78 | 79 | func UnZip(src string, dst string) (err error) { 80 | zr, err := zip.OpenReader(src) 81 | if err != nil { 82 | return err 83 | } 84 | defer func(zr *zip.ReadCloser) { 85 | err = zr.Close() 86 | }(zr) 87 | 88 | if dst != "" { 89 | if err := os.MkdirAll(dst, 0755); err != nil { 90 | return err 91 | } 92 | } 93 | 94 | for _, file := range zr.File { 95 | p := path.Join(dst, file.Name) 96 | 97 | if file.FileInfo().IsDir() { 98 | if err := os.MkdirAll(p, file.Mode()); err != nil { 99 | return err 100 | } 101 | continue 102 | } 103 | 104 | fr, err := file.Open() 105 | if err != nil { 106 | return err 107 | } 108 | 109 | fw, err := os.OpenFile(p, os.O_CREATE|os.O_RDWR|os.O_TRUNC, file.Mode()) 110 | if err != nil { 111 | return err 112 | } 113 | 114 | _, err = io.Copy(fw, fr) 115 | if err != nil { 116 | return err 117 | } 118 | 119 | fw.Close() 120 | fr.Close() 121 | } 122 | return nil 123 | } 124 | 125 | func GetLocalFilesCRC64(base string) (r map[string]string, err error) { 126 | r = make(map[string]string) 127 | err = filepath.Walk(base, func(path string, info os.FileInfo, err error) error { 128 | if err != nil { 129 | return err 130 | } 131 | table := crc64.MakeTable(crc64.ECMA) 132 | if !info.IsDir() { 133 | file, err := os.Open(path) 134 | if err != nil { 135 | return err 136 | } 137 | defer file.Close() 138 | 139 | hash := crc64.New(table) 140 | if _, err := io.Copy(hash, file); err != nil { 141 | return err 142 | } 143 | crc64Hash := hash.Sum64() 144 | r[strings.Replace(path, base, "", -1)[1:]] = strconv.FormatUint(crc64Hash, 10) 145 | } 146 | return nil 147 | }) 148 | 149 | return 150 | } 151 | 152 | func GetLocalFilesMD5(base string) (r map[string]string, err error) { 153 | r = make(map[string]string) 154 | err = filepath.Walk(base, func(path string, info os.FileInfo, err error) error { 155 | if err != nil { 156 | return err 157 | } 158 | if !info.IsDir() { 159 | file, err := os.Open(path) 160 | if err != nil { 161 | return err 162 | } 163 | defer file.Close() 164 | 165 | hash := md5.New() 166 | if _, err := io.Copy(hash, file); err != nil { 167 | return err 168 | } 169 | md5Hash := hash.Sum(nil) 170 | r[strings.Replace(path, base, "", -1)[1:]] = string(md5Hash) 171 | } 172 | return nil 173 | }) 174 | 175 | return 176 | } 177 | -------------------------------------------------------------------------------- /backend/util/utils_test.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func TestUnZip(t *testing.T) { 8 | err := UnZip("", "") 9 | if err != nil { 10 | panic(err) 11 | } 12 | } 13 | 14 | func TestGetLocalFilesCRC64(t *testing.T) { 15 | dir := "" 16 | r, err := GetLocalFilesCRC64(dir) 17 | if err != nil { 18 | println(err) 19 | } 20 | for k, v := range r { 21 | println(k, v) 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /build/README.md: -------------------------------------------------------------------------------- 1 | # Build Directory 2 | 3 | The build directory is used to house all the build files and assets for your application. 4 | 5 | The structure is: 6 | 7 | * bin - Output directory 8 | * darwin - macOS specific files 9 | * windows - Windows specific files 10 | 11 | ## Mac 12 | 13 | The `darwin` directory holds files specific to Mac builds. 14 | These may be customised and used as part of the build. To return these files to the default state, simply delete them 15 | and 16 | build with `wails build`. 17 | 18 | The directory contains the following files: 19 | 20 | - `Info.plist` - the main plist file used for Mac builds. It is used when building using `wails build`. 21 | - `Info.dev.plist` - same as the main plist file but used when building using `wails dev`. 22 | 23 | ## Windows 24 | 25 | The `windows` directory contains the manifest and rc files used when building with `wails build`. 26 | These may be customised for your application. To return these files to the default state, simply delete them and 27 | build with `wails build`. 28 | 29 | - `icon.ico` - The icon used for the application. This is used when building using `wails build`. If you wish to 30 | use a different icon, simply replace this file with your own. If it is missing, a new `icon.ico` file 31 | will be created using the `appicon.png` file in the build directory. 32 | - `installer/*` - The files used to create the Windows installer. These are used when building using `wails build`. 33 | - `info.json` - Application details used for Windows builds. The data here will be used by the Windows installer, 34 | as well as the application itself (right click the exe -> properties -> details) 35 | - `wails.exe.manifest` - The main application manifest file. -------------------------------------------------------------------------------- /build/appicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rangwea/swallow/2d3dca6ed2d84d13d8a48c97c873d71adebb02f1/build/appicon.png -------------------------------------------------------------------------------- /build/darwin/Info.dev.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CFBundlePackageType 5 | APPL 6 | CFBundleName 7 | {{.Info.ProductName}} 8 | CFBundleExecutable 9 | {{.Name}} 10 | CFBundleIdentifier 11 | com.wails.{{.Name}} 12 | CFBundleVersion 13 | {{.Info.ProductVersion}} 14 | CFBundleGetInfoString 15 | {{.Info.Comments}} 16 | CFBundleShortVersionString 17 | {{.Info.ProductVersion}} 18 | CFBundleIconFile 19 | iconfile 20 | LSMinimumSystemVersion 21 | 10.13.0 22 | NSHighResolutionCapable 23 | true 24 | NSHumanReadableCopyright 25 | {{.Info.Copyright}} 26 | NSAppTransportSecurity 27 | 28 | NSAllowsLocalNetworking 29 | 30 | 31 | 32 | -------------------------------------------------------------------------------- /build/darwin/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | CFBundlePackageType 5 | APPL 6 | CFBundleName 7 | {{.Info.ProductName}} 8 | CFBundleExecutable 9 | {{.Name}} 10 | CFBundleIdentifier 11 | com.wails.{{.Name}} 12 | CFBundleVersion 13 | {{.Info.ProductVersion}} 14 | CFBundleGetInfoString 15 | {{.Info.Comments}} 16 | CFBundleShortVersionString 17 | {{.Info.ProductVersion}} 18 | CFBundleIconFile 19 | iconfile 20 | LSMinimumSystemVersion 21 | 10.13.0 22 | NSHighResolutionCapable 23 | true 24 | NSHumanReadableCopyright 25 | {{.Info.Copyright}} 26 | 27 | -------------------------------------------------------------------------------- /build/windows/info.json: -------------------------------------------------------------------------------- 1 | { 2 | "fixed": { 3 | "file_version": "{{.Info.ProductVersion}}" 4 | }, 5 | "info": { 6 | "0000": { 7 | "ProductVersion": "{{.Info.ProductVersion}}", 8 | "CompanyName": "{{.Info.CompanyName}}", 9 | "FileDescription": "{{.Info.ProductName}}", 10 | "LegalCopyright": "{{.Info.Copyright}}", 11 | "ProductName": "{{.Info.ProductName}}", 12 | "Comments": "{{.Info.Comments}}" 13 | } 14 | } 15 | } -------------------------------------------------------------------------------- /build/windows/installer/project.nsi: -------------------------------------------------------------------------------- 1 | Unicode true 2 | 3 | #### 4 | ## Please note: Template replacements don't work in this file. They are provided with default defines like 5 | ## mentioned underneath. 6 | ## If the keyword is not defined, "wails_tools.nsh" will populate them with the values from ProjectInfo. 7 | ## If they are defined here, "wails_tools.nsh" will not touch them. This allows to use this project.nsi manually 8 | ## from outside of Wails for debugging and development of the installer. 9 | ## 10 | ## For development first make a wails nsis build to populate the "wails_tools.nsh": 11 | ## > wails build --target windows/amd64 --nsis 12 | ## Then you can call makensis on this file with specifying the path to your binary: 13 | ## For a AMD64 only installer: 14 | ## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app.exe 15 | ## For a ARM64 only installer: 16 | ## > makensis -DARG_WAILS_ARM64_BINARY=..\..\bin\app.exe 17 | ## For a installer with both architectures: 18 | ## > makensis -DARG_WAILS_AMD64_BINARY=..\..\bin\app-amd64.exe -DARG_WAILS_ARM64_BINARY=..\..\bin\app-arm64.exe 19 | #### 20 | ## The following information is taken from the ProjectInfo file, but they can be overwritten here. 21 | #### 22 | ## !define INFO_PROJECTNAME "MyProject" # Default "{{.Name}}" 23 | ## !define INFO_COMPANYNAME "MyCompany" # Default "{{.Info.CompanyName}}" 24 | ## !define INFO_PRODUCTNAME "MyProduct" # Default "{{.Info.ProductName}}" 25 | ## !define INFO_PRODUCTVERSION "1.0.0" # Default "{{.Info.ProductVersion}}" 26 | ## !define INFO_COPYRIGHT "Copyright" # Default "{{.Info.Copyright}}" 27 | ### 28 | ## !define PRODUCT_EXECUTABLE "Application.exe" # Default "${INFO_PROJECTNAME}.exe" 29 | ## !define UNINST_KEY_NAME "UninstKeyInRegistry" # Default "${INFO_COMPANYNAME}${INFO_PRODUCTNAME}" 30 | #### 31 | ## !define REQUEST_EXECUTION_LEVEL "admin" # Default "admin" see also https://nsis.sourceforge.io/Docs/Chapter4.html 32 | #### 33 | ## Include the wails tools 34 | #### 35 | !include "wails_tools.nsh" 36 | 37 | # The version information for this two must consist of 4 parts 38 | VIProductVersion "${INFO_PRODUCTVERSION}.0" 39 | VIFileVersion "${INFO_PRODUCTVERSION}.0" 40 | 41 | VIAddVersionKey "CompanyName" "${INFO_COMPANYNAME}" 42 | VIAddVersionKey "FileDescription" "${INFO_PRODUCTNAME} Installer" 43 | VIAddVersionKey "ProductVersion" "${INFO_PRODUCTVERSION}" 44 | VIAddVersionKey "FileVersion" "${INFO_PRODUCTVERSION}" 45 | VIAddVersionKey "LegalCopyright" "${INFO_COPYRIGHT}" 46 | VIAddVersionKey "ProductName" "${INFO_PRODUCTNAME}" 47 | 48 | !include "MUI.nsh" 49 | 50 | !define MUI_ICON "..\icon.ico" 51 | !define MUI_UNICON "..\icon.ico" 52 | # !define MUI_WELCOMEFINISHPAGE_BITMAP "resources\leftimage.bmp" #Include this to add a bitmap on the left side of the Welcome Page. Must be a size of 164x314 53 | !define MUI_FINISHPAGE_NOAUTOCLOSE # Wait on the INSTFILES page so the user can take a look into the details of the installation steps 54 | !define MUI_ABORTWARNING # This will warn the user if they exit from the installer. 55 | 56 | !insertmacro MUI_PAGE_WELCOME # Welcome to the installer page. 57 | # !insertmacro MUI_PAGE_LICENSE "resources\eula.txt" # Adds a EULA page to the installer 58 | !insertmacro MUI_PAGE_DIRECTORY # In which folder install page. 59 | !insertmacro MUI_PAGE_INSTFILES # Installing page. 60 | !insertmacro MUI_PAGE_FINISH # Finished installation page. 61 | 62 | !insertmacro MUI_UNPAGE_INSTFILES # Uinstalling page 63 | 64 | !insertmacro MUI_LANGUAGE "English" # Set the Language of the installer 65 | 66 | ## The following two statements can be used to sign the installer and the uninstaller. The path to the binaries are provided in %1 67 | #!uninstfinalize 'signtool --file "%1"' 68 | #!finalize 'signtool --file "%1"' 69 | 70 | Name "${INFO_PRODUCTNAME}" 71 | OutFile "..\..\bin\${INFO_PROJECTNAME}-${ARCH}-installer.exe" # Name of the installer's file. 72 | InstallDir "$PROGRAMFILES64\${INFO_COMPANYNAME}\${INFO_PRODUCTNAME}" # Default installing folder ($PROGRAMFILES is Program Files folder). 73 | ShowInstDetails show # This will always show the installation details. 74 | 75 | Function .onInit 76 | !insertmacro wails.checkArchitecture 77 | FunctionEnd 78 | 79 | Section 80 | !insertmacro wails.setShellContext 81 | 82 | !insertmacro wails.webview2runtime 83 | 84 | SetOutPath $INSTDIR 85 | 86 | !insertmacro wails.files 87 | 88 | CreateShortcut "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}" 89 | CreateShortCut "$DESKTOP\${INFO_PRODUCTNAME}.lnk" "$INSTDIR\${PRODUCT_EXECUTABLE}" 90 | 91 | !insertmacro wails.writeUninstaller 92 | SectionEnd 93 | 94 | Section "uninstall" 95 | !insertmacro wails.setShellContext 96 | 97 | RMDir /r "$AppData\${PRODUCT_EXECUTABLE}" # Remove the WebView2 DataPath 98 | 99 | RMDir /r $INSTDIR 100 | 101 | Delete "$SMPROGRAMS\${INFO_PRODUCTNAME}.lnk" 102 | Delete "$DESKTOP\${INFO_PRODUCTNAME}.lnk" 103 | 104 | !insertmacro wails.deleteUninstaller 105 | SectionEnd 106 | -------------------------------------------------------------------------------- /build/windows/installer/wails_tools.nsh: -------------------------------------------------------------------------------- 1 | # DO NOT EDIT - Generated automatically by `wails build` 2 | 3 | !include "x64.nsh" 4 | !include "WinVer.nsh" 5 | !include "FileFunc.nsh" 6 | 7 | !ifndef INFO_PROJECTNAME 8 | !define INFO_PROJECTNAME "{{.Name}}" 9 | !endif 10 | !ifndef INFO_COMPANYNAME 11 | !define INFO_COMPANYNAME "{{.Info.CompanyName}}" 12 | !endif 13 | !ifndef INFO_PRODUCTNAME 14 | !define INFO_PRODUCTNAME "{{.Info.ProductName}}" 15 | !endif 16 | !ifndef INFO_PRODUCTVERSION 17 | !define INFO_PRODUCTVERSION "{{.Info.ProductVersion}}" 18 | !endif 19 | !ifndef INFO_COPYRIGHT 20 | !define INFO_COPYRIGHT "{{.Info.Copyright}}" 21 | !endif 22 | !ifndef PRODUCT_EXECUTABLE 23 | !define PRODUCT_EXECUTABLE "${INFO_PROJECTNAME}.exe" 24 | !endif 25 | !ifndef UNINST_KEY_NAME 26 | !define UNINST_KEY_NAME "${INFO_COMPANYNAME}${INFO_PRODUCTNAME}" 27 | !endif 28 | !define UNINST_KEY "Software\Microsoft\Windows\CurrentVersion\Uninstall\${UNINST_KEY_NAME}" 29 | 30 | !ifndef REQUEST_EXECUTION_LEVEL 31 | !define REQUEST_EXECUTION_LEVEL "admin" 32 | !endif 33 | 34 | RequestExecutionLevel "${REQUEST_EXECUTION_LEVEL}" 35 | 36 | !ifdef ARG_WAILS_AMD64_BINARY 37 | !define SUPPORTS_AMD64 38 | !endif 39 | 40 | !ifdef ARG_WAILS_ARM64_BINARY 41 | !define SUPPORTS_ARM64 42 | !endif 43 | 44 | !ifdef SUPPORTS_AMD64 45 | !ifdef SUPPORTS_ARM64 46 | !define ARCH "amd64_arm64" 47 | !else 48 | !define ARCH "amd64" 49 | !endif 50 | !else 51 | !ifdef SUPPORTS_ARM64 52 | !define ARCH "arm64" 53 | !else 54 | !error "Wails: Undefined ARCH, please provide at least one of ARG_WAILS_AMD64_BINARY or ARG_WAILS_ARM64_BINARY" 55 | !endif 56 | !endif 57 | 58 | !macro wails.checkArchitecture 59 | !ifndef WAILS_WIN10_REQUIRED 60 | !define WAILS_WIN10_REQUIRED "This product is only supported on Windows 10 (Server 2016) and later." 61 | !endif 62 | 63 | !ifndef WAILS_ARCHITECTURE_NOT_SUPPORTED 64 | !define WAILS_ARCHITECTURE_NOT_SUPPORTED "This product can't be installed on the current Windows architecture. Supports: ${ARCH}" 65 | !endif 66 | 67 | ${If} ${AtLeastWin10} 68 | !ifdef SUPPORTS_AMD64 69 | ${if} ${IsNativeAMD64} 70 | Goto ok 71 | ${EndIf} 72 | !endif 73 | 74 | !ifdef SUPPORTS_ARM64 75 | ${if} ${IsNativeARM64} 76 | Goto ok 77 | ${EndIf} 78 | !endif 79 | 80 | IfSilent silentArch notSilentArch 81 | silentArch: 82 | SetErrorLevel 65 83 | Abort 84 | notSilentArch: 85 | MessageBox MB_OK "${WAILS_ARCHITECTURE_NOT_SUPPORTED}" 86 | Quit 87 | ${else} 88 | IfSilent silentWin notSilentWin 89 | silentWin: 90 | SetErrorLevel 64 91 | Abort 92 | notSilentWin: 93 | MessageBox MB_OK "${WAILS_WIN10_REQUIRED}" 94 | Quit 95 | ${EndIf} 96 | 97 | ok: 98 | !macroend 99 | 100 | !macro wails.files 101 | !ifdef SUPPORTS_AMD64 102 | ${if} ${IsNativeAMD64} 103 | File "/oname=${PRODUCT_EXECUTABLE}" "${ARG_WAILS_AMD64_BINARY}" 104 | ${EndIf} 105 | !endif 106 | 107 | !ifdef SUPPORTS_ARM64 108 | ${if} ${IsNativeARM64} 109 | File "/oname=${PRODUCT_EXECUTABLE}" "${ARG_WAILS_ARM64_BINARY}" 110 | ${EndIf} 111 | !endif 112 | !macroend 113 | 114 | !macro wails.writeUninstaller 115 | WriteUninstaller "$INSTDIR\uninstall.exe" 116 | 117 | SetRegView 64 118 | WriteRegStr HKLM "${UNINST_KEY}" "Publisher" "${INFO_COMPANYNAME}" 119 | WriteRegStr HKLM "${UNINST_KEY}" "DisplayName" "${INFO_PRODUCTNAME}" 120 | WriteRegStr HKLM "${UNINST_KEY}" "DisplayVersion" "${INFO_PRODUCTVERSION}" 121 | WriteRegStr HKLM "${UNINST_KEY}" "DisplayIcon" "$INSTDIR\${PRODUCT_EXECUTABLE}" 122 | WriteRegStr HKLM "${UNINST_KEY}" "UninstallString" "$\"$INSTDIR\uninstall.exe$\"" 123 | WriteRegStr HKLM "${UNINST_KEY}" "QuietUninstallString" "$\"$INSTDIR\uninstall.exe$\" /S" 124 | 125 | ${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2 126 | IntFmt $0 "0x%08X" $0 127 | WriteRegDWORD HKLM "${UNINST_KEY}" "EstimatedSize" "$0" 128 | !macroend 129 | 130 | !macro wails.deleteUninstaller 131 | Delete "$INSTDIR\uninstall.exe" 132 | 133 | SetRegView 64 134 | DeleteRegKey HKLM "${UNINST_KEY}" 135 | !macroend 136 | 137 | !macro wails.setShellContext 138 | ${If} ${REQUEST_EXECUTION_LEVEL} == "admin" 139 | SetShellVarContext all 140 | ${else} 141 | SetShellVarContext current 142 | ${EndIf} 143 | !macroend 144 | 145 | # Install webview2 by launching the bootstrapper 146 | # See https://docs.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution#online-only-deployment 147 | !macro wails.webview2runtime 148 | !ifndef WAILS_INSTALL_WEBVIEW_DETAILPRINT 149 | !define WAILS_INSTALL_WEBVIEW_DETAILPRINT "Installing: WebView2 Runtime" 150 | !endif 151 | 152 | SetRegView 64 153 | # If the admin key exists and is not empty then webview2 is already installed 154 | ReadRegStr $0 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" "pv" 155 | ${If} $0 != "" 156 | Goto ok 157 | ${EndIf} 158 | 159 | ${If} ${REQUEST_EXECUTION_LEVEL} == "user" 160 | # If the installer is run in user level, check the user specific key exists and is not empty then webview2 is already installed 161 | ReadRegStr $0 HKCU "Software\Microsoft\EdgeUpdate\Clients{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" "pv" 162 | ${If} $0 != "" 163 | Goto ok 164 | ${EndIf} 165 | ${EndIf} 166 | 167 | SetDetailsPrint both 168 | DetailPrint "${WAILS_INSTALL_WEBVIEW_DETAILPRINT}" 169 | SetDetailsPrint listonly 170 | 171 | InitPluginsDir 172 | CreateDirectory "$pluginsdir\webview2bootstrapper" 173 | SetOutPath "$pluginsdir\webview2bootstrapper" 174 | File "tmp\MicrosoftEdgeWebview2Setup.exe" 175 | ExecWait '"$pluginsdir\webview2bootstrapper\MicrosoftEdgeWebview2Setup.exe" /silent /install' 176 | 177 | SetDetailsPrint both 178 | ok: 179 | !macroend -------------------------------------------------------------------------------- /build/windows/wails.exe.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | true/pm 12 | permonitorv2,permonitor 13 | 14 | 15 | -------------------------------------------------------------------------------- /doc/deploy/cos.md: -------------------------------------------------------------------------------- 1 | # COS 2 | 3 | 对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。 4 | 5 | **[地址](https://console.cloud.tencent.com/cos)** 6 | 7 | ## 创建 8 | 9 | ## 创建密钥 10 | 11 | https://console.cloud.tencent.com/cam/capi -------------------------------------------------------------------------------- /doc/images/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rangwea/swallow/2d3dca6ed2d84d13d8a48c97c873d71adebb02f1/doc/images/1.png -------------------------------------------------------------------------------- /doc/images/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rangwea/swallow/2d3dca6ed2d84d13d8a48c97c873d71adebb02f1/doc/images/2.png -------------------------------------------------------------------------------- /doc/images/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rangwea/swallow/2d3dca6ed2d84d13d8a48c97c873d71adebb02f1/doc/images/3.png -------------------------------------------------------------------------------- /frontend/README.md: -------------------------------------------------------------------------------- 1 | # React + Vite 2 | 3 | This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. 4 | 5 | Currently, two official plugins are available: 6 | 7 | - [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh 8 | - [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh 9 | -------------------------------------------------------------------------------- /frontend/components.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://ui.shadcn.com/schema.json", 3 | "style": "default", 4 | "rsc": false, 5 | "tsx": false, 6 | "tailwind": { 7 | "config": "tailwind.config.js", 8 | "css": "src/index.css", 9 | "baseColor": "slate", 10 | "cssVariables": true, 11 | "prefix": "" 12 | }, 13 | "aliases": { 14 | "components": "@/components", 15 | "utils": "@/lib/utils" 16 | } 17 | } -------------------------------------------------------------------------------- /frontend/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Vite + React 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /frontend/jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es6", 4 | "module": "commonjs", 5 | "baseUrl": ".", 6 | "paths": { 7 | "@/*": ["src/*"] 8 | } 9 | }, 10 | "exclude": ["node_modules"] 11 | } -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "shadcnj", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vite build", 9 | "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0", 10 | "preview": "vite preview" 11 | }, 12 | "dependencies": { 13 | "@hookform/resolvers": "^3.9.0", 14 | "@radix-ui/react-checkbox": "^1.1.1", 15 | "@radix-ui/react-dialog": "^1.1.1", 16 | "@radix-ui/react-label": "^2.1.0", 17 | "@radix-ui/react-select": "^2.1.1", 18 | "@radix-ui/react-separator": "^1.1.0", 19 | "@radix-ui/react-slot": "^1.1.0", 20 | "@radix-ui/react-tabs": "^1.1.0", 21 | "@radix-ui/react-toast": "^1.2.1", 22 | "@tanstack/react-table": "^8.19.2", 23 | "@uiw/react-md-editor": "^4.0.4", 24 | "class-variance-authority": "^0.7.0", 25 | "clsx": "^2.1.1", 26 | "emblor": "^1.3.6", 27 | "lucide-react": "^0.400.0", 28 | "next-themes": "^0.3.0", 29 | "react": "^18.3.1", 30 | "react-dom": "^18.3.1", 31 | "react-hook-form": "^7.52.1", 32 | "react-router-dom": "^6.24.1", 33 | "sonner": "^1.5.0", 34 | "tailwind-merge": "^2.3.0", 35 | "tailwindcss-animate": "^1.0.7", 36 | "vaul": "^0.9.1", 37 | "zod": "^3.23.8" 38 | }, 39 | "devDependencies": { 40 | "@types/node": "^20.14.9", 41 | "@types/react": "^18.3.3", 42 | "@types/react-dom": "^18.3.0", 43 | "@vitejs/plugin-react": "^4.3.1", 44 | "autoprefixer": "^10.4.19", 45 | "eslint": "^8.57.0", 46 | "eslint-plugin-react": "^7.34.2", 47 | "eslint-plugin-react-hooks": "^4.6.2", 48 | "eslint-plugin-react-refresh": "^0.4.7", 49 | "postcss": "^8.4.39", 50 | "tailwindcss": "^3.4.4", 51 | "vite": "^5.3.3" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /frontend/package.json.md5: -------------------------------------------------------------------------------- 1 | 6f89025ffb2b97595f8cfce7484abfa5 -------------------------------------------------------------------------------- /frontend/postcss.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | } 7 | -------------------------------------------------------------------------------- /frontend/src/assets/react.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /frontend/src/components/page/editor/page.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState, forwardRef } from "react"; 2 | import { Link, useSearchParams } from "react-router-dom"; 3 | import { icons, Check, MoveLeft } from "lucide-react"; 4 | import { Button } from "@/components/ui/button"; 5 | import { Separator } from "@/components/ui/separator"; 6 | import { Input } from "@/components/ui/input"; 7 | import MDEditor from "@uiw/react-md-editor"; 8 | import { 9 | ArticleSave, 10 | ArticleGet, 11 | ArticleInsertImage, 12 | ArticleInsertImageBlob, 13 | } from "/wailsjs/go/backend/App"; 14 | import "../style.css"; 15 | import { 16 | Sheet, 17 | SheetContent, 18 | SheetDescription, 19 | SheetHeader, 20 | SheetTitle, 21 | SheetTrigger, 22 | } from "@/components/ui/sheet" 23 | import { 24 | Form, 25 | FormControl, 26 | FormField, 27 | FormItem, 28 | FormLabel, 29 | } from "@/components/ui/form"; 30 | import { useForm } from "react-hook-form"; 31 | import { TagInput } from "emblor"; 32 | import { Toaster } from "@/components/ui/sonner"; 33 | import { getCurrentTime, isSuccess } from "@/components/page/util"; 34 | 35 | function EditorPage() { 36 | const [params] = useSearchParams(); 37 | const [id, setId] = useState(params.get("id")); 38 | 39 | // article vars 40 | const [title, setTitle] = useState(); // title 41 | const [content, setContent] = useState(""); // content 42 | 43 | // preview button vars 44 | const [preview, setPreview] = useState("edit"); 45 | const [previewIcon, setPreviewIcon] = useState("Eye"); 46 | 47 | const mdTextAreaId = "mdTextArea"; 48 | 49 | const [changed, setChanged] = useState(false); 50 | 51 | const form = useForm(); 52 | 53 | const [tags, setTags] = React.useState([]); 54 | const [activeTagIndex, setActiveTagIndex] = useState(null); 55 | 56 | useEffect(() => { 57 | init(); 58 | }, []); 59 | 60 | function init() { 61 | if (id) { 62 | // existed id,edit 63 | ArticleGet(id).then((result) => { 64 | if (!isSuccess(result)) { 65 | return; 66 | } 67 | let meta = result.data.meta; 68 | setTitle(meta.title); 69 | setContent(result.data.content); 70 | if (meta.tags) { 71 | form.setValue( 72 | "tags", 73 | meta.tags.map((e) => { 74 | text: e; 75 | }) 76 | ); 77 | } 78 | form.setValue("date", meta.date); 79 | form.setValue("lastmod", meta.lastmod); 80 | }); 81 | } else { 82 | let curDate = getCurrentTime(); 83 | form.setValue("date", curDate); 84 | form.setValue("lastmod", curDate); 85 | } 86 | } 87 | 88 | function save(e) { 89 | let meta = getMeta(); 90 | ArticleSave(id, meta, content).then((r) => { 91 | if (isSuccess(r)) { 92 | setId(r.data); 93 | setChanged(false); 94 | } 95 | }); 96 | } 97 | 98 | function getMeta() { 99 | let meta = form.getValues(); 100 | meta["title"] = title; 101 | if (meta["tags"]) { 102 | meta["tags"] = meta["tags"].map((e) => e.text); 103 | } 104 | return meta; 105 | } 106 | 107 | function insertImage() { 108 | ArticleInsertImage(id).then((r) => { 109 | insertImageTextToArea(r); 110 | }); 111 | } 112 | 113 | function insertImageTextToArea(r) { 114 | if (isSuccess(r)) { 115 | const md = insertToTextArea(`![](${r.data})\n`); 116 | setContent(md); 117 | } 118 | } 119 | 120 | function contentChange(c) { 121 | setChanged(true); 122 | setContent(c); 123 | } 124 | 125 | function previewToggle() { 126 | if (preview === "edit") { 127 | setPreview("preview"); 128 | setPreviewIcon("FilePenLine"); 129 | } else { 130 | setPreview("edit"); 131 | setPreviewIcon("Eye"); 132 | } 133 | } 134 | 135 | function insertToTextArea(insertString) { 136 | const textarea = document.getElementById(mdTextAreaId); 137 | if (!textarea) { 138 | return null; 139 | } 140 | 141 | let sentence = textarea.value; 142 | const len = sentence.length; 143 | const pos = textarea.selectionStart; 144 | const end = textarea.selectionEnd; 145 | 146 | const front = sentence.slice(0, pos); 147 | const back = sentence.slice(pos, len); 148 | 149 | sentence = front + insertString + back; 150 | 151 | textarea.value = sentence; 152 | textarea.selectionEnd = end + insertString.length; 153 | 154 | return sentence; 155 | } 156 | 157 | function onImagePasted(dataTransfer) { 158 | const file = dataTransfer.files.item(0); 159 | Promise.resolve(file.arrayBuffer()).then((ab) => { 160 | const u = new Uint8Array(ab); 161 | ArticleInsertImageBlob(id, `[${u.toString()}]`).then((r) => { 162 | insertImageTextToArea(r); 163 | }); 164 | }); 165 | } 166 | 167 | function titleChange(e) { 168 | setChanged(true); 169 | setTitle(e.target.value); 170 | } 171 | 172 | function metaChange() { 173 | setChanged(true); 174 | } 175 | 176 | const ToolBtn = forwardRef((props, ref) => { 177 | const {icon, onClick} = props 178 | const LucideIcon = icons[icon]; 179 | return ( 180 | 183 | ); 184 | }); 185 | 186 | return ( 187 | 188 |
189 | 190 |
194 | 195 | 198 | 199 | 207 |
208 |
209 |
210 | 216 | { 220 | if (e.clipboardData.files.length > 0) { 221 | e.preventDefault(); 222 | onImagePasted(e.clipboardData); 223 | } 224 | }} 225 | onDrop={(e) => { 226 | e.preventDefault(); 227 | onImagePasted(e.dataTransfer); 228 | }} 229 | style={{ 230 | marginTop: 3, 231 | marginBottom: 10, 232 | border: "none", 233 | }} 234 | hideToolbar={true} 235 | height="calc(100vh - 100px)" 236 | preview={preview} 237 | textareaProps={{ 238 | id: mdTextAreaId, 239 | placeholder: "Write you text", 240 | }} 241 | /> 242 |
243 |
244 | 245 | 246 | 247 | 248 | 249 |
250 |
251 | 252 | 253 | 254 | Article Meta 255 | 256 | 257 |
258 | 259 | ( 263 | 264 | Tags 265 | 266 | { 271 | setTags(newTags); 272 | form.setValue("tags", newTags); 273 | }} 274 | activeTagIndex={activeTagIndex} 275 | setActiveTagIndex={setActiveTagIndex} 276 | size={"md"} 277 | animation={"fadeIn"} 278 | styleClasses={{ 279 | input: "h-10", 280 | inlineTagsContainer: "pl-1", 281 | }} 282 | /> 283 | 284 | 285 | )} 286 | > 287 | ( 291 | 292 | Date 293 | 294 | 295 | 296 | 297 | )} 298 | > 299 | ( 303 | 304 | Lastmod 305 | 306 | 307 | 308 | 309 | )} 310 | > 311 |
312 | 313 |
314 |
315 |
316 | ); 317 | } 318 | 319 | export default EditorPage; 320 | -------------------------------------------------------------------------------- /frontend/src/components/page/home.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | import { Button } from "@/components/ui/button"; 3 | import { Input } from "@/components/ui/input"; 4 | import { Checkbox } from "@/components/ui/checkbox"; 5 | import { Toaster } from "@/components/ui/sonner"; 6 | import { toast } from "sonner"; 7 | import { 8 | icons, 9 | ChevronsLeft, 10 | ChevronLeft, 11 | ChevronRight, 12 | ChevronsRight, 13 | Trash2, 14 | } from "lucide-react"; 15 | import { Link, useNavigate } from "react-router-dom"; 16 | import { 17 | ArticleList, 18 | ArticleRemove, 19 | SitePreview, 20 | SiteDeploy, 21 | } from "/wailsjs/go/backend/App"; 22 | import { isSuccess, checkError, checkResult } from "@/components/page/util"; 23 | 24 | function Home() { 25 | const [articles, setArticles] = useState([]); 26 | const [checked, setChecked] = useState([]); 27 | const [deleteBtnShow, setDeleteBtnShow] = useState(false); 28 | const [total, setTotal] = useState(0); 29 | const [page, setPage] = useState(0); 30 | const [search, setSearch] = useState(""); 31 | const navigate = useNavigate(); 32 | 33 | function enterSearch(e) { 34 | if (e.key === "Enter") { 35 | doSearch(); 36 | } 37 | } 38 | 39 | function doSearch() { 40 | ArticleList(search, page).then((r) => { 41 | if (isSuccess(r)) { 42 | setTotal(r.data.total); 43 | setArticles(r.data.list); 44 | } 45 | }); 46 | } 47 | 48 | useEffect(() => { 49 | doSearch(); 50 | }, []); 51 | 52 | useEffect(() => { 53 | doSearch(); 54 | }, [page]); 55 | 56 | function preview() { 57 | SitePreview().then(checkError); 58 | } 59 | 60 | function deploy() { 61 | SiteDeploy().then((r) => checkResult(r, "deploy success")); 62 | } 63 | 64 | function removeArticle() { 65 | if (checked.length > 0) { 66 | ArticleRemove(checked).then((r) => { 67 | if (isSuccess(r)) { 68 | toast.info(`removed ${checked.length} articles`, 2); 69 | doSearch(); 70 | setChecked([]); 71 | setDeleteBtnShow(false); 72 | } 73 | }); 74 | } 75 | } 76 | 77 | function checkedChange(e, id) { 78 | let n = []; 79 | if (e) { 80 | n = [...checked, id]; 81 | } else { 82 | n = checked.filter((v) => v !== id); 83 | } 84 | setDeleteBtnShow(n.length > 0); 85 | setChecked(n); 86 | } 87 | 88 | function pageSearch(type) { 89 | if (type === "first" && page > 0) { 90 | setPage(0); 91 | } else if (type === "prev" && page > 0) { 92 | setPage(page - 1); 93 | } else if (type === "next" && page < calPage()) { 94 | setPage(page + 1); 95 | } else if (type === "last" && page < calPage()) { 96 | setPage(calPage()); 97 | } 98 | } 99 | 100 | function calPage() { 101 | return Math.ceil(total / 10) - 1; 102 | } 103 | 104 | const IBtn = ({ icon, onClick }) => { 105 | const LucideIcon = icons[icon]; 106 | return ( 107 | 115 | ); 116 | }; 117 | 118 | return ( 119 | <> 120 | 121 |
122 | {/* header */} 123 |
127 |
128 |
129 | setSearch(e.target.value)} 134 | /> 135 | {deleteBtnShow ? ( 136 | 144 | ) : null} 145 |
146 |
147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 |
156 |
157 | {/* header */} 158 | 159 | {/* body */} 160 |
161 | {articles.map((item) => ( 162 |
navigate("/editor?id=" + item.id)} 165 | key={item.id} 166 | > 167 |
e.stopPropagation()}> 168 | checkedChange(e, item.id + "")} 170 | /> 171 |
172 |
173 | {item.title} 174 |
175 |
176 | {item.tags} 177 |
178 |
179 | {item.createTime} 180 |
181 |
182 | ))} 183 |
184 | {/* body */} 185 | 186 | {/* footer */} 187 |
188 |
189 | Total {total} 190 |
191 |
192 | 200 | 208 | 216 | 224 |
225 |
226 |
227 | {/* footer */} 228 |
229 | 230 | ); 231 | } 232 | 233 | export default Home; 234 | -------------------------------------------------------------------------------- /frontend/src/components/page/settings/app.jsx: -------------------------------------------------------------------------------- 1 | import { Link, useNavigate } from "react-router-dom"; 2 | import { Button } from "@/components/ui/button"; 3 | import { Toaster } from "@/components/ui/sonner" 4 | import { toast } from "sonner" 5 | 6 | function AppSetting() { 7 | const click = () => { 8 | console.log("aaa") 9 | toast("hhhhh") 10 | } 11 | 12 | return ( 13 | <> 14 |
15 | 16 | 17 |
18 | 19 | ); 20 | } 21 | 22 | export default AppSetting; 23 | -------------------------------------------------------------------------------- /frontend/src/components/page/settings/deploy/cos.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from "react"; 2 | import { Button } from "@/components/ui/button"; 3 | import { Separator } from "@/components/ui/separator"; 4 | import { useForm } from "react-hook-form"; 5 | import { 6 | Form, 7 | FormControl, 8 | FormDescription, 9 | FormField, 10 | FormItem, 11 | FormLabel, 12 | FormMessage, 13 | } from "@/components/ui/form"; 14 | import { Input } from "@/components/ui/input"; 15 | import { ConfSave, ConfGet } from "/wailsjs/go/backend/App"; 16 | import { checkResult, isSuccess } from "@/components/page/util"; 17 | 18 | function CosSetting() { 19 | const form = useForm(); 20 | 21 | const confType = "cos"; 22 | 23 | useEffect(() => { 24 | init(); 25 | }, []); 26 | 27 | function init() { 28 | // init form 29 | ConfGet(confType).then((result) => { 30 | if (isSuccess(result)) { 31 | const data = result.data; 32 | for (var k in data) { 33 | form.setValue(k, data[k]); 34 | } 35 | } 36 | }); 37 | } 38 | 39 | function onSubmit(values) { 40 | ConfSave(confType, JSON.stringify(values)).then((r) => 41 | checkResult(r, "save config success") 42 | ); 43 | } 44 | 45 | return ( 46 |
47 |
48 |

Account

49 |

Deploy site with cos.

50 |
51 | 52 |
53 | 54 | ( 58 | 59 | SecretId 60 | 61 | 62 | 63 | Your SecretId for cos 64 | 65 | 66 | )} 67 | > 68 | ( 72 | 73 | SecretKey 74 | 75 | 76 | 77 | Your SecretKey for cos 78 | 79 | 80 | )} 81 | > 82 | ( 86 | 87 | Region 88 | 89 | 90 | 91 | Your Region for cos 92 | 93 | 94 | )} 95 | > 96 | ( 100 | 101 | Bucket 102 | 103 | 104 | 105 | Your Bucket for cos 106 | 107 | 108 | )} 109 | > 110 | 111 |
112 | 113 |
114 | ); 115 | } 116 | 117 | export default CosSetting; 118 | -------------------------------------------------------------------------------- /frontend/src/components/page/settings/deploy/git.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from "react"; 2 | import { Button } from "@/components/ui/button"; 3 | import { Separator } from "@/components/ui/separator"; 4 | import { useForm } from "react-hook-form"; 5 | import { 6 | Form, 7 | FormControl, 8 | FormDescription, 9 | FormField, 10 | FormItem, 11 | FormLabel, 12 | FormMessage, 13 | } from "@/components/ui/form"; 14 | import { Input } from "@/components/ui/input"; 15 | import { ConfSave, ConfGet } from "/wailsjs/go/backend/App"; 16 | import { checkResult, isSuccess } from "@/components/page/util"; 17 | 18 | function GitSetting() { 19 | const form = useForm(); 20 | 21 | const confType = "github"; 22 | 23 | useEffect(() => { 24 | init(); 25 | }, []); 26 | 27 | function init() { 28 | // init form 29 | ConfGet(confType).then((result) => { 30 | if (isSuccess(result)) { 31 | const data = result.data; 32 | for (var k in data) { 33 | form.setValue(k, data[k]); 34 | } 35 | } 36 | }); 37 | } 38 | 39 | function onSubmit(values) { 40 | ConfSave(confType, JSON.stringify(values)).then(r => checkResult(r, "save config success")); 41 | } 42 | 43 | return ( 44 |
45 |
46 |

Github page

47 |

48 | Deploy site with github. 49 |

50 |
51 | 52 |
53 | 54 | ( 58 | 59 | Repository 60 | 61 | 62 | 63 | Your github repository url 64 | 65 | 66 | )} 67 | > 68 | ( 72 | 73 | Email 74 | 75 | 76 | 77 | Your email for github 78 | 79 | 80 | )} 81 | > 82 | ( 86 | 87 | Username 88 | 89 | 90 | 91 | Your username for github 92 | 93 | 94 | )} 95 | > 96 | ( 100 | 101 | Token 102 | 103 | 104 | 105 | Your token for github 106 | 107 | 108 | )} 109 | > 110 | ( 114 | 115 | CNAME 116 | 117 | 118 | 119 | Your cname for gitpage 120 | 121 | 122 | )} 123 | > 124 | 125 |
126 | 127 |
128 | ); 129 | } 130 | 131 | export default GitSetting; 132 | -------------------------------------------------------------------------------- /frontend/src/components/page/settings/deploy/layout.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState, useEffect } from "react"; 2 | import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"; 3 | import GitSetting from "@/components/page/settings/deploy/git"; 4 | import CosSetting from "@/components/page/settings/deploy/cos"; 5 | import OssSetting from "@/components/page/settings/deploy/oss"; 6 | import NetlifySetting from "@/components/page/settings/deploy/netlify"; 7 | import { ConfGet } from "/wailsjs/go/backend/App"; 8 | import { Toaster } from "@/components/ui/sonner"; 9 | import { isSuccess } from "@/components/page/util"; 10 | 11 | function DeploySetting() { 12 | const [activedDeploy, setActivedDeploy] = useState("github"); 13 | 14 | useEffect(() => { 15 | init(); 16 | }, []); 17 | 18 | function init() { 19 | ConfGet("app").then((result) => { 20 | if (isSuccess(result)) { 21 | const data = result.data; 22 | if (data && data.activedDeploy) { 23 | setActivedDeploy(data.activedDeploy); 24 | } 25 | } 26 | }); 27 | } 28 | 29 | return ( 30 | <> 31 | 32 | 33 | 34 | github 35 | cos 36 | oss 37 | netlify 38 | 39 | {} 40 | {} 41 | {} 42 | {} 43 | 44 | 45 | ); 46 | } 47 | 48 | export default DeploySetting; 49 | -------------------------------------------------------------------------------- /frontend/src/components/page/settings/deploy/netlify.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from "react"; 2 | import { Button } from "@/components/ui/button"; 3 | import { Separator } from "@/components/ui/separator"; 4 | import { useForm } from "react-hook-form"; 5 | import { 6 | Form, 7 | FormControl, 8 | FormDescription, 9 | FormField, 10 | FormItem, 11 | FormLabel, 12 | FormMessage, 13 | } from "@/components/ui/form"; 14 | import { Input } from "@/components/ui/input"; 15 | import { ConfSave, ConfGet } from "/wailsjs/go/backend/App"; 16 | import { checkResult, isSuccess } from "@/components/page/util"; 17 | 18 | function NetlifySetting() { 19 | const form = useForm(); 20 | 21 | const confType = "netlify"; 22 | 23 | useEffect(() => { 24 | init(); 25 | }, []); 26 | 27 | function init() { 28 | // init form 29 | ConfGet(confType).then((result) => { 30 | if (isSuccess(result)) { 31 | const data = result.data; 32 | for (var k in data) { 33 | form.setValue(k, data[k]); 34 | } 35 | } 36 | }); 37 | } 38 | 39 | function onSubmit(values) { 40 | ConfSave(confType, JSON.stringify(values)).then(r => checkResult(r, "save config success")); 41 | } 42 | 43 | return ( 44 |
45 |
46 |

Account

47 |

Deploy site with cos.

48 |
49 | 50 |
51 | 52 | ( 56 | 57 | SiteId 58 | 59 | 60 | 61 | Your SiteId for netlify 62 | 63 | 64 | )} 65 | > 66 | ( 70 | 71 | Token 72 | 73 | 74 | 75 | Your Token for netlify 76 | 77 | 78 | )} 79 | > 80 | 81 |
82 | 83 |
84 | ); 85 | } 86 | 87 | export default NetlifySetting; 88 | -------------------------------------------------------------------------------- /frontend/src/components/page/settings/deploy/oss.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from "react"; 2 | import { Button } from "@/components/ui/button"; 3 | import { Separator } from "@/components/ui/separator"; 4 | import { useForm } from "react-hook-form"; 5 | import { 6 | Form, 7 | FormControl, 8 | FormDescription, 9 | FormField, 10 | FormItem, 11 | FormLabel, 12 | FormMessage, 13 | } from "@/components/ui/form"; 14 | import { Input } from "@/components/ui/input"; 15 | import { ConfSave, ConfGet } from "/wailsjs/go/backend/App"; 16 | import { checkResult, isSuccess } from "@/components/page/util"; 17 | 18 | function OssSetting() { 19 | const form = useForm(); 20 | 21 | const confType = "oss"; 22 | 23 | useEffect(() => { 24 | init(); 25 | }, []); 26 | 27 | function init() { 28 | // init form 29 | ConfGet(confType).then((result) => { 30 | if (isSuccess(result)) { 31 | const data = result.data; 32 | for (var k in data) { 33 | form.setValue(k, data[k]); 34 | } 35 | } 36 | }); 37 | } 38 | 39 | function onSubmit(values) { 40 | ConfSave(confType, JSON.stringify(values)).then(r => checkResult(r, "save config success")); 41 | } 42 | 43 | return ( 44 |
45 |
46 |

Account

47 |

Deploy site with cos.

48 |
49 | 50 |
51 | 52 | ( 56 | 57 | AppId 58 | 59 | 60 | 61 | Your cos app id 62 | 63 | 64 | )} 65 | > 66 | ( 70 | 71 | SecretId 72 | 73 | 74 | 75 | Your SecretId for cos 76 | 77 | 78 | )} 79 | > 80 | ( 84 | 85 | SecretKey 86 | 87 | 88 | 89 | Your SecretKey for cos 90 | 91 | 92 | )} 93 | > 94 | ( 98 | 99 | Region 100 | 101 | 102 | 103 | Your Region for cos 104 | 105 | 106 | )} 107 | > 108 | ( 112 | 113 | Bucket 114 | 115 | 116 | 117 | Your Bucket for cos 118 | 119 | 120 | )} 121 | > 122 | 123 |
124 | 125 |
126 | ); 127 | } 128 | 129 | export default OssSetting; 130 | -------------------------------------------------------------------------------- /frontend/src/components/page/settings/page.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect } from "react"; 2 | import { Link } from "react-router-dom"; 3 | import { Button, buttonVariants } from "@/components/ui/button"; 4 | import { Separator } from "@/components/ui/separator"; 5 | import { useState } from "react"; 6 | import SiteSetting from "@/components/page/settings/site"; 7 | import { cn } from "@/lib/utils"; 8 | import { CircleX } from "lucide-react"; 9 | import "../style.css"; 10 | import DeploySetting from "@/components/page/settings/deploy/layout"; 11 | import { Toaster } from "@/components/ui/sonner" 12 | 13 | function SettingsPage() { 14 | const [panel, setPanel] = useState(""); 15 | const [curMenu, setCurMenu] = useState("Theme"); 16 | 17 | useEffect(() => { 18 | navChange("Theme", ); 19 | }, []); 20 | 21 | function navChange(text, to) { 22 | setCurMenu(text); 23 | setPanel(to); 24 | } 25 | 26 | const NavItem = ({ text, to }) => { 27 | return ( 28 | navChange(text, to)} 30 | className={cn( 31 | buttonVariants({ variant: "ghost" }), 32 | curMenu === text ? "bg-muted hover:bg-muted" : "hover:bg-transparent", 33 | "justify-start", 34 | "h-8" 35 | )} 36 | > 37 | {text} 38 | 39 | ); 40 | }; 41 | 42 | return ( 43 |
44 | 45 |
49 |

Settings

50 |

51 | Manage your account settings and set e-mail preferences. 52 |

53 | 54 | 61 | 62 |
63 | 64 |
65 | 69 |
70 | {panel} 71 |
72 |
73 |
74 | ); 75 | } 76 | 77 | export default SettingsPage; 78 | -------------------------------------------------------------------------------- /frontend/src/components/page/settings/site.jsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useState } from "react"; 2 | import { Button } from "@/components/ui/button"; 3 | import { Separator } from "@/components/ui/separator"; 4 | import { useForm } from "react-hook-form"; 5 | import { 6 | Form, 7 | FormControl, 8 | FormDescription, 9 | FormField, 10 | FormItem, 11 | FormLabel, 12 | FormMessage, 13 | } from "@/components/ui/form"; 14 | import { 15 | Select, 16 | SelectContent, 17 | SelectItem, 18 | SelectTrigger, 19 | SelectValue, 20 | } from "@/components/ui/select"; 21 | import { Input } from "@/components/ui/input"; 22 | import { 23 | SiteConfigGet, 24 | SiteConfigSave, 25 | ConfGetThemes, 26 | GetSiteImageConf, 27 | SelectConfImage, 28 | } from "/wailsjs/go/backend/App"; 29 | import { 30 | ifSuccess, 31 | checkResult, 32 | isSuccess, 33 | checkError, 34 | } from "@/components/page/util"; 35 | import { ImageUp } from "lucide-react"; 36 | 37 | function SiteSetting() { 38 | const form = useForm(); 39 | const [themeOptions, setThemeOptions] = useState([]); 40 | const [avatar, setAvatar] = useState(""); 41 | const [favicon, setFavicon] = useState(""); 42 | 43 | useEffect(() => { 44 | init(); 45 | }, []); 46 | 47 | function init() { 48 | // get themes 49 | getThemes(); 50 | // get site image config 51 | getSiteImage(); 52 | // init form 53 | SiteConfigGet().then((result) => { 54 | if (isSuccess(result)) { 55 | const data = result.data; 56 | for (var k in data) { 57 | form.setValue(k, data[k]); 58 | } 59 | } 60 | }); 61 | } 62 | 63 | const getThemes = () => { 64 | ConfGetThemes().then((r) => ifSuccess(r, setThemeOptions)); 65 | }; 66 | 67 | const getSiteImage = () => { 68 | GetSiteImageConf().then((r) => { 69 | if (isSuccess(r)) { 70 | setAvatar(r.avatar); 71 | setFavicon(r.favicon); 72 | } 73 | }); 74 | }; 75 | 76 | const setSiteImage = (s) => { 77 | SelectConfImage(s).then(checkError); 78 | getSiteImage(); 79 | }; 80 | 81 | function onSubmit(values) { 82 | SiteConfigSave(values).then((r) => checkResult(r, "save success")); 83 | } 84 | 85 | const SiteImageInput = (props) => { 86 | const { label, type } = props; 87 | return ( 88 |
89 | 92 |
93 |
setSiteImage(type)} 96 | > 97 | {avatar ? ( 98 | 103 | ) : ( 104 | <> 105 | 106 |

107 | select a image 108 |

109 | 110 | )} 111 |
112 |
113 |

114 | select a image for {label} 115 |

116 |
117 | ); 118 | }; 119 | 120 | return ( 121 |
122 |
123 |

Account

124 |

125 | Update your site settings. 126 |

127 |
128 | 129 |
130 | 131 | ( 135 | 136 | Title 137 | 138 | 139 | 140 | Your website title 141 | 142 | 143 | )} 144 | > 145 | ( 149 | 150 | Description 151 | 152 | 153 | 154 | Your website description 155 | 156 | 157 | )} 158 | > 159 | ( 163 | 164 | Theme 165 | 183 | 184 | select your website description 185 | 186 | 187 | 188 | )} 189 | > 190 | ( 194 | 195 | Language 196 | 211 | 212 | select your website description 213 | 214 | 215 | 216 | )} 217 | > 218 | ( 222 | 223 | Copyright 224 | 225 | 226 | 227 | 228 | select your website description 229 | 230 | 231 | 232 | )} 233 | > 234 | ( 238 | 239 | Author 240 | 241 | 242 | 243 | 244 | select your website description 245 | 246 | 247 | 248 | )} 249 | > 250 | ( 254 | 255 | Author 256 | 257 | 258 | 259 | 260 | select your website description 261 | 262 | 263 | 264 | )} 265 | > 266 | 267 | 268 | 269 | 270 | 271 |
272 | ); 273 | } 274 | 275 | export default SiteSetting; 276 | -------------------------------------------------------------------------------- /frontend/src/components/page/style.css: -------------------------------------------------------------------------------- 1 | #root, 2 | html, 3 | body { 4 | font-size: 14px; 5 | height: 100vh; 6 | margin: 0; 7 | padding: 0; 8 | overflow: hidden; 9 | } 10 | 11 | .scrollbar-hide::-webkit-scrollbar { 12 | display: none; 13 | } 14 | 15 | .scrollbar-hide { 16 | -ms-overflow-style: none; 17 | scrollbar-width: none; 18 | } 19 | 20 | .editor-title-input { 21 | border: none !important; 22 | @apply outline-none focus:outline-none; 23 | } 24 | 25 | .w-md-editor { 26 | border: none !important; 27 | box-shadow: none !important; 28 | } 29 | 30 | .w-md-editor-input { 31 | scrollbar-width: none !important; 32 | -ms-overflow-style: none !important; 33 | border: none !important; 34 | overflow: hidden; 35 | 36 | &::-webkit-scrollbar { 37 | display: none !important; 38 | } 39 | } 40 | 41 | .w-md-editor-bar { 42 | visibility: hidden; 43 | } 44 | 45 | .w-md-editor-text-input::placeholder { 46 | color: #9d9d9d; 47 | } -------------------------------------------------------------------------------- /frontend/src/components/page/test.jsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from "react"; 2 | import { TagInput } from "emblor"; 3 | 4 | function Example() { 5 | const [exampleTags, setExampleTags] = useState([]); 6 | const [activeTagIndex, setActiveTagIndex] = useState(null); 7 | 8 | return ( 9 | <> 10 |
11 | aaaaa 12 |
13 | { 16 | setExampleTags(newTags); 17 | }} 18 | placeholder="Add a tag" 19 | styleClasses={{}} 20 | activeTagIndex={activeTagIndex} 21 | setActiveTagIndex={setActiveTagIndex} 22 | /> 23 | 24 | ); 25 | } 26 | 27 | export default Example; 28 | -------------------------------------------------------------------------------- /frontend/src/components/page/util.js: -------------------------------------------------------------------------------- 1 | import { toast } from "sonner"; 2 | 3 | /** 4 | * get current date time, format: yyyy-MM-dd HH:MM:SS 5 | */ 6 | export function getCurrentTime() { 7 | return formatDateTime(new Date()); 8 | } 9 | 10 | /** 11 | * format date time: yyyy-MM-dd HH:MM:SS 12 | */ 13 | export function formatDateTime(value) { 14 | let month = zeroFill(value.getMonth() + 1); 15 | let day = zeroFill(value.getDate()); 16 | let hour = zeroFill(value.getHours()); 17 | let minute = zeroFill(value.getMinutes()); 18 | let second = zeroFill(value.getSeconds()); 19 | 20 | return ( 21 | value.getFullYear() + 22 | "-" + 23 | month + 24 | "-" + 25 | day + 26 | " " + 27 | hour + 28 | ":" + 29 | minute + 30 | ":" + 31 | second 32 | ); 33 | } 34 | 35 | export function ifSuccess(r, fn) { 36 | if (r.code == 1) { 37 | fn(r.data); 38 | } else { 39 | toast.error(r.msg); 40 | } 41 | } 42 | 43 | export function isSuccess(r) { 44 | if (r.code == 1) { 45 | return true; 46 | } else { 47 | toast.error(r.msg); 48 | return false; 49 | } 50 | } 51 | 52 | export function checkResult(r, successMsg) { 53 | if (r.code == 1) { 54 | toast.info(successMsg); 55 | } else { 56 | toast.error(r.msg); 57 | } 58 | } 59 | 60 | export function checkError(r) { 61 | if (r.code !== 1) { 62 | toast.error(r.msg); 63 | } 64 | } 65 | 66 | function zeroFill(i) { 67 | if (i >= 0 && i <= 9) { 68 | return "0" + i; 69 | } else { 70 | return i; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /frontend/src/components/ui/badge.jsx: -------------------------------------------------------------------------------- 1 | import * as React from "react" 2 | import { cva } from "class-variance-authority"; 3 | 4 | import { cn } from "@/lib/utils" 5 | 6 | const badgeVariants = cva( 7 | "inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2", 8 | { 9 | variants: { 10 | variant: { 11 | default: 12 | "border-transparent bg-primary text-primary-foreground hover:bg-primary/80", 13 | secondary: 14 | "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80", 15 | destructive: 16 | "border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80", 17 | outline: "text-foreground", 18 | }, 19 | }, 20 | defaultVariants: { 21 | variant: "default", 22 | }, 23 | } 24 | ) 25 | 26 | function Badge({ 27 | className, 28 | variant, 29 | ...props 30 | }) { 31 | return (
); 32 | } 33 | 34 | export { Badge, badgeVariants } 35 | -------------------------------------------------------------------------------- /frontend/src/components/ui/button.jsx: -------------------------------------------------------------------------------- 1 | import * as React from "react" 2 | import { Slot } from "@radix-ui/react-slot" 3 | import { cva } from "class-variance-authority"; 4 | 5 | import { cn } from "@/lib/utils" 6 | 7 | const buttonVariants = cva( 8 | "inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50", 9 | { 10 | variants: { 11 | variant: { 12 | default: "bg-primary text-primary-foreground hover:bg-primary/90", 13 | destructive: 14 | "bg-destructive text-destructive-foreground hover:bg-destructive/90", 15 | outline: 16 | "border border-input bg-background hover:bg-accent hover:text-accent-foreground", 17 | secondary: 18 | "bg-secondary text-secondary-foreground hover:bg-secondary/80", 19 | ghost: "hover:bg-accent hover:text-accent-foreground", 20 | link: "text-primary underline-offset-4 hover:underline", 21 | }, 22 | size: { 23 | default: "h-10 px-4 py-2", 24 | sm: "h-9 rounded-md px-3", 25 | lg: "h-11 rounded-md px-8", 26 | icon: "h-10 w-10", 27 | }, 28 | }, 29 | defaultVariants: { 30 | variant: "default", 31 | size: "default", 32 | }, 33 | } 34 | ) 35 | 36 | const Button = React.forwardRef(({ className, variant, size, asChild = false, ...props }, ref) => { 37 | const Comp = asChild ? Slot : "button" 38 | return ( 39 | () 43 | ); 44 | }) 45 | Button.displayName = "Button" 46 | 47 | export { Button, buttonVariants } 48 | -------------------------------------------------------------------------------- /frontend/src/components/ui/card.jsx: -------------------------------------------------------------------------------- 1 | import * as React from "react" 2 | 3 | import { cn } from "@/lib/utils" 4 | 5 | const Card = React.forwardRef(({ className, ...props }, ref) => ( 6 |
10 | )) 11 | Card.displayName = "Card" 12 | 13 | const CardHeader = React.forwardRef(({ className, ...props }, ref) => ( 14 |
18 | )) 19 | CardHeader.displayName = "CardHeader" 20 | 21 | const CardTitle = React.forwardRef(({ className, ...props }, ref) => ( 22 |

26 | )) 27 | CardTitle.displayName = "CardTitle" 28 | 29 | const CardDescription = React.forwardRef(({ className, ...props }, ref) => ( 30 |

34 | )) 35 | CardDescription.displayName = "CardDescription" 36 | 37 | const CardContent = React.forwardRef(({ className, ...props }, ref) => ( 38 |

39 | )) 40 | CardContent.displayName = "CardContent" 41 | 42 | const CardFooter = React.forwardRef(({ className, ...props }, ref) => ( 43 |
47 | )) 48 | CardFooter.displayName = "CardFooter" 49 | 50 | export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent } 51 | -------------------------------------------------------------------------------- /frontend/src/components/ui/checkbox.jsx: -------------------------------------------------------------------------------- 1 | import * as React from "react" 2 | import * as CheckboxPrimitive from "@radix-ui/react-checkbox" 3 | import { Check } from "lucide-react" 4 | 5 | import { cn } from "@/lib/utils" 6 | 7 | const Checkbox = React.forwardRef(({ className, ...props }, ref) => ( 8 | 15 | 16 | 17 | 18 | 19 | )) 20 | Checkbox.displayName = CheckboxPrimitive.Root.displayName 21 | 22 | export { Checkbox } 23 | -------------------------------------------------------------------------------- /frontend/src/components/ui/form.jsx: -------------------------------------------------------------------------------- 1 | import * as React from "react" 2 | import { Slot } from "@radix-ui/react-slot" 3 | import { Controller, FormProvider, useFormContext } from "react-hook-form"; 4 | 5 | import { cn } from "@/lib/utils" 6 | import { Label } from "@/components/ui/label" 7 | 8 | const Form = FormProvider 9 | 10 | const FormFieldContext = React.createContext({}) 11 | 12 | const FormField = ( 13 | { 14 | ...props 15 | } 16 | ) => { 17 | return ( 18 | ( 19 | 20 | ) 21 | ); 22 | } 23 | 24 | const useFormField = () => { 25 | const fieldContext = React.useContext(FormFieldContext) 26 | const itemContext = React.useContext(FormItemContext) 27 | const { getFieldState, formState } = useFormContext() 28 | 29 | const fieldState = getFieldState(fieldContext.name, formState) 30 | 31 | if (!fieldContext) { 32 | throw new Error("useFormField should be used within ") 33 | } 34 | 35 | const { id } = itemContext 36 | 37 | return { 38 | id, 39 | name: fieldContext.name, 40 | formItemId: `${id}-form-item`, 41 | formDescriptionId: `${id}-form-item-description`, 42 | formMessageId: `${id}-form-item-message`, 43 | ...fieldState, 44 | } 45 | } 46 | 47 | const FormItemContext = React.createContext({}) 48 | 49 | const FormItem = React.forwardRef(({ className, ...props }, ref) => { 50 | const id = React.useId() 51 | 52 | return ( 53 | ( 54 |
55 | ) 56 | ); 57 | }) 58 | FormItem.displayName = "FormItem" 59 | 60 | const FormLabel = React.forwardRef(({ className, ...props }, ref) => { 61 | const { error, formItemId } = useFormField() 62 | 63 | return ( 64 | (