Compare commits
2 Commits
553e66b590
...
6d4bd5cdf2
Author | SHA1 | Date |
---|---|---|
|
6d4bd5cdf2 | |
|
89265ee383 |
|
@ -1,3 +0,0 @@
|
||||||
# Gosora doesn't use Apache, this file is just here to stop Apache from blindly serving our config files, etc. when this program isn't intended to be served in such a manner at all
|
|
||||||
|
|
||||||
deny from all
|
|
26
.travis.yml
26
.travis.yml
|
@ -1,26 +0,0 @@
|
||||||
language: go
|
|
||||||
go:
|
|
||||||
- "1.13"
|
|
||||||
- "1.14"
|
|
||||||
- "1.15"
|
|
||||||
- "1.16"
|
|
||||||
- master
|
|
||||||
before_install:
|
|
||||||
- cd $HOME
|
|
||||||
- git clone https://github.com/Azareal/Gosora gosora
|
|
||||||
- cd gosora
|
|
||||||
- chmod -R 0777 .
|
|
||||||
- mv ./config/config_example.json ./config/config.json
|
|
||||||
- ./update-deps-linux
|
|
||||||
- ./dev-update-travis
|
|
||||||
- mv ./experimental/plugin_sendmail.go ..
|
|
||||||
install: true
|
|
||||||
before_script:
|
|
||||||
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
|
|
||||||
- chmod +x ./cc-test-reporter
|
|
||||||
- ./cc-test-reporter before-build
|
|
||||||
script: ./run-linux-tests
|
|
||||||
after_script:
|
|
||||||
- ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT
|
|
||||||
addons:
|
|
||||||
mariadb: '10.3'
|
|
|
@ -1,4 +1,4 @@
|
||||||
// Place your settings in this file to overwrite default and user settings.
|
// Place your settings in this file to overwrite default and user settings.
|
||||||
{
|
{
|
||||||
"editor.insertSpaces": false
|
"editor.insertSpaces": true
|
||||||
}
|
}
|
|
@ -1,53 +0,0 @@
|
||||||
# Contributing
|
|
||||||
|
|
||||||
First and foremost, if you want to add a contribution, you'll have to open a pull request and to sign the CLA (contributor level agreement).
|
|
||||||
|
|
||||||
It's mainly there to deal with any legal issues which may come our way and to switch licenses without having to track down every contributor who has ever contributed.
|
|
||||||
|
|
||||||
Some things we could do is commercial licensing for companies which are not authorised to use open source licenses or moving to a more permissive license, although I'm not too experianced in these matters, if anyone has any ideas, then feel free to put them forward.
|
|
||||||
|
|
||||||
Try to prefix commits which introduce a lot of bugs or otherwise has a large impact on the usability of Gosora with UNSTABLE.
|
|
||||||
|
|
||||||
If something seems to be strange, then feel free to bring up an alternative for it, although I'd rather not get hung up on the little details, if it's something which is purely a matter of opinion.
|
|
||||||
|
|
||||||
# Coding Standards
|
|
||||||
|
|
||||||
All code must be unit tested where ever possible with the exception of JavaScript which is untestable with our current technologies, tread with caution there.
|
|
||||||
|
|
||||||
Use tabs not spaces for indentation.
|
|
||||||
|
|
||||||
# Golang
|
|
||||||
|
|
||||||
Use the standard linter and listen to what it tells you to do.
|
|
||||||
|
|
||||||
The route assignments in main.go are *legacy code*, add new routes to `router_gen/routes.go` instead.
|
|
||||||
|
|
||||||
Try to use the single responsibility principle where ever possible, with the exception for if doing so will cause a large performance drop. In other words, don't give your interfaces / structs too many responsibilities, keep them simple.
|
|
||||||
|
|
||||||
Avoid hand-rolling queries. Use the builders, a ready built statement or a datastore structure instead. Preferably a datastore.
|
|
||||||
|
|
||||||
Commits which require the patcher / update script to be run should be prefixed with "Database Changes: "
|
|
||||||
|
|
||||||
More coming up.
|
|
||||||
|
|
||||||
# JavaScript
|
|
||||||
|
|
||||||
Use semicolons at the end of statements. If you don't, you might wind up breaking a minifier or two.
|
|
||||||
|
|
||||||
Always use strict mode.
|
|
||||||
|
|
||||||
Don't worry about ES5, we're targetting modern browsers. If we decide to backport code to older browsers, then we'll transpile the files.
|
|
||||||
|
|
||||||
Please don't use await. It incurs too much of a cognitive overhead as to where and when you can use it. We can't use it everywhere quite yet, which means that we really should be using it nowhere.
|
|
||||||
|
|
||||||
Please don't abuse `const` just to shave off a few nanoseconds. Even in the Go server where I care about performance the most, I don't use const everywhere, only in about five spots in thirty thousand lines and I don't use it for performance at all there.
|
|
||||||
|
|
||||||
To keep consistency with Go code, variables must be camelCase.
|
|
||||||
|
|
||||||
# JSON
|
|
||||||
|
|
||||||
To keep consistency with Go code, map keys must be camelCase.
|
|
||||||
|
|
||||||
# Phrases
|
|
||||||
|
|
||||||
Try to keep the name of the phrase close to the actual phrase in english to make it easier for localisers to reason about which phrase is which.
|
|
189
README.md
189
README.md
|
@ -1,189 +0,0 @@
|
||||||
# Gosora ![Build Status](https://travis-ci.org/Azareal/Gosora.svg?branch=master) [![Azareal's Discord Chat](https://img.shields.io/badge/style-Invite-7289DA.svg?style=flat&label=Discord)](https://discord.gg/eyYvtTf)
|
|
||||||
|
|
||||||
A super fast forum software written in Go. You can talk to us on our Discord chat!
|
|
||||||
|
|
||||||
The initial code-base was forked from one of my side projects, but has now gone far beyond that. We've moved along in a development and the software should be somewhat stable for general use.
|
|
||||||
|
|
||||||
Features may break from time to time, however I will generally try to warn of the biggest offenders in advance, so that you can tread with caution around certain commits, the upcoming v0.1 will undergo even more rigorous testing.
|
|
||||||
|
|
||||||
File an issue or open a topic on the forum, if there's something you want and you very well might find it landing in the software fairly quickly.
|
|
||||||
|
|
||||||
For plugin and theme developers, things are a little dicier, as the internal APIs and ways of writing themes are in constant flux, however some stability in that area should be coming fairly soon.
|
|
||||||
|
|
||||||
If you like this software, please give it a star and give us some feedback :)
|
|
||||||
|
|
||||||
If you dislike it, please give us some feedback on how to make it better! We're always looking for feedback. We love hearing your opinions. If there's something missing or something doesn't look quite right, don't worry! We plan to add many, many things in the run up to v0.1!
|
|
||||||
|
|
||||||
|
|
||||||
# Features
|
|
||||||
Standard Forum Functionality. All of the little things you would expect of any forum software. E.g. Common Moderation features, modlogs, theme system, avatars, bbcode parser, markdown parser, report system, per-forum permissions, group permissions and so on.
|
|
||||||
|
|
||||||
Custom Pages. There are some rough edges
|
|
||||||
|
|
||||||
Emojis. Allow your users to express themselves without resorting to serving tons upon tons of image files.
|
|
||||||
|
|
||||||
In-memory static file, forum and group caches. We have a slightly more dynamic cache for users and topics.
|
|
||||||
|
|
||||||
A profile system, including profile comments and moderation tools for the profile owner.
|
|
||||||
|
|
||||||
A template engine which compiles templates down to machine code. Over forty times faster than the standard template library `html/templates`, although it does remove some of the hand holding to achieve this. Compatible with templates written for `html/templates`, so you don't need to learn any new templating language.
|
|
||||||
|
|
||||||
A plugin system. We have a number of APIs and hooks for plugins, however they're currently subject to change and don't cover as much of the software as we'd like yet.
|
|
||||||
|
|
||||||
A responsive design. Looks great on mobile phones, tablets, laptops, desktops and more!
|
|
||||||
|
|
||||||
Other modern features like alerts, likes, advanced dashboard with live stats (CPU, RAM, online user count, and so on), etc.
|
|
||||||
|
|
||||||
|
|
||||||
# Requirements
|
|
||||||
|
|
||||||
Go 1.13 or newer - You will need to install this. Pick the .msi, if you want everything sorted out for you rather than having to go around updating the environment settings. https://golang.org/doc/install
|
|
||||||
|
|
||||||
For Ubuntu, you can consult: https://tecadmin.net/install-go-on-ubuntu/
|
|
||||||
You will also want to run `ln -s /usr/local/go/bin/go` (replace /usr/local with where ever you put Go), so that go becomes visible to other users.
|
|
||||||
|
|
||||||
If you followed the instructions above, you can update to the latest version of Go simply by deleting the `/go/` folder and replacing it with a `/go/` folder for the latest version of Go.
|
|
||||||
|
|
||||||
Git - You may need this for downloading updates via the updater. You might already have this installed on your server, if the `git` commands don't work, then install this. https://git-scm.com/downloads
|
|
||||||
|
|
||||||
MySQL Database - You will need to setup a MySQL Database somewhere. A MariaDB Database works equally well and is much faster than MySQL. You could use something like WNMP / XAMPP which have a little PHP script called PhpMyAdmin for managing MySQL databases or you could install MariaDB directly.
|
|
||||||
|
|
||||||
Download the .msi installer from [MariaDB](https://mariadb.com/downloads) and run that. You may want to set it up as a service to avoid running it every-time the computer starts up.
|
|
||||||
|
|
||||||
Instructions on how to set MariaDB up on Linux: https://downloads.mariadb.org/mariadb/repositories/
|
|
||||||
|
|
||||||
We recommend changing the root password (that is the password for the user 'root'). Remember that password, you will need it for the installation process. Of course, we would advise using a user other than root for maximum security, although that adds additional steps to the process of getting everything setup.
|
|
||||||
|
|
||||||
You might also want to run `mysql_secure_installation` to further harden (aka make it more secure) MySQL / MariaDB.
|
|
||||||
|
|
||||||
If you're using Ubuntu, you might want to look at: https://www.itzgeek.com/how-tos/linux/ubuntu-how-tos/install-mariadb-on-ubuntu-16-04.html
|
|
||||||
|
|
||||||
It's entirely possible that your host already has MySQL installed and ready to go, so you might be able to skip this step, particularly if it's a managed VPS or a shared host. Or they might have a quicker and easier method of setting up MySQL.
|
|
||||||
|
|
||||||
|
|
||||||
# How to download
|
|
||||||
|
|
||||||
For Linux, you can skip down to the Installation section as it covers this.
|
|
||||||
|
|
||||||
On Windows, you might want to try the [GosoraBootstrapper](https://github.com/Azareal/GosoraBootstrapper), if you can't find the command prompt or otherwise can't follow those instructions. It's just a matter of double-clicking on the bat file there and it'll download the rest of the files for you.
|
|
||||||
|
|
||||||
# Installation
|
|
||||||
|
|
||||||
Consult [installation](https://github.com/Azareal/Gosora/blob/master/docs/installation.md) for instructions on how to install Gosora.
|
|
||||||
|
|
||||||
# Updating
|
|
||||||
|
|
||||||
Consult [updating](https://github.com/Azareal/Gosora/blob/master/docs/updating.md) for instructions on how to update Gosora.
|
|
||||||
|
|
||||||
|
|
||||||
# Running the program
|
|
||||||
|
|
||||||
*Linux*
|
|
||||||
|
|
||||||
If you have setup a service, you can run:
|
|
||||||
|
|
||||||
`./pre-run-linux`
|
|
||||||
|
|
||||||
`service gosora start`
|
|
||||||
|
|
||||||
You can then, check Gosora's current status (to see if it started up properly) with:
|
|
||||||
|
|
||||||
`service gosora status`
|
|
||||||
|
|
||||||
And you can stop it with:
|
|
||||||
|
|
||||||
`service gosora stop`
|
|
||||||
|
|
||||||
If you haven't setup a service, you can run `./run-linux`, although you will be responsible for finding a way to run it in the background, so that it doesn't close when the terminal does.
|
|
||||||
|
|
||||||
One method might be to use: https://serverfault.com/questions/34750/is-it-possible-to-detach-a-process-from-its-terminal-or-i-should-have-used-s
|
|
||||||
|
|
||||||
*Windows*
|
|
||||||
|
|
||||||
Run `run.bat`, e.g. double-clicking on it.
|
|
||||||
|
|
||||||
|
|
||||||
# How do I install plugins?
|
|
||||||
|
|
||||||
For the default plugins like Markdown and Helloworld, you can find them in the Plugin Manager of your Control Panel. For ones which aren't included by default, you will need to drop them down in the `/extend/` directory.
|
|
||||||
|
|
||||||
You will then need to recompile Gosora in order to link the plugin code with Gosora's code. For plugins not written in Go (e.g. JavaScript), they will automatically show up in your Control Panel ready to be installed, although we currently don't support these types of plugins at this time.
|
|
||||||
|
|
||||||
There are also some experimental plugins in the `/experimental/` folder like plugin_sendmail which you may want to make use of, although there aren't any particular guarantees about whether they will continue to function or not.
|
|
||||||
|
|
||||||
We're currently in the process of moving plugins from the `/` to the `/extend/` folder, if there is a piece of functionality that you would like to tap into, but which you cannot from that package, then feel free to poke me, otherwise you may need to drop it in `/` and name the package accordingly.
|
|
||||||
|
|
||||||
|
|
||||||
# Images
|
|
||||||
![Shadow Theme](https://github.com/Azareal/Gosora/blob/master/images/shadow.png)
|
|
||||||
|
|
||||||
![Shadow Quick Topic](https://github.com/Azareal/Gosora/blob/master/images/quick-topics.png)
|
|
||||||
|
|
||||||
![Tempra Simple Theme](https://github.com/Azareal/Gosora/blob/master/images/tempra-simple.png)
|
|
||||||
|
|
||||||
![Tempra Simple Topic List](https://github.com/Azareal/Gosora/blob/master/images/topic-list.png)
|
|
||||||
|
|
||||||
![Tempra Simple Mobile](https://github.com/Azareal/Gosora/blob/master/images/tempra-simple-mobile-375px.png)
|
|
||||||
|
|
||||||
![Cosora Prototype WIP](https://github.com/Azareal/Gosora/blob/master/images/cosora-wip.png)
|
|
||||||
|
|
||||||
More images in the /images/ folder. Beware though, some of them are *really* outdated. Also, keep in mind that a new theme is in the works.
|
|
||||||
|
|
||||||
# Dependencies
|
|
||||||
|
|
||||||
These are the libraries and pieces of software which Gosora relies on to function, an "ingredients" list so to speak.
|
|
||||||
|
|
||||||
A few of these like Rez aren't currently in use, but are things we think we'll need in the very near future and want to have those things ready, so that we can quickly slot them in.
|
|
||||||
|
|
||||||
* Go 1.11+
|
|
||||||
|
|
||||||
* MariaDB (or any other MySQL compatible database engine). We'll allow other database engines in the future.
|
|
||||||
|
|
||||||
* github.com/go-sql-driver/mysql For interfacing with MariaDB.
|
|
||||||
|
|
||||||
* golang.org/x/crypto/bcrypt For hashing passwords.
|
|
||||||
* golang.org/x/crypto/argon2 For hashing passwords.
|
|
||||||
|
|
||||||
* github.com/Azareal/gopsutil For pulling information on CPU and memory usage. I've temporarily forked this, as we were having stability issues with the latest build.
|
|
||||||
|
|
||||||
* github.com/StackExchange/wmi Dependency for gopsutil on Windows.
|
|
||||||
|
|
||||||
* golang.org/x/sys/windows Also a dependency for gopsutil on Windows. This isn't needed at the moment, as I've rolled things back to an older more stable build.
|
|
||||||
|
|
||||||
* github.com/gorilla/websocket Needed for Gosora's Optional WebSockets Module.
|
|
||||||
|
|
||||||
* github.com/robertkrimen/otto Needed for the upcoming JS plugin type.
|
|
||||||
|
|
||||||
* gopkg.in/sourcemap.v1 Dependency for Otto.
|
|
||||||
|
|
||||||
* github.com/lib/pq For interfacing with PostgreSQL. You will be able to pick this instead of MariaDB soon.
|
|
||||||
|
|
||||||
* ithub.com/denisenkom/go-mssqldb For interfacing with MSSQL. You will be able to pick this instead of MSSQL soon.
|
|
||||||
|
|
||||||
* github.com/bamiaux/rez An image resizer (e.g. for spitting out thumbnails)
|
|
||||||
|
|
||||||
* github.com/esimov/caire The other image resizer, slower but may be useful for covering cases Rez does not. A third faster one we might point to at some point is probably Discord's Lilliput, however it requires a C Compiler and we don't want to add that as a dependency at this time.
|
|
||||||
|
|
||||||
* github.com/fsnotify/fsnotify A library for watching events on the file system.
|
|
||||||
|
|
||||||
* github.com/pkg/errors Some helpers to make it easier for us to track down bugs.
|
|
||||||
|
|
||||||
* More items to come here, our dependencies are going through a lot of changes, and I'll be documenting those soon ;)
|
|
||||||
|
|
||||||
# Bundled Plugins
|
|
||||||
|
|
||||||
There are several plugins which are bundled with the software by default. These cover various common tasks which aren't common enough to clutter the core with or which have competing implementation methods (E.g. plugin_markdown vs plugin_bbcode for post mark-up).
|
|
||||||
|
|
||||||
* Hey There / Skeleton / Hey There (JS Version) - Example plugins for helping you learn how to develop plugins.
|
|
||||||
|
|
||||||
* BBCode - A plugin in early development for converting BBCode Tags into HTML.
|
|
||||||
|
|
||||||
* Markdown - An extremely simple plugin for converting Markdown into HTML.
|
|
||||||
|
|
||||||
* Social Groups - An extremely unstable WIP plugin which lets users create their own little discussion areas which they can administrate / moderate on their own.
|
|
||||||
|
|
||||||
# Developers
|
|
||||||
|
|
||||||
There are a few things you'll need to know before running the more developer oriented features like the tests or the benchmarks.
|
|
||||||
|
|
||||||
The benchmarks are currently being rewritten as they're currently extremely serial which can lead to severe slow-downs when run on a home computer due to the benchmarks being run on the one core everything else is being run on (Browser, OS, etc.) and the tests not taking parallelism into account.
|
|
38
TODO.md
38
TODO.md
|
@ -1,38 +0,0 @@
|
||||||
# TO-DO
|
|
||||||
|
|
||||||
Oh my, you caught me right at the start of this project. There's nothing to see here yet, asides from the absolute basics. You might want to look again later!
|
|
||||||
|
|
||||||
|
|
||||||
The various little features which somehow got stuck in the net. Don't worry, I'll get to them!
|
|
||||||
|
|
||||||
More moderation features. E.g. Move, Approval Queue (Posts made by users in certain usergroups will need to be approved by a moderator before they're publically visible), etc.
|
|
||||||
|
|
||||||
Add a simple anti-spam measure. I have quite a few ideas in mind, but it'll take a while to implement the more advanced ones, so I'd like to put off some of those to a later date and focus on the basics. E.g. CAPTCHAs, hidden fields, etc.
|
|
||||||
|
|
||||||
Add more granular permissions management to the Forum Manager.
|
|
||||||
|
|
||||||
Add a *better* plugin system. E.g. Allow for plugins written in Javascript and ones written in Go. Also, we need to add many, many, many more plugin hooks.
|
|
||||||
|
|
||||||
I will need to ponder over implementing an even faster router. We don't need one immediately, although it would be nice if we could get one in the near future. It really depends. Ideally, it would be one which can easily integrate with the current structure without much work, although I'm not beyond making some alterations to faciliate it, assuming that we don't get too tightly bound to that specific router.
|
|
||||||
|
|
||||||
Allow themes to define their own templates and to override core templates with their own.
|
|
||||||
|
|
||||||
Add a friend system.
|
|
||||||
|
|
||||||
Improve profile customisability.
|
|
||||||
|
|
||||||
Implement all the common BBCode tags in plugin_bbcode
|
|
||||||
|
|
||||||
Implement all the common Markdown codes in plugin_markdown
|
|
||||||
|
|
||||||
Add more administration features.
|
|
||||||
|
|
||||||
Add more features for improving user engagement. E.g. A like system. I have a few of these in mind, but I've been pre-occupied with implementing other features.
|
|
||||||
|
|
||||||
Add a widget system.
|
|
||||||
|
|
||||||
Add support for multi-factor authentication.
|
|
||||||
|
|
||||||
Add support for secondary emails for users.
|
|
||||||
|
|
||||||
Improve the shell scripts and possibly add support for Make? A make.go might be a good solution?
|
|
|
@ -1,63 +0,0 @@
|
||||||
@echo off
|
|
||||||
rem TODO: Make these deletes a little less noisy
|
|
||||||
del "template_*.go"
|
|
||||||
del "tmpl_*.go"
|
|
||||||
del "gen_*.go"
|
|
||||||
del ".\tmpl_client\template_*"
|
|
||||||
del ".\tmpl_client\tmpl_*"
|
|
||||||
del ".\common\gen_extend.go"
|
|
||||||
del "gosora.exe"
|
|
||||||
|
|
||||||
echo Generating the dynamic code
|
|
||||||
go generate
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Generating the JSON handlers
|
|
||||||
easyjson -pkg common
|
|
||||||
|
|
||||||
echo Building the executable
|
|
||||||
go build -ldflags="-s -w" -o gosora.exe -tags no_ws
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the installer
|
|
||||||
go build -ldflags="-s -w" "./cmd/install"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the router generator
|
|
||||||
go build -ldflags="-s -w" ./router_gen
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the hook stub generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the hook generator
|
|
||||||
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the query generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/query_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Gosora was successfully built
|
|
||||||
pause
|
|
63
build.bat
63
build.bat
|
@ -1,63 +0,0 @@
|
||||||
@echo off
|
|
||||||
rem TODO: Make these deletes a little less noisy
|
|
||||||
del "template_*.go"
|
|
||||||
del "tmpl_*.go"
|
|
||||||
del "gen_*.go"
|
|
||||||
del ".\tmpl_client\template_*"
|
|
||||||
del ".\tmpl_client\tmpl_*"
|
|
||||||
del ".\common\gen_extend.go"
|
|
||||||
del "gosora.exe"
|
|
||||||
|
|
||||||
echo Generating the dynamic code
|
|
||||||
go generate
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Generating the JSON handlers
|
|
||||||
easyjson -pkg common
|
|
||||||
|
|
||||||
echo Building the executable
|
|
||||||
go build -ldflags="-s -w" -o gosora.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the installer
|
|
||||||
go build -ldflags="-s -w" "./cmd/install"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the router generator
|
|
||||||
go build -ldflags="-s -w" ./router_gen
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the hook stub generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the hook generator
|
|
||||||
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the query generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/query_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Gosora was successfully built
|
|
||||||
pause
|
|
|
@ -1,11 +0,0 @@
|
||||||
echo Building the templates
|
|
||||||
gosora.exe -build-templates
|
|
||||||
|
|
||||||
echo Rebuilding the executable
|
|
||||||
go build -ldflags="-s -w" -o gosora.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
pause
|
|
|
@ -1,115 +1,115 @@
|
||||||
package hookgen
|
package hookgen
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"text/template"
|
"text/template"
|
||||||
)
|
)
|
||||||
|
|
||||||
type HookVars struct {
|
type HookVars struct {
|
||||||
Imports []string
|
Imports []string
|
||||||
Hooks []Hook
|
Hooks []Hook
|
||||||
}
|
}
|
||||||
|
|
||||||
type Hook struct {
|
type Hook struct {
|
||||||
Name string
|
Name string
|
||||||
Params string
|
Params string
|
||||||
Params2 string
|
Params2 string
|
||||||
Ret string
|
Ret string
|
||||||
Type string
|
Type string
|
||||||
Any bool
|
Any bool
|
||||||
MultiHook bool
|
MultiHook bool
|
||||||
Skip bool
|
Skip bool
|
||||||
DefaultRet string
|
DefaultRet string
|
||||||
Pure string
|
Pure string
|
||||||
}
|
}
|
||||||
|
|
||||||
func AddHooks(add func(name, params, ret, htype string, multiHook, skip bool, defaultRet, pure string)) {
|
func AddHooks(add func(name, params, ret, htype string, multiHook, skip bool, defaultRet, pure string)) {
|
||||||
vhookskip := func(name, params string) {
|
vhookskip := func(name, params string) {
|
||||||
add(name, params, "(bool,RouteError)", "VhookSkippable_", false, true, "false,nil", "")
|
add(name, params, "(bool,RouteError)", "VhookSkippable_", false, true, "false,nil", "")
|
||||||
}
|
}
|
||||||
vhookskip("simple_forum_check_pre_perms", "w http.ResponseWriter,r *http.Request,u *User,fid *int,h *HeaderLite")
|
vhookskip("simple_forum_check_pre_perms", "w http.ResponseWriter,r *http.Request,u *User,fid *int,h *HeaderLite")
|
||||||
vhookskip("forum_check_pre_perms", "w http.ResponseWriter,r *http.Request,u *User,fid *int,h *Header")
|
vhookskip("forum_check_pre_perms", "w http.ResponseWriter,r *http.Request,u *User,fid *int,h *Header")
|
||||||
vhookskip("router_after_filters", "w http.ResponseWriter,r *http.Request,prefix string")
|
vhookskip("router_after_filters", "w http.ResponseWriter,r *http.Request,prefix string")
|
||||||
vhookskip("router_pre_route", "w http.ResponseWriter,r *http.Request,u *User,prefix string")
|
vhookskip("router_pre_route", "w http.ResponseWriter,r *http.Request,u *User,prefix string")
|
||||||
vhookskip("route_forum_list_start", "w http.ResponseWriter,r *http.Request,u *User,h *Header")
|
vhookskip("route_forum_list_start", "w http.ResponseWriter,r *http.Request,u *User,h *Header")
|
||||||
vhookskip("route_topic_list_start", "w http.ResponseWriter,r *http.Request,u *User,h *Header")
|
vhookskip("route_topic_list_start", "w http.ResponseWriter,r *http.Request,u *User,h *Header")
|
||||||
vhookskip("route_attach_start", "w http.ResponseWriter,r *http.Request,u *User,fname string")
|
vhookskip("route_attach_start", "w http.ResponseWriter,r *http.Request,u *User,fname string")
|
||||||
vhookskip("route_attach_post_get", "w http.ResponseWriter,r *http.Request,u *User,a *Attachment")
|
vhookskip("route_attach_post_get", "w http.ResponseWriter,r *http.Request,u *User,a *Attachment")
|
||||||
|
|
||||||
vhooknoret := func(name, params string) {
|
vhooknoret := func(name, params string) {
|
||||||
add(name, params, "", "Vhooks", false, false, "false,nil", "")
|
add(name, params, "", "Vhooks", false, false, "false,nil", "")
|
||||||
}
|
}
|
||||||
vhooknoret("router_end", "w http.ResponseWriter,r *http.Request,u *User,prefix string,extraData string")
|
vhooknoret("router_end", "w http.ResponseWriter,r *http.Request,u *User,prefix string,extraData string")
|
||||||
vhooknoret("topic_reply_row_assign", "r *ReplyUser")
|
vhooknoret("topic_reply_row_assign", "r *ReplyUser")
|
||||||
vhooknoret("counters_perf_tick_row", "low int64,high int64,avg int64")
|
vhooknoret("counters_perf_tick_row", "low int64,high int64,avg int64")
|
||||||
//forums_frow_assign
|
//forums_frow_assign
|
||||||
//Hook(name string, data interface{}) interface{}
|
//Hook(name string, data interface{}) interface{}
|
||||||
/*hook := func(name, params, ret, pure string) {
|
/*hook := func(name, params, ret, pure string) {
|
||||||
add(name,params,ret,"Hooks",true,false,ret,pure)
|
add(name,params,ret,"Hooks",true,false,ret,pure)
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
hooknoret := func(name, params string) {
|
hooknoret := func(name, params string) {
|
||||||
add(name, params, "", "HooksNoRet", true, false, "", "")
|
add(name, params, "", "HooksNoRet", true, false, "", "")
|
||||||
}
|
}
|
||||||
hooknoret("forums_frow_assign", "f *Forum")
|
hooknoret("forums_frow_assign", "f *Forum")
|
||||||
|
|
||||||
hookskip := func(name, params string) {
|
hookskip := func(name, params string) {
|
||||||
add(name, params, "(skip bool)", "HooksSkip", true, true, "", "")
|
add(name, params, "(skip bool)", "HooksSkip", true, true, "", "")
|
||||||
}
|
}
|
||||||
//hookskip("forums_frow_assign","f *Forum")
|
//hookskip("forums_frow_assign","f *Forum")
|
||||||
hookskip("topic_create_frow_assign", "f *Forum")
|
hookskip("topic_create_frow_assign", "f *Forum")
|
||||||
|
|
||||||
hookss := func(name string) {
|
hookss := func(name string) {
|
||||||
add(name, "d string", "string", "Sshooks", true, false, "", "d")
|
add(name, "d string", "string", "Sshooks", true, false, "", "d")
|
||||||
}
|
}
|
||||||
hookss("topic_ogdesc_assign")
|
hookss("topic_ogdesc_assign")
|
||||||
}
|
}
|
||||||
|
|
||||||
func Write(hookVars HookVars) {
|
func Write(hookVars HookVars) {
|
||||||
fileData := `// Code generated by Gosora's Hook Generator. DO NOT EDIT.
|
fileData := `// Code generated by Gosora's Hook Generator. DO NOT EDIT.
|
||||||
/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */
|
/* This file was automatically generated by the software. Please don't edit it as your changes may be overwritten at any moment. */
|
||||||
package common
|
package common
|
||||||
import ({{range .Imports}}
|
import ({{range .Imports}}
|
||||||
"{{.}}"{{end}}
|
"{{.}}"{{end}}
|
||||||
)
|
)
|
||||||
{{range .Hooks}}
|
{{range .Hooks}}
|
||||||
func H_{{.Name}}_hook(t *HookTable,{{.Params}}) {{.Ret}} { {{if .Any}}
|
func H_{{.Name}}_hook(t *HookTable,{{.Params}}) {{.Ret}} { {{if .Any}}
|
||||||
{{if .MultiHook}}for _, hook := range t.{{.Type}}["{{.Name}}"] {
|
{{if .MultiHook}}for _, hook := range t.{{.Type}}["{{.Name}}"] {
|
||||||
{{if .Skip}}if skip = hook({{.Params2}}); skip {
|
{{if .Skip}}if skip = hook({{.Params2}}); skip {
|
||||||
break
|
break
|
||||||
}{{else}}{{if .Pure}}{{.Pure}} = {{else if .Ret}}return {{end}}hook({{.Params2}}){{end}}
|
}{{else}}{{if .Pure}}{{.Pure}} = {{else if .Ret}}return {{end}}hook({{.Params2}}){{end}}
|
||||||
}{{else}}hook := t.{{.Type}}["{{.Name}}"]
|
}{{else}}hook := t.{{.Type}}["{{.Name}}"]
|
||||||
if hook != nil {
|
if hook != nil {
|
||||||
{{if .Ret}}return {{end}}hook({{.Params2}})
|
{{if .Ret}}return {{end}}hook({{.Params2}})
|
||||||
} {{end}}{{end}}{{if .Pure}}
|
} {{end}}{{end}}{{if .Pure}}
|
||||||
return {{.Pure}}{{else if .Ret}}
|
return {{.Pure}}{{else if .Ret}}
|
||||||
return {{.DefaultRet}}{{end}}
|
return {{.DefaultRet}}{{end}}
|
||||||
}{{end}}
|
}{{end}}
|
||||||
`
|
`
|
||||||
tmpl := template.Must(template.New("hooks").Parse(fileData))
|
tmpl := template.Must(template.New("hooks").Parse(fileData))
|
||||||
var b bytes.Buffer
|
var b bytes.Buffer
|
||||||
if e := tmpl.Execute(&b, hookVars); e != nil {
|
if e := tmpl.Execute(&b, hookVars); e != nil {
|
||||||
log.Fatal(e)
|
log.Fatal(e)
|
||||||
}
|
}
|
||||||
|
|
||||||
err := writeFile("./common/gen_extend.go", b.String())
|
err := writeFile("./common/gen_extend.go", b.String())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeFile(name, body string) error {
|
func writeFile(name, body string) error {
|
||||||
f, e := os.Create(name)
|
f, e := os.Create(name)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
if _, e = f.WriteString(body); e != nil {
|
if _, e = f.WriteString(body); e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
if e = f.Sync(); e != nil {
|
if e = f.Sync(); e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
return f.Close()
|
return f.Close()
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,265 +2,265 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
|
||||||
c "github.com/Azareal/Gosora/common"
|
c "github.com/Azareal/Gosora/common"
|
||||||
"github.com/Azareal/Gosora/query_gen"
|
"github.com/Azareal/Gosora/query_gen"
|
||||||
"gopkg.in/olivere/elastic.v6"
|
"gopkg.in/olivere/elastic.v6"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
log.Print("Loading the configuration data")
|
log.Print("Loading the configuration data")
|
||||||
err := c.LoadConfig()
|
err := c.LoadConfig()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Print("Processing configuration data")
|
log.Print("Processing configuration data")
|
||||||
err = c.ProcessConfig()
|
err = c.ProcessConfig()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.DbConfig.Adapter != "mysql" && c.DbConfig.Adapter != "" {
|
if c.DbConfig.Adapter != "mysql" && c.DbConfig.Adapter != "" {
|
||||||
log.Fatal("Only MySQL is supported for upgrades right now, please wait for a newer build of the patcher")
|
log.Fatal("Only MySQL is supported for upgrades right now, please wait for a newer build of the patcher")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = prepMySQL()
|
err = prepMySQL()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
client, err := elastic.NewClient(elastic.SetErrorLog(log.New(os.Stdout, "ES ", log.LstdFlags)))
|
client, err := elastic.NewClient(elastic.SetErrorLog(log.New(os.Stdout, "ES ", log.LstdFlags)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
_, _, err = client.Ping("http://127.0.0.1:9200").Do(context.Background())
|
_, _, err = client.Ping("http://127.0.0.1:9200").Do(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = setupIndices(client)
|
err = setupIndices(client)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = setupData(client)
|
err = setupData(client)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func prepMySQL() error {
|
func prepMySQL() error {
|
||||||
return qgen.Builder.Init("mysql", map[string]string{
|
return qgen.Builder.Init("mysql", map[string]string{
|
||||||
"host": c.DbConfig.Host,
|
"host": c.DbConfig.Host,
|
||||||
"port": c.DbConfig.Port,
|
"port": c.DbConfig.Port,
|
||||||
"name": c.DbConfig.Dbname,
|
"name": c.DbConfig.Dbname,
|
||||||
"username": c.DbConfig.Username,
|
"username": c.DbConfig.Username,
|
||||||
"password": c.DbConfig.Password,
|
"password": c.DbConfig.Password,
|
||||||
"collation": "utf8mb4_general_ci",
|
"collation": "utf8mb4_general_ci",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
type ESIndexBase struct {
|
type ESIndexBase struct {
|
||||||
Mappings ESIndexMappings `json:"mappings"`
|
Mappings ESIndexMappings `json:"mappings"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ESIndexMappings struct {
|
type ESIndexMappings struct {
|
||||||
Doc ESIndexDoc `json:"_doc"`
|
Doc ESIndexDoc `json:"_doc"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ESIndexDoc struct {
|
type ESIndexDoc struct {
|
||||||
Properties map[string]map[string]string `json:"properties"`
|
Properties map[string]map[string]string `json:"properties"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ESDocMap map[string]map[string]string
|
type ESDocMap map[string]map[string]string
|
||||||
|
|
||||||
func (d ESDocMap) Add(column string, cType string) {
|
func (d ESDocMap) Add(column string, cType string) {
|
||||||
d["column"] = map[string]string{"type": cType}
|
d["column"] = map[string]string{"type": cType}
|
||||||
}
|
}
|
||||||
|
|
||||||
func setupIndices(client *elastic.Client) error {
|
func setupIndices(client *elastic.Client) error {
|
||||||
exists, err := client.IndexExists("topics").Do(context.Background())
|
exists, err := client.IndexExists("topics").Do(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if exists {
|
if exists {
|
||||||
deleteIndex, err := client.DeleteIndex("topics").Do(context.Background())
|
deleteIndex, err := client.DeleteIndex("topics").Do(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !deleteIndex.Acknowledged {
|
if !deleteIndex.Acknowledged {
|
||||||
return errors.New("delete not acknowledged")
|
return errors.New("delete not acknowledged")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
docMap := make(ESDocMap)
|
docMap := make(ESDocMap)
|
||||||
docMap.Add("tid", "integer")
|
docMap.Add("tid", "integer")
|
||||||
docMap.Add("title", "text")
|
docMap.Add("title", "text")
|
||||||
docMap.Add("content", "text")
|
docMap.Add("content", "text")
|
||||||
docMap.Add("createdBy", "integer")
|
docMap.Add("createdBy", "integer")
|
||||||
docMap.Add("ip", "ip")
|
docMap.Add("ip", "ip")
|
||||||
docMap.Add("suggest", "completion")
|
docMap.Add("suggest", "completion")
|
||||||
indexBase := ESIndexBase{ESIndexMappings{ESIndexDoc{docMap}}}
|
indexBase := ESIndexBase{ESIndexMappings{ESIndexDoc{docMap}}}
|
||||||
oBytes, err := json.Marshal(indexBase)
|
oBytes, err := json.Marshal(indexBase)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
createIndex, err := client.CreateIndex("topics").Body(string(oBytes)).Do(context.Background())
|
createIndex, err := client.CreateIndex("topics").Body(string(oBytes)).Do(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !createIndex.Acknowledged {
|
if !createIndex.Acknowledged {
|
||||||
return errors.New("not acknowledged")
|
return errors.New("not acknowledged")
|
||||||
}
|
}
|
||||||
|
|
||||||
exists, err = client.IndexExists("replies").Do(context.Background())
|
exists, err = client.IndexExists("replies").Do(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if exists {
|
if exists {
|
||||||
deleteIndex, err := client.DeleteIndex("replies").Do(context.Background())
|
deleteIndex, err := client.DeleteIndex("replies").Do(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !deleteIndex.Acknowledged {
|
if !deleteIndex.Acknowledged {
|
||||||
return errors.New("delete not acknowledged")
|
return errors.New("delete not acknowledged")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
docMap = make(ESDocMap)
|
docMap = make(ESDocMap)
|
||||||
docMap.Add("rid", "integer")
|
docMap.Add("rid", "integer")
|
||||||
docMap.Add("tid", "integer")
|
docMap.Add("tid", "integer")
|
||||||
docMap.Add("content", "text")
|
docMap.Add("content", "text")
|
||||||
docMap.Add("createdBy", "integer")
|
docMap.Add("createdBy", "integer")
|
||||||
docMap.Add("ip", "ip")
|
docMap.Add("ip", "ip")
|
||||||
docMap.Add("suggest", "completion")
|
docMap.Add("suggest", "completion")
|
||||||
indexBase = ESIndexBase{ESIndexMappings{ESIndexDoc{docMap}}}
|
indexBase = ESIndexBase{ESIndexMappings{ESIndexDoc{docMap}}}
|
||||||
oBytes, err = json.Marshal(indexBase)
|
oBytes, err = json.Marshal(indexBase)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
createIndex, err = client.CreateIndex("replies").Body(string(oBytes)).Do(context.Background())
|
createIndex, err = client.CreateIndex("replies").Body(string(oBytes)).Do(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if !createIndex.Acknowledged {
|
if !createIndex.Acknowledged {
|
||||||
return errors.New("not acknowledged")
|
return errors.New("not acknowledged")
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type ESTopic struct {
|
type ESTopic struct {
|
||||||
ID int `json:"tid"`
|
ID int `json:"tid"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
CreatedBy int `json:"createdBy"`
|
CreatedBy int `json:"createdBy"`
|
||||||
IP string `json:"ip"`
|
IP string `json:"ip"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type ESReply struct {
|
type ESReply struct {
|
||||||
ID int `json:"rid"`
|
ID int `json:"rid"`
|
||||||
TID int `json:"tid"`
|
TID int `json:"tid"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
CreatedBy int `json:"createdBy"`
|
CreatedBy int `json:"createdBy"`
|
||||||
IP string `json:"ip"`
|
IP string `json:"ip"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func setupData(client *elastic.Client) error {
|
func setupData(client *elastic.Client) error {
|
||||||
tcount := 4
|
tcount := 4
|
||||||
errs := make(chan error)
|
errs := make(chan error)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
tin := make([]chan ESTopic, tcount)
|
tin := make([]chan ESTopic, tcount)
|
||||||
tf := func(tin chan ESTopic) {
|
tf := func(tin chan ESTopic) {
|
||||||
for {
|
for {
|
||||||
topic, more := <-tin
|
topic, more := <-tin
|
||||||
if !more {
|
if !more {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
_, err := client.Index().Index("topics").Type("_doc").Id(strconv.Itoa(topic.ID)).BodyJson(topic).Do(context.Background())
|
_, err := client.Index().Index("topics").Type("_doc").Id(strconv.Itoa(topic.ID)).BodyJson(topic).Do(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errs <- err
|
errs <- err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for i := 0; i < 4; i++ {
|
for i := 0; i < 4; i++ {
|
||||||
go tf(tin[i])
|
go tf(tin[i])
|
||||||
}
|
}
|
||||||
|
|
||||||
oi := 0
|
oi := 0
|
||||||
err := qgen.NewAcc().Select("topics").Cols("tid,title,content,createdBy,ip").Each(func(rows *sql.Rows) error {
|
err := qgen.NewAcc().Select("topics").Cols("tid,title,content,createdBy,ip").Each(func(rows *sql.Rows) error {
|
||||||
t := ESTopic{}
|
t := ESTopic{}
|
||||||
err := rows.Scan(&t.ID, &t.Title, &t.Content, &t.CreatedBy, &t.IP)
|
err := rows.Scan(&t.ID, &t.Title, &t.Content, &t.CreatedBy, &t.IP)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
tin[oi] <- t
|
tin[oi] <- t
|
||||||
if oi < 3 {
|
if oi < 3 {
|
||||||
oi++
|
oi++
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
for i := 0; i < 4; i++ {
|
for i := 0; i < 4; i++ {
|
||||||
close(tin[i])
|
close(tin[i])
|
||||||
}
|
}
|
||||||
errs <- err
|
errs <- err
|
||||||
}()
|
}()
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
rin := make([]chan ESReply, tcount)
|
rin := make([]chan ESReply, tcount)
|
||||||
rf := func(rin chan ESReply) {
|
rf := func(rin chan ESReply) {
|
||||||
for {
|
for {
|
||||||
reply, more := <-rin
|
reply, more := <-rin
|
||||||
if !more {
|
if !more {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
_, err := client.Index().Index("replies").Type("_doc").Id(strconv.Itoa(reply.ID)).BodyJson(reply).Do(context.Background())
|
_, err := client.Index().Index("replies").Type("_doc").Id(strconv.Itoa(reply.ID)).BodyJson(reply).Do(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
errs <- err
|
errs <- err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for i := 0; i < 4; i++ {
|
for i := 0; i < 4; i++ {
|
||||||
rf(rin[i])
|
rf(rin[i])
|
||||||
}
|
}
|
||||||
oi := 0
|
oi := 0
|
||||||
err := qgen.NewAcc().Select("replies").Cols("rid,tid,content,createdBy,ip").Each(func(rows *sql.Rows) error {
|
err := qgen.NewAcc().Select("replies").Cols("rid,tid,content,createdBy,ip").Each(func(rows *sql.Rows) error {
|
||||||
r := ESReply{}
|
r := ESReply{}
|
||||||
err := rows.Scan(&r.ID, &r.TID, &r.Content, &r.CreatedBy, &r.IP)
|
err := rows.Scan(&r.ID, &r.TID, &r.Content, &r.CreatedBy, &r.IP)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
rin[oi] <- r
|
rin[oi] <- r
|
||||||
if oi < 3 {
|
if oi < 3 {
|
||||||
oi++
|
oi++
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
for i := 0; i < 4; i++ {
|
for i := 0; i < 4; i++ {
|
||||||
close(rin[i])
|
close(rin[i])
|
||||||
}
|
}
|
||||||
errs <- err
|
errs <- err
|
||||||
}()
|
}()
|
||||||
|
|
||||||
fin := 0
|
fin := 0
|
||||||
for {
|
for {
|
||||||
err := <-errs
|
err := <-errs
|
||||||
if err == nil {
|
if err == nil {
|
||||||
fin++
|
fin++
|
||||||
if fin == 2 {
|
if fin == 2 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,67 +3,67 @@
|
||||||
package main // import "github.com/Azareal/Gosora/hook_gen"
|
package main // import "github.com/Azareal/Gosora/hook_gen"
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
h "github.com/Azareal/Gosora/cmd/common_hook_gen"
|
h "github.com/Azareal/Gosora/cmd/common_hook_gen"
|
||||||
c "github.com/Azareal/Gosora/common"
|
c "github.com/Azareal/Gosora/common"
|
||||||
_ "github.com/Azareal/Gosora/extend"
|
_ "github.com/Azareal/Gosora/extend"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TODO: Make sure all the errors in this file propagate upwards properly
|
// TODO: Make sure all the errors in this file propagate upwards properly
|
||||||
func main() {
|
func main() {
|
||||||
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
|
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
|
||||||
defer func() {
|
defer func() {
|
||||||
if r := recover(); r != nil {
|
if r := recover(); r != nil {
|
||||||
fmt.Println(r)
|
fmt.Println(r)
|
||||||
debug.PrintStack()
|
debug.PrintStack()
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
hooks := make(map[string]int)
|
hooks := make(map[string]int)
|
||||||
for _, pl := range c.Plugins {
|
for _, pl := range c.Plugins {
|
||||||
if len(pl.Meta.Hooks) > 0 {
|
if len(pl.Meta.Hooks) > 0 {
|
||||||
for _, hook := range pl.Meta.Hooks {
|
for _, hook := range pl.Meta.Hooks {
|
||||||
hooks[hook]++
|
hooks[hook]++
|
||||||
}
|
}
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if pl.Init != nil {
|
if pl.Init != nil {
|
||||||
if e := pl.Init(pl); e != nil {
|
if e := pl.Init(pl); e != nil {
|
||||||
log.Print("early plugin init err: ", e)
|
log.Print("early plugin init err: ", e)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if pl.Hooks != nil {
|
if pl.Hooks != nil {
|
||||||
log.Print("Hooks not nil for ", pl.UName)
|
log.Print("Hooks not nil for ", pl.UName)
|
||||||
for hook, _ := range pl.Hooks {
|
for hook, _ := range pl.Hooks {
|
||||||
hooks[hook] += 1
|
hooks[hook] += 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
log.Printf("hooks: %+v\n", hooks)
|
log.Printf("hooks: %+v\n", hooks)
|
||||||
|
|
||||||
imports := []string{"net/http"}
|
imports := []string{"net/http"}
|
||||||
hookVars := h.HookVars{imports, nil}
|
hookVars := h.HookVars{imports, nil}
|
||||||
var params2sb strings.Builder
|
var params2sb strings.Builder
|
||||||
add := func(name, params, ret, htype string, multiHook, skip bool, defaultRet, pure string) {
|
add := func(name, params, ret, htype string, multiHook, skip bool, defaultRet, pure string) {
|
||||||
first := true
|
first := true
|
||||||
for _, param := range strings.Split(params, ",") {
|
for _, param := range strings.Split(params, ",") {
|
||||||
if !first {
|
if !first {
|
||||||
params2sb.WriteRune(',')
|
params2sb.WriteRune(',')
|
||||||
}
|
}
|
||||||
pspl := strings.Split(strings.ReplaceAll(strings.TrimSpace(param), " ", " "), " ")
|
pspl := strings.Split(strings.ReplaceAll(strings.TrimSpace(param), " ", " "), " ")
|
||||||
params2sb.WriteString(pspl[0])
|
params2sb.WriteString(pspl[0])
|
||||||
first = false
|
first = false
|
||||||
}
|
}
|
||||||
hookVars.Hooks = append(hookVars.Hooks, h.Hook{name, params, params2sb.String(), ret, htype, hooks[name] > 0, multiHook, skip, defaultRet, pure})
|
hookVars.Hooks = append(hookVars.Hooks, h.Hook{name, params, params2sb.String(), ret, htype, hooks[name] > 0, multiHook, skip, defaultRet, pure})
|
||||||
params2sb.Reset()
|
params2sb.Reset()
|
||||||
}
|
}
|
||||||
|
|
||||||
h.AddHooks(add)
|
h.AddHooks(add)
|
||||||
h.Write(hookVars)
|
h.Write(hookVars)
|
||||||
log.Println("Successfully generated the hooks")
|
log.Println("Successfully generated the hooks")
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,41 +1,41 @@
|
||||||
package main // import "github.com/Azareal/Gosora/hook_stub_gen"
|
package main // import "github.com/Azareal/Gosora/hook_stub_gen"
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"strings"
|
"strings"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
|
|
||||||
h "github.com/Azareal/Gosora/cmd/common_hook_gen"
|
h "github.com/Azareal/Gosora/cmd/common_hook_gen"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TODO: Make sure all the errors in this file propagate upwards properly
|
// TODO: Make sure all the errors in this file propagate upwards properly
|
||||||
func main() {
|
func main() {
|
||||||
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
|
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
|
||||||
defer func() {
|
defer func() {
|
||||||
if r := recover(); r != nil {
|
if r := recover(); r != nil {
|
||||||
fmt.Println(r)
|
fmt.Println(r)
|
||||||
debug.PrintStack()
|
debug.PrintStack()
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
imports := []string{"net/http"}
|
imports := []string{"net/http"}
|
||||||
hookVars := h.HookVars{imports,nil}
|
hookVars := h.HookVars{imports,nil}
|
||||||
add := func(name, params, ret, htype string, multiHook, skip bool, defaultRet, pure string) {
|
add := func(name, params, ret, htype string, multiHook, skip bool, defaultRet, pure string) {
|
||||||
var params2 string
|
var params2 string
|
||||||
first := true
|
first := true
|
||||||
for _, param := range strings.Split(params,",") {
|
for _, param := range strings.Split(params,",") {
|
||||||
if !first {
|
if !first {
|
||||||
params2 += ","
|
params2 += ","
|
||||||
}
|
}
|
||||||
pspl := strings.Split(strings.ReplaceAll(strings.TrimSpace(param)," "," ")," ")
|
pspl := strings.Split(strings.ReplaceAll(strings.TrimSpace(param)," "," ")," ")
|
||||||
params2 += pspl[0]
|
params2 += pspl[0]
|
||||||
first = false
|
first = false
|
||||||
}
|
}
|
||||||
hookVars.Hooks = append(hookVars.Hooks, h.Hook{name, params, params2, ret, htype, true, multiHook, skip, defaultRet,pure})
|
hookVars.Hooks = append(hookVars.Hooks, h.Hook{name, params, params2, ret, htype, true, multiHook, skip, defaultRet,pure})
|
||||||
}
|
}
|
||||||
|
|
||||||
h.AddHooks(add)
|
h.AddHooks(add)
|
||||||
h.Write(hookVars)
|
h.Write(hookVars)
|
||||||
log.Println("Successfully generated the hooks")
|
log.Println("Successfully generated the hooks")
|
||||||
}
|
}
|
|
@ -7,15 +7,15 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Azareal/Gosora/install"
|
"github.com/Azareal/Gosora/install"
|
||||||
)
|
)
|
||||||
|
|
||||||
var scanner *bufio.Scanner
|
var scanner *bufio.Scanner
|
||||||
|
@ -35,287 +35,287 @@ var defaultsiteURL = "localhost"
|
||||||
var defaultServerPort = "80" // 8080's a good one, if you're testing and don't want it to clash with port 80
|
var defaultServerPort = "80" // 8080's a good one, if you're testing and don't want it to clash with port 80
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
|
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
|
||||||
defer func() {
|
defer func() {
|
||||||
if r := recover(); r != nil {
|
if r := recover(); r != nil {
|
||||||
fmt.Println(r)
|
fmt.Println(r)
|
||||||
debug.PrintStack()
|
debug.PrintStack()
|
||||||
pressAnyKey()
|
pressAnyKey()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
scanner = bufio.NewScanner(os.Stdin)
|
scanner = bufio.NewScanner(os.Stdin)
|
||||||
fmt.Println("Welcome to Gosora's Installer")
|
fmt.Println("Welcome to Gosora's Installer")
|
||||||
fmt.Println("We're going to take you through a few steps to help you get started :)")
|
fmt.Println("We're going to take you through a few steps to help you get started :)")
|
||||||
adap, ok := handleDatabaseDetails()
|
adap, ok := handleDatabaseDetails()
|
||||||
if !ok {
|
if !ok {
|
||||||
err := scanner.Err()
|
err := scanner.Err()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
} else {
|
} else {
|
||||||
err = errors.New("Something went wrong!")
|
err = errors.New("Something went wrong!")
|
||||||
}
|
}
|
||||||
abortError(err)
|
abortError(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if !getSiteDetails() {
|
if !getSiteDetails() {
|
||||||
err := scanner.Err()
|
err := scanner.Err()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
} else {
|
} else {
|
||||||
err = errors.New("Something went wrong!")
|
err = errors.New("Something went wrong!")
|
||||||
}
|
}
|
||||||
abortError(err)
|
abortError(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err := adap.InitDatabase()
|
err := adap.InitDatabase()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
abortError(err)
|
abortError(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err = adap.TableDefs()
|
err = adap.TableDefs()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
abortError(err)
|
abortError(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err = adap.CreateAdmin()
|
err = adap.CreateAdmin()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
abortError(err)
|
abortError(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
err = adap.InitialData()
|
err = adap.InitialData()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
abortError(err)
|
abortError(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
configContents := []byte(`{
|
configContents := []byte(`{
|
||||||
"Site": {
|
"Site": {
|
||||||
"ShortName":"` + siteShortName + `",
|
"ShortName":"` + siteShortName + `",
|
||||||
"Name":"` + siteName + `",
|
"Name":"` + siteName + `",
|
||||||
"URL":"` + siteURL + `",
|
"URL":"` + siteURL + `",
|
||||||
"Port":"` + serverPort + `",
|
"Port":"` + serverPort + `",
|
||||||
"EnableSsl":false,
|
"EnableSsl":false,
|
||||||
"EnableEmails":false,
|
"EnableEmails":false,
|
||||||
"HasProxy":false,
|
"HasProxy":false,
|
||||||
"Language": "english"
|
"Language": "english"
|
||||||
},
|
},
|
||||||
"Config": {
|
"Config": {
|
||||||
"SslPrivkey": "",
|
"SslPrivkey": "",
|
||||||
"SslFullchain": "",
|
"SslFullchain": "",
|
||||||
"SMTPServer": "",
|
"SMTPServer": "",
|
||||||
"SMTPUsername": "",
|
"SMTPUsername": "",
|
||||||
"SMTPPassword": "",
|
"SMTPPassword": "",
|
||||||
"SMTPPort": "25",
|
"SMTPPort": "25",
|
||||||
|
|
||||||
"MaxRequestSizeStr":"5MB",
|
"MaxRequestSizeStr":"5MB",
|
||||||
"UserCache":"static",
|
"UserCache":"static",
|
||||||
"TopicCache":"static",
|
"TopicCache":"static",
|
||||||
"ReplyCache":"static",
|
"ReplyCache":"static",
|
||||||
"UserCacheCapacity":180,
|
"UserCacheCapacity":180,
|
||||||
"TopicCacheCapacity":400,
|
"TopicCacheCapacity":400,
|
||||||
"ReplyCacheCapacity":20,
|
"ReplyCacheCapacity":20,
|
||||||
"DefaultPath":"/topics/",
|
"DefaultPath":"/topics/",
|
||||||
"DefaultGroup":3,
|
"DefaultGroup":3,
|
||||||
"ActivationGroup":5,
|
"ActivationGroup":5,
|
||||||
"StaffCSS":"staff_post",
|
"StaffCSS":"staff_post",
|
||||||
"DefaultForum":2,
|
"DefaultForum":2,
|
||||||
"MinifyTemplates":true,
|
"MinifyTemplates":true,
|
||||||
"BuildSlugs":true,
|
"BuildSlugs":true,
|
||||||
"ServerCount":1,
|
"ServerCount":1,
|
||||||
"Noavatar":"https://api.adorable.io/avatars/{width}/{id}.png",
|
"Noavatar":"https://api.adorable.io/avatars/{width}/{id}.png",
|
||||||
"ItemsPerPage":25
|
"ItemsPerPage":25
|
||||||
},
|
},
|
||||||
"Database": {
|
"Database": {
|
||||||
"Adapter": "` + adap.Name() + `",
|
"Adapter": "` + adap.Name() + `",
|
||||||
"Host": "` + adap.DBHost() + `",
|
"Host": "` + adap.DBHost() + `",
|
||||||
"Username": "` + adap.DBUsername() + `",
|
"Username": "` + adap.DBUsername() + `",
|
||||||
"Password": "` + adap.DBPassword() + `",
|
"Password": "` + adap.DBPassword() + `",
|
||||||
"Dbname": "` + adap.DBName() + `",
|
"Dbname": "` + adap.DBName() + `",
|
||||||
"Port": "` + adap.DBPort() + `",
|
"Port": "` + adap.DBPort() + `",
|
||||||
|
|
||||||
"TestAdapter": "` + adap.Name() + `",
|
"TestAdapter": "` + adap.Name() + `",
|
||||||
"TestHost": "",
|
"TestHost": "",
|
||||||
"TestUsername": "",
|
"TestUsername": "",
|
||||||
"TestPassword": "",
|
"TestPassword": "",
|
||||||
"TestDbname": "",
|
"TestDbname": "",
|
||||||
"TestPort": ""
|
"TestPort": ""
|
||||||
},
|
},
|
||||||
"Dev": {
|
"Dev": {
|
||||||
"DebugMode":true,
|
"DebugMode":true,
|
||||||
"SuperDebug":false
|
"SuperDebug":false
|
||||||
}
|
}
|
||||||
}`)
|
}`)
|
||||||
|
|
||||||
fmt.Println("Opening the configuration file")
|
fmt.Println("Opening the configuration file")
|
||||||
configFile, err := os.Create("./config/config.json")
|
configFile, err := os.Create("./config/config.json")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
abortError(err)
|
abortError(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println("Writing to the configuration file...")
|
fmt.Println("Writing to the configuration file...")
|
||||||
_, err = configFile.Write(configContents)
|
_, err = configFile.Write(configContents)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
abortError(err)
|
abortError(err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
configFile.Sync()
|
configFile.Sync()
|
||||||
configFile.Close()
|
configFile.Close()
|
||||||
fmt.Println("Finished writing to the configuration file")
|
fmt.Println("Finished writing to the configuration file")
|
||||||
|
|
||||||
fmt.Println("Yay, you have successfully installed Gosora!")
|
fmt.Println("Yay, you have successfully installed Gosora!")
|
||||||
fmt.Println("Your name is Admin and you can login with the password 'password'. Don't forget to change it! Seriously. It's really insecure.")
|
fmt.Println("Your name is Admin and you can login with the password 'password'. Don't forget to change it! Seriously. It's really insecure.")
|
||||||
pressAnyKey()
|
pressAnyKey()
|
||||||
}
|
}
|
||||||
|
|
||||||
func abortError(err error) {
|
func abortError(err error) {
|
||||||
fmt.Println(err)
|
fmt.Println(err)
|
||||||
fmt.Println("Aborting installation...")
|
fmt.Println("Aborting installation...")
|
||||||
pressAnyKey()
|
pressAnyKey()
|
||||||
}
|
}
|
||||||
|
|
||||||
func handleDatabaseDetails() (adap install.InstallAdapter, ok bool) {
|
func handleDatabaseDetails() (adap install.InstallAdapter, ok bool) {
|
||||||
var dbAdapter string
|
var dbAdapter string
|
||||||
var dbHost string
|
var dbHost string
|
||||||
var dbUsername string
|
var dbUsername string
|
||||||
var dbPassword string
|
var dbPassword string
|
||||||
var dbName string
|
var dbName string
|
||||||
// TODO: Let the admin set the database port?
|
// TODO: Let the admin set the database port?
|
||||||
//var dbPort string
|
//var dbPort string
|
||||||
|
|
||||||
for {
|
for {
|
||||||
fmt.Println("Which database adapter do you wish to use? mysql or mssql? Default: mysql")
|
fmt.Println("Which database adapter do you wish to use? mysql or mssql? Default: mysql")
|
||||||
if !scanner.Scan() {
|
if !scanner.Scan() {
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
dbAdapter := strings.TrimSpace(scanner.Text())
|
dbAdapter := strings.TrimSpace(scanner.Text())
|
||||||
if dbAdapter == "" {
|
if dbAdapter == "" {
|
||||||
dbAdapter = defaultAdapter
|
dbAdapter = defaultAdapter
|
||||||
}
|
}
|
||||||
adap, ok = install.Lookup(dbAdapter)
|
adap, ok = install.Lookup(dbAdapter)
|
||||||
if ok {
|
if ok {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
fmt.Println("That adapter doesn't exist")
|
fmt.Println("That adapter doesn't exist")
|
||||||
}
|
}
|
||||||
fmt.Println("Set database adapter to " + dbAdapter)
|
fmt.Println("Set database adapter to " + dbAdapter)
|
||||||
|
|
||||||
fmt.Println("Database Host? Default: " + defaultHost)
|
fmt.Println("Database Host? Default: " + defaultHost)
|
||||||
if !scanner.Scan() {
|
if !scanner.Scan() {
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
dbHost = scanner.Text()
|
dbHost = scanner.Text()
|
||||||
if dbHost == "" {
|
if dbHost == "" {
|
||||||
dbHost = defaultHost
|
dbHost = defaultHost
|
||||||
}
|
}
|
||||||
fmt.Println("Set database host to " + dbHost)
|
fmt.Println("Set database host to " + dbHost)
|
||||||
|
|
||||||
fmt.Println("Database Username? Default: " + defaultUsername)
|
fmt.Println("Database Username? Default: " + defaultUsername)
|
||||||
if !scanner.Scan() {
|
if !scanner.Scan() {
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
dbUsername = scanner.Text()
|
dbUsername = scanner.Text()
|
||||||
if dbUsername == "" {
|
if dbUsername == "" {
|
||||||
dbUsername = defaultUsername
|
dbUsername = defaultUsername
|
||||||
}
|
}
|
||||||
fmt.Println("Set database username to " + dbUsername)
|
fmt.Println("Set database username to " + dbUsername)
|
||||||
|
|
||||||
fmt.Println("Database Password? Default: ''")
|
fmt.Println("Database Password? Default: ''")
|
||||||
if !scanner.Scan() {
|
if !scanner.Scan() {
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
dbPassword = scanner.Text()
|
dbPassword = scanner.Text()
|
||||||
if len(dbPassword) == 0 {
|
if len(dbPassword) == 0 {
|
||||||
fmt.Println("You didn't set a password for this user. This won't block the installation process, but it might create security issues in the future.")
|
fmt.Println("You didn't set a password for this user. This won't block the installation process, but it might create security issues in the future.")
|
||||||
fmt.Println("")
|
fmt.Println("")
|
||||||
} else {
|
} else {
|
||||||
fmt.Println("Set password to " + obfuscatePassword(dbPassword))
|
fmt.Println("Set password to " + obfuscatePassword(dbPassword))
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println("Database Name? Pick a name you like or one provided to you. Default: " + defaultDbname)
|
fmt.Println("Database Name? Pick a name you like or one provided to you. Default: " + defaultDbname)
|
||||||
if !scanner.Scan() {
|
if !scanner.Scan() {
|
||||||
return nil, false
|
return nil, false
|
||||||
}
|
}
|
||||||
dbName = scanner.Text()
|
dbName = scanner.Text()
|
||||||
if dbName == "" {
|
if dbName == "" {
|
||||||
dbName = defaultDbname
|
dbName = defaultDbname
|
||||||
}
|
}
|
||||||
fmt.Println("Set database name to " + dbName)
|
fmt.Println("Set database name to " + dbName)
|
||||||
|
|
||||||
adap.SetConfig(dbHost, dbUsername, dbPassword, dbName, adap.DefaultPort())
|
adap.SetConfig(dbHost, dbUsername, dbPassword, dbName, adap.DefaultPort())
|
||||||
return adap, true
|
return adap, true
|
||||||
}
|
}
|
||||||
|
|
||||||
func getSiteDetails() bool {
|
func getSiteDetails() bool {
|
||||||
fmt.Println("Okay. We also need to know some actual information about your site!")
|
fmt.Println("Okay. We also need to know some actual information about your site!")
|
||||||
fmt.Println("What's your site's name? Default: " + defaultSiteName)
|
fmt.Println("What's your site's name? Default: " + defaultSiteName)
|
||||||
if !scanner.Scan() {
|
if !scanner.Scan() {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
siteName = scanner.Text()
|
siteName = scanner.Text()
|
||||||
if siteName == "" {
|
if siteName == "" {
|
||||||
siteName = defaultSiteName
|
siteName = defaultSiteName
|
||||||
}
|
}
|
||||||
fmt.Println("Set the site name to " + siteName)
|
fmt.Println("Set the site name to " + siteName)
|
||||||
|
|
||||||
// ? - We could compute this based on the first letter of each word in the site's name, if it's name spans multiple words. I'm not sure how to do this for single word names.
|
// ? - We could compute this based on the first letter of each word in the site's name, if it's name spans multiple words. I'm not sure how to do this for single word names.
|
||||||
fmt.Println("Can we have a short abbreviation for your site? Default: " + defaultSiteShortName)
|
fmt.Println("Can we have a short abbreviation for your site? Default: " + defaultSiteShortName)
|
||||||
if !scanner.Scan() {
|
if !scanner.Scan() {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
siteShortName = scanner.Text()
|
siteShortName = scanner.Text()
|
||||||
if siteShortName == "" {
|
if siteShortName == "" {
|
||||||
siteShortName = defaultSiteShortName
|
siteShortName = defaultSiteShortName
|
||||||
}
|
}
|
||||||
fmt.Println("Set the short name to " + siteShortName)
|
fmt.Println("Set the short name to " + siteShortName)
|
||||||
|
|
||||||
fmt.Println("What's your site's url? Default: " + defaultsiteURL)
|
fmt.Println("What's your site's url? Default: " + defaultsiteURL)
|
||||||
if !scanner.Scan() {
|
if !scanner.Scan() {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
siteURL = scanner.Text()
|
siteURL = scanner.Text()
|
||||||
if siteURL == "" {
|
if siteURL == "" {
|
||||||
siteURL = defaultsiteURL
|
siteURL = defaultsiteURL
|
||||||
}
|
}
|
||||||
fmt.Println("Set the site url to " + siteURL)
|
fmt.Println("Set the site url to " + siteURL)
|
||||||
|
|
||||||
fmt.Println("What port do you want the server to listen on? If you don't know what this means, you should probably leave it on the default. Default: " + defaultServerPort)
|
fmt.Println("What port do you want the server to listen on? If you don't know what this means, you should probably leave it on the default. Default: " + defaultServerPort)
|
||||||
if !scanner.Scan() {
|
if !scanner.Scan() {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
serverPort = scanner.Text()
|
serverPort = scanner.Text()
|
||||||
if serverPort == "" {
|
if serverPort == "" {
|
||||||
serverPort = defaultServerPort
|
serverPort = defaultServerPort
|
||||||
}
|
}
|
||||||
_, err := strconv.Atoi(serverPort)
|
_, err := strconv.Atoi(serverPort)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("That's not a valid number!")
|
fmt.Println("That's not a valid number!")
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
fmt.Println("Set the server port to " + serverPort)
|
fmt.Println("Set the server port to " + serverPort)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func obfuscatePassword(password string) (out string) {
|
func obfuscatePassword(password string) (out string) {
|
||||||
for i := 0; i < len(password); i++ {
|
for i := 0; i < len(password); i++ {
|
||||||
out += "*"
|
out += "*"
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}
|
}
|
||||||
|
|
||||||
func pressAnyKey() {
|
func pressAnyKey() {
|
||||||
//fmt.Println("Press any key to exit...")
|
//fmt.Println("Press any key to exit...")
|
||||||
fmt.Println("Please press enter to exit...")
|
fmt.Println("Please press enter to exit...")
|
||||||
for scanner.Scan() {
|
for scanner.Scan() {
|
||||||
_ = scanner.Text()
|
_ = scanner.Text()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,8 +2,8 @@
|
||||||
echo Building the query generator
|
echo Building the query generator
|
||||||
go build -ldflags="-s -w"
|
go build -ldflags="-s -w"
|
||||||
if %errorlevel% neq 0 (
|
if %errorlevel% neq 0 (
|
||||||
pause
|
pause
|
||||||
exit /b %errorlevel%
|
exit /b %errorlevel%
|
||||||
)
|
)
|
||||||
echo The query generator was successfully built
|
echo The query generator was successfully built
|
||||||
pause
|
pause
|
|
@ -2,407 +2,407 @@
|
||||||
package main // import "github.com/Azareal/Gosora/query_gen"
|
package main // import "github.com/Azareal/Gosora/query_gen"
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
c "github.com/Azareal/Gosora/common"
|
c "github.com/Azareal/Gosora/common"
|
||||||
qgen "github.com/Azareal/Gosora/query_gen"
|
qgen "github.com/Azareal/Gosora/query_gen"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TODO: Make sure all the errors in this file propagate upwards properly
|
// TODO: Make sure all the errors in this file propagate upwards properly
|
||||||
func main() {
|
func main() {
|
||||||
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
|
// Capture panics instead of closing the window at a superhuman speed before the user can read the message on Windows
|
||||||
defer func() {
|
defer func() {
|
||||||
if r := recover(); r != nil {
|
if r := recover(); r != nil {
|
||||||
fmt.Println(r)
|
fmt.Println(r)
|
||||||
debug.PrintStack()
|
debug.PrintStack()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
log.Println("Running the query generator")
|
log.Println("Running the query generator")
|
||||||
for _, a := range qgen.Registry {
|
for _, a := range qgen.Registry {
|
||||||
log.Printf("Building the queries for the %s adapter", a.GetName())
|
log.Printf("Building the queries for the %s adapter", a.GetName())
|
||||||
qgen.Install.SetAdapterInstance(a)
|
qgen.Install.SetAdapterInstance(a)
|
||||||
qgen.Install.AddPlugins(NewPrimaryKeySpitter()) // TODO: Do we really need to fill the spitter for every adapter?
|
qgen.Install.AddPlugins(NewPrimaryKeySpitter()) // TODO: Do we really need to fill the spitter for every adapter?
|
||||||
|
|
||||||
e := writeStatements(a)
|
e := writeStatements(a)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
log.Print(e)
|
log.Print(e)
|
||||||
}
|
}
|
||||||
e = qgen.Install.Write()
|
e = qgen.Install.Write()
|
||||||
if e != nil {
|
if e != nil {
|
||||||
log.Print(e)
|
log.Print(e)
|
||||||
}
|
}
|
||||||
e = a.Write()
|
e = a.Write()
|
||||||
if e != nil {
|
if e != nil {
|
||||||
log.Print(e)
|
log.Print(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// nolint
|
// nolint
|
||||||
func writeStatements(a qgen.Adapter) (err error) {
|
func writeStatements(a qgen.Adapter) (err error) {
|
||||||
e := func(f func(qgen.Adapter) error) {
|
e := func(f func(qgen.Adapter) error) {
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = f(a)
|
err = f(a)
|
||||||
}
|
}
|
||||||
e(createTables)
|
e(createTables)
|
||||||
e(seedTables)
|
e(seedTables)
|
||||||
e(writeSelects)
|
e(writeSelects)
|
||||||
e(writeLeftJoins)
|
e(writeLeftJoins)
|
||||||
e(writeInnerJoins)
|
e(writeInnerJoins)
|
||||||
e(writeInserts)
|
e(writeInserts)
|
||||||
e(writeUpdates)
|
e(writeUpdates)
|
||||||
e(writeDeletes)
|
e(writeDeletes)
|
||||||
e(writeSimpleCounts)
|
e(writeSimpleCounts)
|
||||||
e(writeInsertSelects)
|
e(writeInsertSelects)
|
||||||
e(writeInsertLeftJoins)
|
e(writeInsertLeftJoins)
|
||||||
e(writeInsertInnerJoins)
|
e(writeInsertInnerJoins)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
type si = map[string]interface{}
|
type si = map[string]interface{}
|
||||||
type tK = tblKey
|
type tK = tblKey
|
||||||
|
|
||||||
func seedTables(a qgen.Adapter) error {
|
func seedTables(a qgen.Adapter) error {
|
||||||
qgen.Install.AddIndex("topics", "parentID", "parentID")
|
qgen.Install.AddIndex("topics", "parentID", "parentID")
|
||||||
qgen.Install.AddIndex("replies", "tid", "tid")
|
qgen.Install.AddIndex("replies", "tid", "tid")
|
||||||
qgen.Install.AddIndex("polls", "parentID", "parentID")
|
qgen.Install.AddIndex("polls", "parentID", "parentID")
|
||||||
qgen.Install.AddIndex("likes", "targetItem", "targetItem")
|
qgen.Install.AddIndex("likes", "targetItem", "targetItem")
|
||||||
qgen.Install.AddIndex("emails", "uid", "uid")
|
qgen.Install.AddIndex("emails", "uid", "uid")
|
||||||
qgen.Install.AddIndex("attachments", "originID", "originID")
|
qgen.Install.AddIndex("attachments", "originID", "originID")
|
||||||
qgen.Install.AddIndex("attachments", "path", "path")
|
qgen.Install.AddIndex("attachments", "path", "path")
|
||||||
qgen.Install.AddIndex("activity_stream_matches", "watcher", "watcher")
|
qgen.Install.AddIndex("activity_stream_matches", "watcher", "watcher")
|
||||||
// TODO: Remove these keys to save space when Elasticsearch is active?
|
// TODO: Remove these keys to save space when Elasticsearch is active?
|
||||||
//qgen.Install.AddKey("topics", "title", tK{"title", "fulltext", "", false})
|
//qgen.Install.AddKey("topics", "title", tK{"title", "fulltext", "", false})
|
||||||
//qgen.Install.AddKey("topics", "content", tK{"content", "fulltext", "", false})
|
//qgen.Install.AddKey("topics", "content", tK{"content", "fulltext", "", false})
|
||||||
//qgen.Install.AddKey("topics", "title,content", tK{"title,content", "fulltext", "", false})
|
//qgen.Install.AddKey("topics", "title,content", tK{"title,content", "fulltext", "", false})
|
||||||
//qgen.Install.AddKey("replies", "content", tK{"content", "fulltext", "", false})
|
//qgen.Install.AddKey("replies", "content", tK{"content", "fulltext", "", false})
|
||||||
|
|
||||||
insert := func(tbl, cols, vals string) {
|
insert := func(tbl, cols, vals string) {
|
||||||
qgen.Install.SimpleInsert(tbl, cols, vals)
|
qgen.Install.SimpleInsert(tbl, cols, vals)
|
||||||
}
|
}
|
||||||
insert("sync", "last_update", "UTC_TIMESTAMP()")
|
insert("sync", "last_update", "UTC_TIMESTAMP()")
|
||||||
addSetting := func(name, content, stype string, constraints ...string) {
|
addSetting := func(name, content, stype string, constraints ...string) {
|
||||||
if strings.Contains(name, "'") {
|
if strings.Contains(name, "'") {
|
||||||
panic("name contains '")
|
panic("name contains '")
|
||||||
}
|
}
|
||||||
if strings.Contains(stype, "'") {
|
if strings.Contains(stype, "'") {
|
||||||
panic("stype contains '")
|
panic("stype contains '")
|
||||||
}
|
}
|
||||||
// TODO: Add more field validators
|
// TODO: Add more field validators
|
||||||
cols := "name,content,type"
|
cols := "name,content,type"
|
||||||
if len(constraints) > 0 {
|
if len(constraints) > 0 {
|
||||||
cols += ",constraints"
|
cols += ",constraints"
|
||||||
}
|
}
|
||||||
q := func(s string) string {
|
q := func(s string) string {
|
||||||
return "'" + s + "'"
|
return "'" + s + "'"
|
||||||
}
|
}
|
||||||
c := func() string {
|
c := func() string {
|
||||||
if len(constraints) == 0 {
|
if len(constraints) == 0 {
|
||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
return "," + q(constraints[0])
|
return "," + q(constraints[0])
|
||||||
}
|
}
|
||||||
insert("settings", cols, q(name)+","+q(content)+","+q(stype)+c())
|
insert("settings", cols, q(name)+","+q(content)+","+q(stype)+c())
|
||||||
}
|
}
|
||||||
addSetting("activation_type", "1", "list", "1-3")
|
addSetting("activation_type", "1", "list", "1-3")
|
||||||
addSetting("bigpost_min_words", "250", "int")
|
addSetting("bigpost_min_words", "250", "int")
|
||||||
addSetting("megapost_min_words", "1000", "int")
|
addSetting("megapost_min_words", "1000", "int")
|
||||||
addSetting("meta_desc", "", "html-attribute")
|
addSetting("meta_desc", "", "html-attribute")
|
||||||
addSetting("rapid_loading", "1", "bool")
|
addSetting("rapid_loading", "1", "bool")
|
||||||
addSetting("google_site_verify", "", "html-attribute")
|
addSetting("google_site_verify", "", "html-attribute")
|
||||||
addSetting("avatar_visibility", "0", "list", "0-1")
|
addSetting("avatar_visibility", "0", "list", "0-1")
|
||||||
insert("themes", "uname, default", "'cosora',1")
|
insert("themes", "uname, default", "'cosora',1")
|
||||||
insert("emails", "email, uid, validated", "'admin@localhost',1,1") // ? - Use a different default email or let the admin input it during installation?
|
insert("emails", "email, uid, validated", "'admin@localhost',1,1") // ? - Use a different default email or let the admin input it during installation?
|
||||||
|
|
||||||
/*
|
/*
|
||||||
The Permissions:
|
The Permissions:
|
||||||
|
|
||||||
Global Permissions:
|
Global Permissions:
|
||||||
BanUsers
|
BanUsers
|
||||||
ActivateUsers
|
ActivateUsers
|
||||||
EditUser
|
EditUser
|
||||||
EditUserEmail
|
EditUserEmail
|
||||||
EditUserPassword
|
EditUserPassword
|
||||||
EditUserGroup
|
EditUserGroup
|
||||||
EditUserGroupSuperMod
|
EditUserGroupSuperMod
|
||||||
EditUserGroupAdmin
|
EditUserGroupAdmin
|
||||||
EditGroup
|
EditGroup
|
||||||
EditGroupLocalPerms
|
EditGroupLocalPerms
|
||||||
EditGroupGlobalPerms
|
EditGroupGlobalPerms
|
||||||
EditGroupSuperMod
|
EditGroupSuperMod
|
||||||
EditGroupAdmin
|
EditGroupAdmin
|
||||||
ManageForums
|
ManageForums
|
||||||
EditSettings
|
EditSettings
|
||||||
ManageThemes
|
ManageThemes
|
||||||
ManagePlugins
|
ManagePlugins
|
||||||
ViewAdminLogs
|
ViewAdminLogs
|
||||||
ViewIPs
|
ViewIPs
|
||||||
|
|
||||||
Non-staff Global Permissions:
|
Non-staff Global Permissions:
|
||||||
UploadFiles
|
UploadFiles
|
||||||
UploadAvatars
|
UploadAvatars
|
||||||
UseConvos
|
UseConvos
|
||||||
UseConvosOnlyWithMod
|
UseConvosOnlyWithMod
|
||||||
CreateProfileReply
|
CreateProfileReply
|
||||||
AutoEmbed
|
AutoEmbed
|
||||||
AutoLink
|
AutoLink
|
||||||
// CreateConvo ?
|
// CreateConvo ?
|
||||||
// CreateConvoReply ?
|
// CreateConvoReply ?
|
||||||
|
|
||||||
Forum Permissions:
|
Forum Permissions:
|
||||||
ViewTopic
|
ViewTopic
|
||||||
LikeItem
|
LikeItem
|
||||||
CreateTopic
|
CreateTopic
|
||||||
EditTopic
|
EditTopic
|
||||||
DeleteTopic
|
DeleteTopic
|
||||||
CreateReply
|
CreateReply
|
||||||
EditReply
|
EditReply
|
||||||
DeleteReply
|
DeleteReply
|
||||||
PinTopic
|
PinTopic
|
||||||
CloseTopic
|
CloseTopic
|
||||||
MoveTopic
|
MoveTopic
|
||||||
*/
|
*/
|
||||||
|
|
||||||
p := func(perms *c.Perms) string {
|
p := func(perms *c.Perms) string {
|
||||||
jBytes, err := json.Marshal(perms)
|
jBytes, err := json.Marshal(perms)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
return string(jBytes)
|
return string(jBytes)
|
||||||
}
|
}
|
||||||
addGroup := func(name string, perms c.Perms, mod, admin, banned bool, tag string) {
|
addGroup := func(name string, perms c.Perms, mod, admin, banned bool, tag string) {
|
||||||
mi, ai, bi := "0", "0", "0"
|
mi, ai, bi := "0", "0", "0"
|
||||||
if mod {
|
if mod {
|
||||||
mi = "1"
|
mi = "1"
|
||||||
}
|
}
|
||||||
if admin {
|
if admin {
|
||||||
ai = "1"
|
ai = "1"
|
||||||
}
|
}
|
||||||
if banned {
|
if banned {
|
||||||
bi = "1"
|
bi = "1"
|
||||||
}
|
}
|
||||||
insert("users_groups", "name, permissions, plugin_perms, is_mod, is_admin, is_banned, tag", `'`+name+`','`+p(&perms)+`','{}',`+mi+`,`+ai+`,`+bi+`,"`+tag+`"`)
|
insert("users_groups", "name, permissions, plugin_perms, is_mod, is_admin, is_banned, tag", `'`+name+`','`+p(&perms)+`','{}',`+mi+`,`+ai+`,`+bi+`,"`+tag+`"`)
|
||||||
}
|
}
|
||||||
|
|
||||||
perms := c.AllPerms
|
perms := c.AllPerms
|
||||||
perms.EditUserGroupAdmin = false
|
perms.EditUserGroupAdmin = false
|
||||||
perms.EditGroupAdmin = false
|
perms.EditGroupAdmin = false
|
||||||
addGroup("Administrator", perms, true, true, false, "Admin")
|
addGroup("Administrator", perms, true, true, false, "Admin")
|
||||||
|
|
||||||
perms = c.Perms{BanUsers: true, ActivateUsers: true, EditUser: true, EditUserEmail: false, EditUserGroup: true, ViewIPs: true, UploadFiles: true, UploadAvatars: true, UseConvos: true, UseConvosOnlyWithMod: true, CreateProfileReply: true, AutoEmbed: true, AutoLink: true, ViewTopic: true, LikeItem: true, CreateTopic: true, EditTopic: true, DeleteTopic: true, CreateReply: true, EditReply: true, DeleteReply: true, PinTopic: true, CloseTopic: true, MoveTopic: true}
|
perms = c.Perms{BanUsers: true, ActivateUsers: true, EditUser: true, EditUserEmail: false, EditUserGroup: true, ViewIPs: true, UploadFiles: true, UploadAvatars: true, UseConvos: true, UseConvosOnlyWithMod: true, CreateProfileReply: true, AutoEmbed: true, AutoLink: true, ViewTopic: true, LikeItem: true, CreateTopic: true, EditTopic: true, DeleteTopic: true, CreateReply: true, EditReply: true, DeleteReply: true, PinTopic: true, CloseTopic: true, MoveTopic: true}
|
||||||
addGroup("Moderator", perms, true, false, false, "Mod")
|
addGroup("Moderator", perms, true, false, false, "Mod")
|
||||||
|
|
||||||
perms = c.Perms{UploadFiles: true, UploadAvatars: true, UseConvos: true, UseConvosOnlyWithMod: true, CreateProfileReply: true, AutoEmbed: true, AutoLink: true, ViewTopic: true, LikeItem: true, CreateTopic: true, CreateReply: true}
|
perms = c.Perms{UploadFiles: true, UploadAvatars: true, UseConvos: true, UseConvosOnlyWithMod: true, CreateProfileReply: true, AutoEmbed: true, AutoLink: true, ViewTopic: true, LikeItem: true, CreateTopic: true, CreateReply: true}
|
||||||
addGroup("Member", perms, false, false, false, "")
|
addGroup("Member", perms, false, false, false, "")
|
||||||
|
|
||||||
perms = c.Perms{ViewTopic: true}
|
perms = c.Perms{ViewTopic: true}
|
||||||
addGroup("Banned", perms, false, false, true, "")
|
addGroup("Banned", perms, false, false, true, "")
|
||||||
addGroup("Awaiting Activation", c.Perms{ViewTopic: true, UseConvosOnlyWithMod: true}, false, false, false, "")
|
addGroup("Awaiting Activation", c.Perms{ViewTopic: true, UseConvosOnlyWithMod: true}, false, false, false, "")
|
||||||
addGroup("Not Loggedin", perms, false, false, false, "Guest")
|
addGroup("Not Loggedin", perms, false, false, false, "Guest")
|
||||||
|
|
||||||
//
|
//
|
||||||
// TODO: Stop processFields() from stripping the spaces in the descriptions in the next commit
|
// TODO: Stop processFields() from stripping the spaces in the descriptions in the next commit
|
||||||
|
|
||||||
insert("forums", "name, active, desc, tmpl", "'Reports',0,'All the reports go here',''")
|
insert("forums", "name, active, desc, tmpl", "'Reports',0,'All the reports go here',''")
|
||||||
insert("forums", "name, lastTopicID, lastReplyerID, desc, tmpl", "'General',1,1,'A place for general discussions which don't fit elsewhere',''")
|
insert("forums", "name, lastTopicID, lastReplyerID, desc, tmpl", "'General',1,1,'A place for general discussions which don't fit elsewhere',''")
|
||||||
|
|
||||||
//
|
//
|
||||||
|
|
||||||
/*var addForumPerm = func(gid, fid int, permStr string) {
|
/*var addForumPerm = func(gid, fid int, permStr string) {
|
||||||
insert("forums_permissions", "gid, fid, permissions", strconv.Itoa(gid)+`,`+strconv.Itoa(fid)+`,'`+permStr+`'`)
|
insert("forums_permissions", "gid, fid, permissions", strconv.Itoa(gid)+`,`+strconv.Itoa(fid)+`,'`+permStr+`'`)
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
insert("forums_permissions", "gid, fid, permissions", `1,1,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"PinTopic":true,"CloseTopic":true}'`)
|
insert("forums_permissions", "gid, fid, permissions", `1,1,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"PinTopic":true,"CloseTopic":true}'`)
|
||||||
insert("forums_permissions", "gid, fid, permissions", `2,1,'{"ViewTopic":true,"CreateReply":true,"CloseTopic":true}'`)
|
insert("forums_permissions", "gid, fid, permissions", `2,1,'{"ViewTopic":true,"CreateReply":true,"CloseTopic":true}'`)
|
||||||
insert("forums_permissions", "gid, fid, permissions", "3,1,'{}'")
|
insert("forums_permissions", "gid, fid, permissions", "3,1,'{}'")
|
||||||
insert("forums_permissions", "gid, fid, permissions", "4,1,'{}'")
|
insert("forums_permissions", "gid, fid, permissions", "4,1,'{}'")
|
||||||
insert("forums_permissions", "gid, fid, permissions", "5,1,'{}'")
|
insert("forums_permissions", "gid, fid, permissions", "5,1,'{}'")
|
||||||
insert("forums_permissions", "gid, fid, permissions", "6,1,'{}'")
|
insert("forums_permissions", "gid, fid, permissions", "6,1,'{}'")
|
||||||
|
|
||||||
//
|
//
|
||||||
|
|
||||||
insert("forums_permissions", "gid, fid, permissions", `1,2,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"LikeItem":true,"EditTopic":true,"DeleteTopic":true,"EditReply":true,"DeleteReply":true,"PinTopic":true,"CloseTopic":true,"MoveTopic":true}'`)
|
insert("forums_permissions", "gid, fid, permissions", `1,2,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"LikeItem":true,"EditTopic":true,"DeleteTopic":true,"EditReply":true,"DeleteReply":true,"PinTopic":true,"CloseTopic":true,"MoveTopic":true}'`)
|
||||||
|
|
||||||
insert("forums_permissions", "gid, fid, permissions", `2,2,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"LikeItem":true,"EditTopic":true,"DeleteTopic":true,"EditReply":true,"DeleteReply":true,"PinTopic":true,"CloseTopic":true,"MoveTopic":true}'`)
|
insert("forums_permissions", "gid, fid, permissions", `2,2,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"LikeItem":true,"EditTopic":true,"DeleteTopic":true,"EditReply":true,"DeleteReply":true,"PinTopic":true,"CloseTopic":true,"MoveTopic":true}'`)
|
||||||
|
|
||||||
insert("forums_permissions", "gid, fid, permissions", `3,2,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"LikeItem":true}'`)
|
insert("forums_permissions", "gid, fid, permissions", `3,2,'{"ViewTopic":true,"CreateReply":true,"CreateTopic":true,"LikeItem":true}'`)
|
||||||
|
|
||||||
insert("forums_permissions", "gid, fid, permissions", `4,2,'{"ViewTopic":true}'`)
|
insert("forums_permissions", "gid, fid, permissions", `4,2,'{"ViewTopic":true}'`)
|
||||||
|
|
||||||
insert("forums_permissions", "gid, fid, permissions", `5,2,'{"ViewTopic":true}'`)
|
insert("forums_permissions", "gid, fid, permissions", `5,2,'{"ViewTopic":true}'`)
|
||||||
|
|
||||||
insert("forums_permissions", "gid, fid, permissions", `6,2,'{"ViewTopic":true}'`)
|
insert("forums_permissions", "gid, fid, permissions", `6,2,'{"ViewTopic":true}'`)
|
||||||
|
|
||||||
//
|
//
|
||||||
|
|
||||||
insert("topics", "title, content, parsed_content, createdAt, lastReplyAt, lastReplyBy, createdBy, parentID, ip", "'Test Topic','A topic automatically generated by the software.','A topic automatically generated by the software.',UTC_TIMESTAMP(),UTC_TIMESTAMP(),1,1,2,''")
|
insert("topics", "title, content, parsed_content, createdAt, lastReplyAt, lastReplyBy, createdBy, parentID, ip", "'Test Topic','A topic automatically generated by the software.','A topic automatically generated by the software.',UTC_TIMESTAMP(),UTC_TIMESTAMP(),1,1,2,''")
|
||||||
|
|
||||||
insert("replies", "tid, content, parsed_content, createdAt, createdBy, lastUpdated, lastEdit, lastEditBy, ip", "1,'A reply!','A reply!',UTC_TIMESTAMP(),1,UTC_TIMESTAMP(),0,0,''")
|
insert("replies", "tid, content, parsed_content, createdAt, createdBy, lastUpdated, lastEdit, lastEditBy, ip", "1,'A reply!','A reply!',UTC_TIMESTAMP(),1,UTC_TIMESTAMP(),0,0,''")
|
||||||
|
|
||||||
insert("menus", "", "")
|
insert("menus", "", "")
|
||||||
|
|
||||||
// Go maps have a random iteration order, so we have to do this, otherwise the schema files will become unstable and harder to audit
|
// Go maps have a random iteration order, so we have to do this, otherwise the schema files will become unstable and harder to audit
|
||||||
order := 0
|
order := 0
|
||||||
mOrder := "mid, name, htmlID, cssClass, position, path, aria, tooltip, guestOnly, memberOnly, staffOnly, adminOnly"
|
mOrder := "mid, name, htmlID, cssClass, position, path, aria, tooltip, guestOnly, memberOnly, staffOnly, adminOnly"
|
||||||
addMenuItem := func(data map[string]interface{}) {
|
addMenuItem := func(data map[string]interface{}) {
|
||||||
if data["mid"] == nil {
|
if data["mid"] == nil {
|
||||||
data["mid"] = 1
|
data["mid"] = 1
|
||||||
}
|
}
|
||||||
if data["position"] == nil {
|
if data["position"] == nil {
|
||||||
data["position"] = "left"
|
data["position"] = "left"
|
||||||
}
|
}
|
||||||
cols, values := qgen.InterfaceMapToInsertStrings(data, mOrder)
|
cols, values := qgen.InterfaceMapToInsertStrings(data, mOrder)
|
||||||
insert("menu_items", cols+", order", values+","+strconv.Itoa(order))
|
insert("menu_items", cols+", order", values+","+strconv.Itoa(order))
|
||||||
order++
|
order++
|
||||||
}
|
}
|
||||||
|
|
||||||
addMenuItem(si{"name": "{lang.menu_forums}", "htmlID": "menu_forums", "path": "/forums/", "aria": "{lang.menu_forums_aria}", "tooltip": "{lang.menu_forums_tooltip}"})
|
addMenuItem(si{"name": "{lang.menu_forums}", "htmlID": "menu_forums", "path": "/forums/", "aria": "{lang.menu_forums_aria}", "tooltip": "{lang.menu_forums_tooltip}"})
|
||||||
|
|
||||||
addMenuItem(si{"name": "{lang.menu_topics}", "htmlID": "menu_topics", "cssClass": "menu_topics", "path": "/topics/", "aria": "{lang.menu_topics_aria}", "tooltip": "{lang.menu_topics_tooltip}"})
|
addMenuItem(si{"name": "{lang.menu_topics}", "htmlID": "menu_topics", "cssClass": "menu_topics", "path": "/topics/", "aria": "{lang.menu_topics_aria}", "tooltip": "{lang.menu_topics_tooltip}"})
|
||||||
|
|
||||||
addMenuItem(si{"htmlID": "general_alerts", "cssClass": "menu_alerts", "position": "right", "tmplName": "menu_alerts"})
|
addMenuItem(si{"htmlID": "general_alerts", "cssClass": "menu_alerts", "position": "right", "tmplName": "menu_alerts"})
|
||||||
|
|
||||||
addMenuItem(si{"name": "{lang.menu_account}", "cssClass": "menu_account", "path": "/user/edit/", "aria": "{lang.menu_account_aria}", "tooltip": "{lang.menu_account_tooltip}", "memberOnly": true})
|
addMenuItem(si{"name": "{lang.menu_account}", "cssClass": "menu_account", "path": "/user/edit/", "aria": "{lang.menu_account_aria}", "tooltip": "{lang.menu_account_tooltip}", "memberOnly": true})
|
||||||
|
|
||||||
addMenuItem(si{"name": "{lang.menu_profile}", "cssClass": "menu_profile", "path": "{me.Link}", "aria": "{lang.menu_profile_aria}", "tooltip": "{lang.menu_profile_tooltip}", "memberOnly": true})
|
addMenuItem(si{"name": "{lang.menu_profile}", "cssClass": "menu_profile", "path": "{me.Link}", "aria": "{lang.menu_profile_aria}", "tooltip": "{lang.menu_profile_tooltip}", "memberOnly": true})
|
||||||
|
|
||||||
addMenuItem(si{"name": "{lang.menu_panel}", "cssClass": "menu_panel menu_account", "path": "/panel/", "aria": "{lang.menu_panel_aria}", "tooltip": "{lang.menu_panel_tooltip}", "memberOnly": true, "staffOnly": true})
|
addMenuItem(si{"name": "{lang.menu_panel}", "cssClass": "menu_panel menu_account", "path": "/panel/", "aria": "{lang.menu_panel_aria}", "tooltip": "{lang.menu_panel_tooltip}", "memberOnly": true, "staffOnly": true})
|
||||||
|
|
||||||
addMenuItem(si{"name": "{lang.menu_logout}", "cssClass": "menu_logout", "path": "/accounts/logout/?s={me.Session}", "aria": "{lang.menu_logout_aria}", "tooltip": "{lang.menu_logout_tooltip}", "memberOnly": true})
|
addMenuItem(si{"name": "{lang.menu_logout}", "cssClass": "menu_logout", "path": "/accounts/logout/?s={me.Session}", "aria": "{lang.menu_logout_aria}", "tooltip": "{lang.menu_logout_tooltip}", "memberOnly": true})
|
||||||
|
|
||||||
addMenuItem(si{"name": "{lang.menu_register}", "cssClass": "menu_register", "path": "/accounts/create/", "aria": "{lang.menu_register_aria}", "tooltip": "{lang.menu_register_tooltip}", "guestOnly": true})
|
addMenuItem(si{"name": "{lang.menu_register}", "cssClass": "menu_register", "path": "/accounts/create/", "aria": "{lang.menu_register_aria}", "tooltip": "{lang.menu_register_tooltip}", "guestOnly": true})
|
||||||
|
|
||||||
addMenuItem(si{"name": "{lang.menu_login}", "cssClass": "menu_login", "path": "/accounts/login/", "aria": "{lang.menu_login_aria}", "tooltip": "{lang.menu_login_tooltip}", "guestOnly": true})
|
addMenuItem(si{"name": "{lang.menu_login}", "cssClass": "menu_login", "path": "/accounts/login/", "aria": "{lang.menu_login_aria}", "tooltip": "{lang.menu_login_tooltip}", "guestOnly": true})
|
||||||
|
|
||||||
/*var fSet []string
|
/*var fSet []string
|
||||||
for _, table := range tables {
|
for _, table := range tables {
|
||||||
fSet = append(fSet, "'"+table+"'")
|
fSet = append(fSet, "'"+table+"'")
|
||||||
}
|
}
|
||||||
qgen.Install.SimpleBulkInsert("tables", "name", fSet)*/
|
qgen.Install.SimpleBulkInsert("tables", "name", fSet)*/
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ? - What is this for?
|
// ? - What is this for?
|
||||||
/*func copyInsertMap(in map[string]interface{}) (out map[string]interface{}) {
|
/*func copyInsertMap(in map[string]interface{}) (out map[string]interface{}) {
|
||||||
out = make(map[string]interface{})
|
out = make(map[string]interface{})
|
||||||
for col, value := range in {
|
for col, value := range in {
|
||||||
out[col] = value
|
out[col] = value
|
||||||
}
|
}
|
||||||
return out
|
return out
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
type LitStr string
|
type LitStr string
|
||||||
|
|
||||||
func writeSelects(a qgen.Adapter) error {
|
func writeSelects(a qgen.Adapter) error {
|
||||||
b := a.Builder()
|
b := a.Builder()
|
||||||
|
|
||||||
// Looking for getTopic? Your statement is in another castle
|
// Looking for getTopic? Your statement is in another castle
|
||||||
|
|
||||||
//b.Select("isPluginInstalled").Table("plugins").Columns("installed").Where("uname = ?").Parse()
|
//b.Select("isPluginInstalled").Table("plugins").Columns("installed").Where("uname = ?").Parse()
|
||||||
|
|
||||||
b.Select("forumEntryExists").Table("forums").Columns("fid").Where("name = ''").Orderby("fid ASC").Limit("0,1").Parse()
|
b.Select("forumEntryExists").Table("forums").Columns("fid").Where("name = ''").Orderby("fid ASC").Limit("0,1").Parse()
|
||||||
|
|
||||||
b.Select("groupEntryExists").Table("users_groups").Columns("gid").Where("name = ''").Orderby("gid ASC").Limit("0,1").Parse()
|
b.Select("groupEntryExists").Table("users_groups").Columns("gid").Where("name = ''").Orderby("gid ASC").Limit("0,1").Parse()
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeLeftJoins(a qgen.Adapter) error {
|
func writeLeftJoins(a qgen.Adapter) error {
|
||||||
a.SimpleLeftJoin("getForumTopics", "topics", "users", "topics.tid, topics.title, topics.content, topics.createdBy, topics.is_closed, topics.sticky, topics.createdAt, topics.lastReplyAt, topics.parentID, users.name, users.avatar", "topics.createdBy = users.uid", "topics.parentID = ?", "topics.sticky DESC, topics.lastReplyAt DESC, topics.createdBy desc", "")
|
a.SimpleLeftJoin("getForumTopics", "topics", "users", "topics.tid, topics.title, topics.content, topics.createdBy, topics.is_closed, topics.sticky, topics.createdAt, topics.lastReplyAt, topics.parentID, users.name, users.avatar", "topics.createdBy = users.uid", "topics.parentID = ?", "topics.sticky DESC, topics.lastReplyAt DESC, topics.createdBy desc", "")
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeInnerJoins(a qgen.Adapter) (err error) {
|
func writeInnerJoins(a qgen.Adapter) (err error) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeInserts(a qgen.Adapter) error {
|
func writeInserts(a qgen.Adapter) error {
|
||||||
b := a.Builder()
|
b := a.Builder()
|
||||||
|
|
||||||
b.Insert("addForumPermsToForum").Table("forums_permissions").Columns("gid,fid,preset,permissions").Fields("?,?,?,?").Parse()
|
b.Insert("addForumPermsToForum").Table("forums_permissions").Columns("gid,fid,preset,permissions").Fields("?,?,?,?").Parse()
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeUpdates(a qgen.Adapter) error {
|
func writeUpdates(a qgen.Adapter) error {
|
||||||
b := a.Builder()
|
b := a.Builder()
|
||||||
|
|
||||||
b.Update("updateEmail").Table("emails").Set("email = ?, uid = ?, validated = ?, token = ?").Where("email = ?").Parse()
|
b.Update("updateEmail").Table("emails").Set("email = ?, uid = ?, validated = ?, token = ?").Where("email = ?").Parse()
|
||||||
|
|
||||||
b.Update("setTempGroup").Table("users").Set("temp_group = ?").Where("uid = ?").Parse()
|
b.Update("setTempGroup").Table("users").Set("temp_group = ?").Where("uid = ?").Parse()
|
||||||
|
|
||||||
b.Update("bumpSync").Table("sync").Set("last_update = UTC_TIMESTAMP()").Parse()
|
b.Update("bumpSync").Table("sync").Set("last_update = UTC_TIMESTAMP()").Parse()
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeDeletes(a qgen.Adapter) error {
|
func writeDeletes(a qgen.Adapter) error {
|
||||||
b := a.Builder()
|
b := a.Builder()
|
||||||
|
|
||||||
//b.Delete("deleteForumPermsByForum").Table("forums_permissions").Where("fid=?").Parse()
|
//b.Delete("deleteForumPermsByForum").Table("forums_permissions").Where("fid=?").Parse()
|
||||||
|
|
||||||
b.Delete("deleteActivityStreamMatch").Table("activity_stream_matches").Where("watcher=? AND asid=?").Parse()
|
b.Delete("deleteActivityStreamMatch").Table("activity_stream_matches").Where("watcher=? AND asid=?").Parse()
|
||||||
//b.Delete("deleteActivityStreamMatchesByWatcher").Table("activity_stream_matches").Where("watcher=?").Parse()
|
//b.Delete("deleteActivityStreamMatchesByWatcher").Table("activity_stream_matches").Where("watcher=?").Parse()
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeSimpleCounts(a qgen.Adapter) error {
|
func writeSimpleCounts(a qgen.Adapter) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeInsertSelects(a qgen.Adapter) error {
|
func writeInsertSelects(a qgen.Adapter) error {
|
||||||
/*a.SimpleInsertSelect("addForumPermsToForumAdmins",
|
/*a.SimpleInsertSelect("addForumPermsToForumAdmins",
|
||||||
qgen.DB_Insert{"forums_permissions", "gid, fid, preset, permissions", ""},
|
qgen.DB_Insert{"forums_permissions", "gid, fid, preset, permissions", ""},
|
||||||
qgen.DB_Select{"users_groups", "gid, ? AS fid, ? AS preset, ? AS permissions", "is_admin = 1", "", ""},
|
qgen.DB_Select{"users_groups", "gid, ? AS fid, ? AS preset, ? AS permissions", "is_admin = 1", "", ""},
|
||||||
)*/
|
)*/
|
||||||
|
|
||||||
/*a.SimpleInsertSelect("addForumPermsToForumStaff",
|
/*a.SimpleInsertSelect("addForumPermsToForumStaff",
|
||||||
qgen.DB_Insert{"forums_permissions", "gid, fid, preset, permissions", ""},
|
qgen.DB_Insert{"forums_permissions", "gid, fid, preset, permissions", ""},
|
||||||
qgen.DB_Select{"users_groups", "gid, ? AS fid, ? AS preset, ? AS permissions", "is_admin = 0 AND is_mod = 1", "", ""},
|
qgen.DB_Select{"users_groups", "gid, ? AS fid, ? AS preset, ? AS permissions", "is_admin = 0 AND is_mod = 1", "", ""},
|
||||||
)*/
|
)*/
|
||||||
|
|
||||||
/*a.SimpleInsertSelect("addForumPermsToForumMembers",
|
/*a.SimpleInsertSelect("addForumPermsToForumMembers",
|
||||||
qgen.DB_Insert{"forums_permissions", "gid, fid, preset, permissions", ""},
|
qgen.DB_Insert{"forums_permissions", "gid, fid, preset, permissions", ""},
|
||||||
qgen.DB_Select{"users_groups", "gid, ? AS fid, ? AS preset, ? AS permissions", "is_admin = 0 AND is_mod = 0 AND is_banned = 0", "", ""},
|
qgen.DB_Select{"users_groups", "gid, ? AS fid, ? AS preset, ? AS permissions", "is_admin = 0 AND is_mod = 0 AND is_banned = 0", "", ""},
|
||||||
)*/
|
)*/
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// nolint
|
// nolint
|
||||||
func writeInsertLeftJoins(a qgen.Adapter) error {
|
func writeInsertLeftJoins(a qgen.Adapter) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeInsertInnerJoins(a qgen.Adapter) error {
|
func writeInsertInnerJoins(a qgen.Adapter) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeFile(name, content string) (err error) {
|
func writeFile(name, content string) (err error) {
|
||||||
f, err := os.Create(name)
|
f, err := os.Create(name)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
_, err = f.WriteString(content)
|
_, err = f.WriteString(content)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
err = f.Sync()
|
err = f.Sync()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return f.Close()
|
return f.Close()
|
||||||
}
|
}
|
||||||
|
|
|
@ -2,8 +2,8 @@
|
||||||
echo Building the query generator
|
echo Building the query generator
|
||||||
go build -ldflags="-s -w"
|
go build -ldflags="-s -w"
|
||||||
if %errorlevel% neq 0 (
|
if %errorlevel% neq 0 (
|
||||||
pause
|
pause
|
||||||
exit /b %errorlevel%
|
exit /b %errorlevel%
|
||||||
)
|
)
|
||||||
echo The query generator was successfully built
|
echo The query generator was successfully built
|
||||||
query_gen.exe
|
query_gen.exe
|
||||||
|
|
|
@ -4,42 +4,42 @@ import "strings"
|
||||||
import "github.com/Azareal/Gosora/query_gen"
|
import "github.com/Azareal/Gosora/query_gen"
|
||||||
|
|
||||||
type PrimaryKeySpitter struct {
|
type PrimaryKeySpitter struct {
|
||||||
keys map[string]string
|
keys map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPrimaryKeySpitter() *PrimaryKeySpitter {
|
func NewPrimaryKeySpitter() *PrimaryKeySpitter {
|
||||||
return &PrimaryKeySpitter{make(map[string]string)}
|
return &PrimaryKeySpitter{make(map[string]string)}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (spit *PrimaryKeySpitter) Hook(name string, args ...interface{}) error {
|
func (spit *PrimaryKeySpitter) Hook(name string, args ...interface{}) error {
|
||||||
if name == "CreateTableStart" {
|
if name == "CreateTableStart" {
|
||||||
var found string
|
var found string
|
||||||
var table = args[0].(*qgen.DBInstallTable)
|
var table = args[0].(*qgen.DBInstallTable)
|
||||||
for _, key := range table.Keys {
|
for _, key := range table.Keys {
|
||||||
if key.Type == "primary" {
|
if key.Type == "primary" {
|
||||||
expl := strings.Split(key.Columns, ",")
|
expl := strings.Split(key.Columns, ",")
|
||||||
if len(expl) > 1 {
|
if len(expl) > 1 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
found = key.Columns
|
found = key.Columns
|
||||||
}
|
}
|
||||||
if found != "" {
|
if found != "" {
|
||||||
table := table.Name
|
table := table.Name
|
||||||
spit.keys[table] = found
|
spit.keys[table] = found
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (spit *PrimaryKeySpitter) Write() error {
|
func (spit *PrimaryKeySpitter) Write() error {
|
||||||
out := `// Generated by Gosora's Query Generator. DO NOT EDIT.
|
out := `// Generated by Gosora's Query Generator. DO NOT EDIT.
|
||||||
package main
|
package main
|
||||||
|
|
||||||
var dbTablePrimaryKeys = map[string]string{
|
var dbTablePrimaryKeys = map[string]string{
|
||||||
`
|
`
|
||||||
for table, key := range spit.keys {
|
for table, key := range spit.keys {
|
||||||
out += "\t\"" + table + "\":\"" + key + "\",\n"
|
out += "\t\"" + table + "\":\"" + key + "\",\n"
|
||||||
}
|
}
|
||||||
return writeFile("./gen_tables.go", out+"}\n")
|
return writeFile("./gen_tables.go", out+"}\n")
|
||||||
}
|
}
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,12 +0,0 @@
|
||||||
echo "Updating the dependencies"
|
|
||||||
./update-deps-linux
|
|
||||||
|
|
||||||
echo "Updating Gosora"
|
|
||||||
git stash
|
|
||||||
git pull origin master
|
|
||||||
git stash apply
|
|
||||||
|
|
||||||
echo "Patching Gosora"
|
|
||||||
go generate
|
|
||||||
go build -ldflags="-s -w" -o Patcher "./patcher"
|
|
||||||
./Patcher
|
|
|
@ -1,4 +0,0 @@
|
||||||
echo "Building the patcher"
|
|
||||||
go generate
|
|
||||||
./update-deps-linux
|
|
||||||
go build -ldflags="-s -w" -o Patcher "./patcher"
|
|
|
@ -1,32 +0,0 @@
|
||||||
@echo off
|
|
||||||
|
|
||||||
echo Updating the dependencies
|
|
||||||
go get
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
go get -u github.com/mailru/easyjson/...
|
|
||||||
|
|
||||||
echo Updating Gosora
|
|
||||||
git stash
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
git pull origin master
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
git stash apply
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Patching Gosora
|
|
||||||
go generate
|
|
||||||
go build -ldflags="-s -w" ./patcher
|
|
||||||
patcher.exe
|
|
122
gen_mysql.go
122
gen_mysql.go
|
@ -11,80 +11,80 @@ import "github.com/Azareal/Gosora/common"
|
||||||
|
|
||||||
// nolint
|
// nolint
|
||||||
type Stmts struct {
|
type Stmts struct {
|
||||||
forumEntryExists *sql.Stmt
|
forumEntryExists *sql.Stmt
|
||||||
groupEntryExists *sql.Stmt
|
groupEntryExists *sql.Stmt
|
||||||
getForumTopics *sql.Stmt
|
getForumTopics *sql.Stmt
|
||||||
addForumPermsToForum *sql.Stmt
|
addForumPermsToForum *sql.Stmt
|
||||||
updateEmail *sql.Stmt
|
updateEmail *sql.Stmt
|
||||||
setTempGroup *sql.Stmt
|
setTempGroup *sql.Stmt
|
||||||
bumpSync *sql.Stmt
|
bumpSync *sql.Stmt
|
||||||
deleteActivityStreamMatch *sql.Stmt
|
deleteActivityStreamMatch *sql.Stmt
|
||||||
|
|
||||||
getActivityFeedByWatcher *sql.Stmt
|
getActivityFeedByWatcher *sql.Stmt
|
||||||
getActivityCountByWatcher *sql.Stmt
|
getActivityCountByWatcher *sql.Stmt
|
||||||
|
|
||||||
Mocks bool
|
Mocks bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// nolint
|
// nolint
|
||||||
func _gen_mysql() (err error) {
|
func _gen_mysql() (err error) {
|
||||||
common.DebugLog("Building the generated statements")
|
common.DebugLog("Building the generated statements")
|
||||||
|
|
||||||
common.DebugLog("Preparing forumEntryExists statement.")
|
common.DebugLog("Preparing forumEntryExists statement.")
|
||||||
stmts.forumEntryExists, err = db.Prepare("SELECT `fid` FROM `forums` WHERE `name` = '' ORDER BY `fid` ASC LIMIT 0,1")
|
stmts.forumEntryExists, err = db.Prepare("SELECT `fid` FROM `forums` WHERE `name` = '' ORDER BY `fid` ASC LIMIT 0,1")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print("Error in forumEntryExists statement.")
|
log.Print("Error in forumEntryExists statement.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
common.DebugLog("Preparing groupEntryExists statement.")
|
common.DebugLog("Preparing groupEntryExists statement.")
|
||||||
stmts.groupEntryExists, err = db.Prepare("SELECT `gid` FROM `users_groups` WHERE `name` = '' ORDER BY `gid` ASC LIMIT 0,1")
|
stmts.groupEntryExists, err = db.Prepare("SELECT `gid` FROM `users_groups` WHERE `name` = '' ORDER BY `gid` ASC LIMIT 0,1")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print("Error in groupEntryExists statement.")
|
log.Print("Error in groupEntryExists statement.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
common.DebugLog("Preparing getForumTopics statement.")
|
common.DebugLog("Preparing getForumTopics statement.")
|
||||||
stmts.getForumTopics, err = db.Prepare("SELECT `topics`.`tid`, `topics`.`title`, `topics`.`content`, `topics`.`createdBy`, `topics`.`is_closed`, `topics`.`sticky`, `topics`.`createdAt`, `topics`.`lastReplyAt`, `topics`.`parentID`, `users`.`name`, `users`.`avatar` FROM `topics` LEFT JOIN `users` ON `topics`.`createdBy` = `users`.`uid` WHERE `topics`.`parentID` = ? ORDER BY `topics`.`sticky` DESC,`topics`.`lastReplyAt` DESC,`topics`.`createdBy` DESC")
|
stmts.getForumTopics, err = db.Prepare("SELECT `topics`.`tid`, `topics`.`title`, `topics`.`content`, `topics`.`createdBy`, `topics`.`is_closed`, `topics`.`sticky`, `topics`.`createdAt`, `topics`.`lastReplyAt`, `topics`.`parentID`, `users`.`name`, `users`.`avatar` FROM `topics` LEFT JOIN `users` ON `topics`.`createdBy` = `users`.`uid` WHERE `topics`.`parentID` = ? ORDER BY `topics`.`sticky` DESC,`topics`.`lastReplyAt` DESC,`topics`.`createdBy` DESC")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print("Error in getForumTopics statement.")
|
log.Print("Error in getForumTopics statement.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
common.DebugLog("Preparing addForumPermsToForum statement.")
|
common.DebugLog("Preparing addForumPermsToForum statement.")
|
||||||
stmts.addForumPermsToForum, err = db.Prepare("INSERT INTO `forums_permissions`(`gid`,`fid`,`preset`,`permissions`) VALUES (?,?,?,?)")
|
stmts.addForumPermsToForum, err = db.Prepare("INSERT INTO `forums_permissions`(`gid`,`fid`,`preset`,`permissions`) VALUES (?,?,?,?)")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print("Error in addForumPermsToForum statement.")
|
log.Print("Error in addForumPermsToForum statement.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
common.DebugLog("Preparing updateEmail statement.")
|
common.DebugLog("Preparing updateEmail statement.")
|
||||||
stmts.updateEmail, err = db.Prepare("UPDATE `emails` SET `email`= ?,`uid`= ?,`validated`= ?,`token`= ? WHERE `email` = ?")
|
stmts.updateEmail, err = db.Prepare("UPDATE `emails` SET `email`= ?,`uid`= ?,`validated`= ?,`token`= ? WHERE `email` = ?")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print("Error in updateEmail statement.")
|
log.Print("Error in updateEmail statement.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
common.DebugLog("Preparing setTempGroup statement.")
|
common.DebugLog("Preparing setTempGroup statement.")
|
||||||
stmts.setTempGroup, err = db.Prepare("UPDATE `users` SET `temp_group`= ? WHERE `uid` = ?")
|
stmts.setTempGroup, err = db.Prepare("UPDATE `users` SET `temp_group`= ? WHERE `uid` = ?")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print("Error in setTempGroup statement.")
|
log.Print("Error in setTempGroup statement.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
common.DebugLog("Preparing bumpSync statement.")
|
common.DebugLog("Preparing bumpSync statement.")
|
||||||
stmts.bumpSync, err = db.Prepare("UPDATE `sync` SET `last_update`= UTC_TIMESTAMP()")
|
stmts.bumpSync, err = db.Prepare("UPDATE `sync` SET `last_update`= UTC_TIMESTAMP()")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print("Error in bumpSync statement.")
|
log.Print("Error in bumpSync statement.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
common.DebugLog("Preparing deleteActivityStreamMatch statement.")
|
common.DebugLog("Preparing deleteActivityStreamMatch statement.")
|
||||||
stmts.deleteActivityStreamMatch, err = db.Prepare("DELETE FROM `activity_stream_matches` WHERE `watcher` = ? AND `asid` = ?")
|
stmts.deleteActivityStreamMatch, err = db.Prepare("DELETE FROM `activity_stream_matches` WHERE `watcher` = ? AND `asid` = ?")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print("Error in deleteActivityStreamMatch statement.")
|
log.Print("Error in deleteActivityStreamMatch statement.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
66
gen_pgsql.go
66
gen_pgsql.go
|
@ -9,48 +9,48 @@ import "github.com/Azareal/Gosora/common"
|
||||||
|
|
||||||
// nolint
|
// nolint
|
||||||
type Stmts struct {
|
type Stmts struct {
|
||||||
addForumPermsToForum *sql.Stmt
|
addForumPermsToForum *sql.Stmt
|
||||||
updateEmail *sql.Stmt
|
updateEmail *sql.Stmt
|
||||||
setTempGroup *sql.Stmt
|
setTempGroup *sql.Stmt
|
||||||
bumpSync *sql.Stmt
|
bumpSync *sql.Stmt
|
||||||
|
|
||||||
getActivityFeedByWatcher *sql.Stmt
|
getActivityFeedByWatcher *sql.Stmt
|
||||||
getActivityCountByWatcher *sql.Stmt
|
getActivityCountByWatcher *sql.Stmt
|
||||||
|
|
||||||
Mocks bool
|
Mocks bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// nolint
|
// nolint
|
||||||
func _gen_pgsql() (err error) {
|
func _gen_pgsql() (err error) {
|
||||||
common.DebugLog("Building the generated statements")
|
common.DebugLog("Building the generated statements")
|
||||||
|
|
||||||
common.DebugLog("Preparing addForumPermsToForum statement.")
|
common.DebugLog("Preparing addForumPermsToForum statement.")
|
||||||
stmts.addForumPermsToForum, err = db.Prepare("INSERT INTO \"forums_permissions\"(\"gid\",\"fid\",\"preset\",\"permissions\") VALUES (?,?,?,?)")
|
stmts.addForumPermsToForum, err = db.Prepare("INSERT INTO \"forums_permissions\"(\"gid\",\"fid\",\"preset\",\"permissions\") VALUES (?,?,?,?)")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print("Error in addForumPermsToForum statement.")
|
log.Print("Error in addForumPermsToForum statement.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
common.DebugLog("Preparing updateEmail statement.")
|
common.DebugLog("Preparing updateEmail statement.")
|
||||||
stmts.updateEmail, err = db.Prepare("UPDATE \"emails\" SET `email`= ?,`uid`= ?,`validated`= ?,`token`= ? WHERE `email` = ?")
|
stmts.updateEmail, err = db.Prepare("UPDATE \"emails\" SET `email`= ?,`uid`= ?,`validated`= ?,`token`= ? WHERE `email` = ?")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print("Error in updateEmail statement.")
|
log.Print("Error in updateEmail statement.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
common.DebugLog("Preparing setTempGroup statement.")
|
common.DebugLog("Preparing setTempGroup statement.")
|
||||||
stmts.setTempGroup, err = db.Prepare("UPDATE \"users\" SET `temp_group`= ? WHERE `uid` = ?")
|
stmts.setTempGroup, err = db.Prepare("UPDATE \"users\" SET `temp_group`= ? WHERE `uid` = ?")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print("Error in setTempGroup statement.")
|
log.Print("Error in setTempGroup statement.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
common.DebugLog("Preparing bumpSync statement.")
|
common.DebugLog("Preparing bumpSync statement.")
|
||||||
stmts.bumpSync, err = db.Prepare("UPDATE \"sync\" SET `last_update`= LOCALTIMESTAMP()")
|
stmts.bumpSync, err = db.Prepare("UPDATE \"sync\" SET `last_update`= LOCALTIMESTAMP()")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Print("Error in bumpSync statement.")
|
log.Print("Error in bumpSync statement.")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,21 +0,0 @@
|
||||||
# An example systemd service file
|
|
||||||
[Unit]
|
|
||||||
Description=Gosora
|
|
||||||
|
|
||||||
[Service]
|
|
||||||
User=gosora
|
|
||||||
Group=www-data
|
|
||||||
|
|
||||||
Restart=on-failure
|
|
||||||
RestartSec=10
|
|
||||||
# Set these to the location of Gosora
|
|
||||||
WorkingDirectory=/home/gosora/src
|
|
||||||
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
|
||||||
# Make sure you manually run pre-run-linux before you start the service
|
|
||||||
ExecStart=/home/gosora/src/Gosora
|
|
||||||
|
|
||||||
ProtectSystem=full
|
|
||||||
PrivateDevices=true
|
|
||||||
|
|
||||||
[Install]
|
|
||||||
WantedBy=multi-user.target
|
|
|
@ -1,7 +0,0 @@
|
||||||
go get -u github.com/mailru/easyjson/...
|
|
||||||
easyjson -pkg common
|
|
||||||
go get
|
|
||||||
|
|
||||||
go build -ldflags="-s -w" -o Installer "./cmd/install"
|
|
||||||
|
|
||||||
./Installer --dbType=mysql --dbHost=localhost --dbUser=$MYSQL_USER --dbPassword=$MYSQL_PASSWORD --dbName=$MYSQL_DATABASE --shortSiteName=$SITE_SHORT_NAME --siteName=$SITE_NAME --siteURL=$SITE_URL --serverPort=$SERVER_PORT--secureServerPort=$SECURE_SERVER_PORT
|
|
|
@ -1,8 +0,0 @@
|
||||||
echo "Installing the dependencies"
|
|
||||||
./update-deps-linux
|
|
||||||
|
|
||||||
echo "Building the installer"
|
|
||||||
go build -ldflags="-s -w" -o Installer "./cmd/install"
|
|
||||||
|
|
||||||
echo "Running the installer"
|
|
||||||
./Installer
|
|
29
install.bat
29
install.bat
|
@ -1,29 +0,0 @@
|
||||||
@echo off
|
|
||||||
|
|
||||||
echo Installing the dependencies
|
|
||||||
go get -u github.com/mailru/easyjson/...
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
easyjson -pkg common
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
go get
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the installer
|
|
||||||
go generate
|
|
||||||
go build -ldflags="-s -w" "./cmd/install"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
install.exe
|
|
|
@ -1,48 +1,48 @@
|
||||||
package install
|
package install
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
qgen "github.com/Azareal/Gosora/query_gen"
|
qgen "github.com/Azareal/Gosora/query_gen"
|
||||||
)
|
)
|
||||||
|
|
||||||
var adapters = make(map[string]InstallAdapter)
|
var adapters = make(map[string]InstallAdapter)
|
||||||
|
|
||||||
type InstallAdapter interface {
|
type InstallAdapter interface {
|
||||||
Name() string
|
Name() string
|
||||||
DefaultPort() string
|
DefaultPort() string
|
||||||
SetConfig(dbHost, dbUsername, dbPassword, dbName, dbPort string)
|
SetConfig(dbHost, dbUsername, dbPassword, dbName, dbPort string)
|
||||||
InitDatabase() error
|
InitDatabase() error
|
||||||
TableDefs() error
|
TableDefs() error
|
||||||
InitialData() error
|
InitialData() error
|
||||||
CreateAdmin() error
|
CreateAdmin() error
|
||||||
|
|
||||||
DBHost() string
|
DBHost() string
|
||||||
DBUsername() string
|
DBUsername() string
|
||||||
DBPassword() string
|
DBPassword() string
|
||||||
DBName() string
|
DBName() string
|
||||||
DBPort() string
|
DBPort() string
|
||||||
}
|
}
|
||||||
|
|
||||||
func Lookup(name string) (InstallAdapter, bool) {
|
func Lookup(name string) (InstallAdapter, bool) {
|
||||||
adap, ok := adapters[name]
|
adap, ok := adapters[name]
|
||||||
return adap, ok
|
return adap, ok
|
||||||
}
|
}
|
||||||
|
|
||||||
func createAdmin() error {
|
func createAdmin() error {
|
||||||
fmt.Println("Creating the admin user")
|
fmt.Println("Creating the admin user")
|
||||||
hashedPassword, salt, e := BcryptGeneratePassword("password")
|
hashedPassword, salt, e := BcryptGeneratePassword("password")
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build the admin user query
|
// Build the admin user query
|
||||||
adminUserStmt, e := qgen.Builder.SimpleInsert("users", "name, password, salt, email, group, is_super_admin, active, createdAt, lastActiveAt, lastLiked, oldestItemLikedCreatedAt, message, last_ip", "'Admin',?,?,'admin@localhost',1,1,1,UTC_TIMESTAMP(),UTC_TIMESTAMP(),UTC_TIMESTAMP(),UTC_TIMESTAMP(),'',''")
|
adminUserStmt, e := qgen.Builder.SimpleInsert("users", "name, password, salt, email, group, is_super_admin, active, createdAt, lastActiveAt, lastLiked, oldestItemLikedCreatedAt, message, last_ip", "'Admin',?,?,'admin@localhost',1,1,1,UTC_TIMESTAMP(),UTC_TIMESTAMP(),UTC_TIMESTAMP(),UTC_TIMESTAMP(),'',''")
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
|
|
||||||
// Run the admin user query
|
// Run the admin user query
|
||||||
_, e = adminUserStmt.Exec(hashedPassword, salt)
|
_, e = adminUserStmt.Exec(hashedPassword, salt)
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
|
|
216
install/mssql.go
216
install/mssql.go
|
@ -7,165 +7,165 @@
|
||||||
package install
|
package install
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
"net/url"
|
"net/url"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Azareal/Gosora/query_gen"
|
"github.com/Azareal/Gosora/query_gen"
|
||||||
_ "github.com/denisenkom/go-mssqldb"
|
_ "github.com/denisenkom/go-mssqldb"
|
||||||
)
|
)
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
adapters["mssql"] = &MssqlInstaller{dbHost: ""}
|
adapters["mssql"] = &MssqlInstaller{dbHost: ""}
|
||||||
}
|
}
|
||||||
|
|
||||||
type MssqlInstaller struct {
|
type MssqlInstaller struct {
|
||||||
db *sql.DB
|
db *sql.DB
|
||||||
dbHost string
|
dbHost string
|
||||||
dbUsername string
|
dbUsername string
|
||||||
dbPassword string
|
dbPassword string
|
||||||
dbName string
|
dbName string
|
||||||
dbInstance string
|
dbInstance string
|
||||||
dbPort string
|
dbPort string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MssqlInstaller) SetConfig(dbHost string, dbUsername string, dbPassword string, dbName string, dbPort string) {
|
func (ins *MssqlInstaller) SetConfig(dbHost string, dbUsername string, dbPassword string, dbName string, dbPort string) {
|
||||||
ins.dbHost = dbHost
|
ins.dbHost = dbHost
|
||||||
ins.dbUsername = dbUsername
|
ins.dbUsername = dbUsername
|
||||||
ins.dbPassword = dbPassword
|
ins.dbPassword = dbPassword
|
||||||
ins.dbName = dbName
|
ins.dbName = dbName
|
||||||
ins.dbInstance = "" // You can't set this from the installer right now, it allows you to connect to a named instance instead of a port
|
ins.dbInstance = "" // You can't set this from the installer right now, it allows you to connect to a named instance instead of a port
|
||||||
ins.dbPort = dbPort
|
ins.dbPort = dbPort
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MssqlInstaller) Name() string {
|
func (ins *MssqlInstaller) Name() string {
|
||||||
return "mssql"
|
return "mssql"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MssqlInstaller) DefaultPort() string {
|
func (ins *MssqlInstaller) DefaultPort() string {
|
||||||
return "1433"
|
return "1433"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MssqlInstaller) InitDatabase() (err error) {
|
func (ins *MssqlInstaller) InitDatabase() (err error) {
|
||||||
query := url.Values{}
|
query := url.Values{}
|
||||||
query.Add("database", ins.dbName)
|
query.Add("database", ins.dbName)
|
||||||
u := &url.URL{
|
u := &url.URL{
|
||||||
Scheme: "sqlserver",
|
Scheme: "sqlserver",
|
||||||
User: url.UserPassword(ins.dbUsername, ins.dbPassword),
|
User: url.UserPassword(ins.dbUsername, ins.dbPassword),
|
||||||
Host: ins.dbHost + ":" + ins.dbPort,
|
Host: ins.dbHost + ":" + ins.dbPort,
|
||||||
Path: ins.dbInstance,
|
Path: ins.dbInstance,
|
||||||
RawQuery: query.Encode(),
|
RawQuery: query.Encode(),
|
||||||
}
|
}
|
||||||
log.Print("u.String() ", u.String())
|
log.Print("u.String() ", u.String())
|
||||||
|
|
||||||
db, err := sql.Open("mssql", u.String())
|
db, err := sql.Open("mssql", u.String())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make sure that the connection is alive..
|
// Make sure that the connection is alive..
|
||||||
err = db.Ping()
|
err = db.Ping()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
fmt.Println("Successfully connected to the database")
|
fmt.Println("Successfully connected to the database")
|
||||||
|
|
||||||
// TODO: Create the database, if it doesn't exist
|
// TODO: Create the database, if it doesn't exist
|
||||||
|
|
||||||
// Ready the query builder
|
// Ready the query builder
|
||||||
ins.db = db
|
ins.db = db
|
||||||
qgen.Builder.SetConn(db)
|
qgen.Builder.SetConn(db)
|
||||||
return qgen.Builder.SetAdapter("mssql")
|
return qgen.Builder.SetAdapter("mssql")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MssqlInstaller) TableDefs() (err error) {
|
func (ins *MssqlInstaller) TableDefs() (err error) {
|
||||||
//fmt.Println("Creating the tables")
|
//fmt.Println("Creating the tables")
|
||||||
files, _ := ioutil.ReadDir("./schema/mssql/")
|
files, _ := ioutil.ReadDir("./schema/mssql/")
|
||||||
for _, f := range files {
|
for _, f := range files {
|
||||||
if !strings.HasPrefix(f.Name(), "query_") {
|
if !strings.HasPrefix(f.Name(), "query_") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
var table, ext string
|
var table, ext string
|
||||||
table = strings.TrimPrefix(f.Name(), "query_")
|
table = strings.TrimPrefix(f.Name(), "query_")
|
||||||
ext = filepath.Ext(table)
|
ext = filepath.Ext(table)
|
||||||
if ext != ".sql" {
|
if ext != ".sql" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
table = strings.TrimSuffix(table, ext)
|
table = strings.TrimSuffix(table, ext)
|
||||||
|
|
||||||
// ? - This is mainly here for tests, although it might allow the installer to overwrite a production database, so we might want to proceed with caution
|
// ? - This is mainly here for tests, although it might allow the installer to overwrite a production database, so we might want to proceed with caution
|
||||||
_, err = ins.db.Exec("DROP TABLE IF EXISTS [" + table + "];")
|
_, err = ins.db.Exec("DROP TABLE IF EXISTS [" + table + "];")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("Failed query:", "DROP TABLE IF EXISTS ["+table+"]")
|
fmt.Println("Failed query:", "DROP TABLE IF EXISTS ["+table+"]")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println("Creating table '" + table + "'")
|
fmt.Println("Creating table '" + table + "'")
|
||||||
data, err := ioutil.ReadFile("./schema/mssql/" + f.Name())
|
data, err := ioutil.ReadFile("./schema/mssql/" + f.Name())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
data = bytes.TrimSpace(data)
|
data = bytes.TrimSpace(data)
|
||||||
|
|
||||||
_, err = ins.db.Exec(string(data))
|
_, err = ins.db.Exec(string(data))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("Failed query:", string(data))
|
fmt.Println("Failed query:", string(data))
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MssqlInstaller) InitialData() (err error) {
|
func (ins *MssqlInstaller) InitialData() (err error) {
|
||||||
//fmt.Println("Seeding the tables")
|
//fmt.Println("Seeding the tables")
|
||||||
data, err := ioutil.ReadFile("./schema/mssql/inserts.sql")
|
data, err := ioutil.ReadFile("./schema/mssql/inserts.sql")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
data = bytes.TrimSpace(data)
|
data = bytes.TrimSpace(data)
|
||||||
|
|
||||||
statements := bytes.Split(data, []byte(";"))
|
statements := bytes.Split(data, []byte(";"))
|
||||||
for key, statement := range statements {
|
for key, statement := range statements {
|
||||||
if len(statement) == 0 {
|
if len(statement) == 0 {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
fmt.Println("Executing query #" + strconv.Itoa(key) + " " + string(statement))
|
fmt.Println("Executing query #" + strconv.Itoa(key) + " " + string(statement))
|
||||||
_, err = ins.db.Exec(string(statement))
|
_, err = ins.db.Exec(string(statement))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MssqlInstaller) CreateAdmin() error {
|
func (ins *MssqlInstaller) CreateAdmin() error {
|
||||||
return createAdmin()
|
return createAdmin()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MssqlInstaller) DBHost() string {
|
func (ins *MssqlInstaller) DBHost() string {
|
||||||
return ins.dbHost
|
return ins.dbHost
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MssqlInstaller) DBUsername() string {
|
func (ins *MssqlInstaller) DBUsername() string {
|
||||||
return ins.dbUsername
|
return ins.dbUsername
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MssqlInstaller) DBPassword() string {
|
func (ins *MssqlInstaller) DBPassword() string {
|
||||||
return ins.dbPassword
|
return ins.dbPassword
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MssqlInstaller) DBName() string {
|
func (ins *MssqlInstaller) DBName() string {
|
||||||
return ins.dbName
|
return ins.dbName
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MssqlInstaller) DBPort() string {
|
func (ins *MssqlInstaller) DBPort() string {
|
||||||
return ins.dbPort
|
return ins.dbPort
|
||||||
}
|
}
|
||||||
|
|
306
install/mysql.go
306
install/mysql.go
|
@ -7,177 +7,177 @@
|
||||||
package install
|
package install
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Azareal/Gosora/query_gen"
|
"github.com/Azareal/Gosora/query_gen"
|
||||||
_ "github.com/go-sql-driver/mysql"
|
_ "github.com/go-sql-driver/mysql"
|
||||||
)
|
)
|
||||||
|
|
||||||
//var dbCollation string = "utf8mb4_general_ci"
|
//var dbCollation string = "utf8mb4_general_ci"
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
adapters["mysql"] = &MysqlInstaller{dbHost: ""}
|
adapters["mysql"] = &MysqlInstaller{dbHost: ""}
|
||||||
}
|
}
|
||||||
|
|
||||||
type MysqlInstaller struct {
|
type MysqlInstaller struct {
|
||||||
db *sql.DB
|
db *sql.DB
|
||||||
dbHost string
|
dbHost string
|
||||||
dbUsername string
|
dbUsername string
|
||||||
dbPassword string
|
dbPassword string
|
||||||
dbName string
|
dbName string
|
||||||
dbPort string
|
dbPort string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) SetConfig(dbHost string, dbUsername string, dbPassword string, dbName string, dbPort string) {
|
func (ins *MysqlInstaller) SetConfig(dbHost string, dbUsername string, dbPassword string, dbName string, dbPort string) {
|
||||||
ins.dbHost = dbHost
|
ins.dbHost = dbHost
|
||||||
ins.dbUsername = dbUsername
|
ins.dbUsername = dbUsername
|
||||||
ins.dbPassword = dbPassword
|
ins.dbPassword = dbPassword
|
||||||
ins.dbName = dbName
|
ins.dbName = dbName
|
||||||
ins.dbPort = dbPort
|
ins.dbPort = dbPort
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) Name() string {
|
func (ins *MysqlInstaller) Name() string {
|
||||||
return "mysql"
|
return "mysql"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) DefaultPort() string {
|
func (ins *MysqlInstaller) DefaultPort() string {
|
||||||
return "3306"
|
return "3306"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) dbExists(dbName string) (bool, error) {
|
func (ins *MysqlInstaller) dbExists(dbName string) (bool, error) {
|
||||||
var waste string
|
var waste string
|
||||||
err := ins.db.QueryRow("SHOW DATABASES LIKE '" + dbName + "'").Scan(&waste)
|
err := ins.db.QueryRow("SHOW DATABASES LIKE '" + dbName + "'").Scan(&waste)
|
||||||
if err != nil && err != sql.ErrNoRows {
|
if err != nil && err != sql.ErrNoRows {
|
||||||
return false, err
|
return false, err
|
||||||
} else if err == sql.ErrNoRows {
|
} else if err == sql.ErrNoRows {
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) InitDatabase() (err error) {
|
func (ins *MysqlInstaller) InitDatabase() (err error) {
|
||||||
_dbPassword := ins.dbPassword
|
_dbPassword := ins.dbPassword
|
||||||
if _dbPassword != "" {
|
if _dbPassword != "" {
|
||||||
_dbPassword = ":" + _dbPassword
|
_dbPassword = ":" + _dbPassword
|
||||||
}
|
}
|
||||||
db, err := sql.Open("mysql", ins.dbUsername+_dbPassword+"@tcp("+ins.dbHost+":"+ins.dbPort+")/")
|
db, err := sql.Open("mysql", ins.dbUsername+_dbPassword+"@tcp("+ins.dbHost+":"+ins.dbPort+")/")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make sure that the connection is alive..
|
// Make sure that the connection is alive..
|
||||||
err = db.Ping()
|
err = db.Ping()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
fmt.Println("Successfully connected to the database")
|
fmt.Println("Successfully connected to the database")
|
||||||
|
|
||||||
ins.db = db
|
ins.db = db
|
||||||
ok, err := ins.dbExists(ins.dbName)
|
ok, err := ins.dbExists(ins.dbName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
fmt.Println("Unable to find the database. Attempting to create it")
|
fmt.Println("Unable to find the database. Attempting to create it")
|
||||||
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS " + ins.dbName)
|
_, err = db.Exec("CREATE DATABASE IF NOT EXISTS " + ins.dbName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
fmt.Println("The database was successfully created")
|
fmt.Println("The database was successfully created")
|
||||||
}
|
}
|
||||||
|
|
||||||
/*fmt.Println("Switching to database ", ins.dbName)
|
/*fmt.Println("Switching to database ", ins.dbName)
|
||||||
_, err = db.Exec("USE " + ins.dbName)
|
_, err = db.Exec("USE " + ins.dbName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}*/
|
}*/
|
||||||
db.Close()
|
db.Close()
|
||||||
|
|
||||||
db, err = sql.Open("mysql", ins.dbUsername+_dbPassword+"@tcp("+ins.dbHost+":"+ins.dbPort+")/"+ins.dbName)
|
db, err = sql.Open("mysql", ins.dbUsername+_dbPassword+"@tcp("+ins.dbHost+":"+ins.dbPort+")/"+ins.dbName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make sure that the connection is alive..
|
// Make sure that the connection is alive..
|
||||||
err = db.Ping()
|
err = db.Ping()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
fmt.Println("Successfully connected to the database")
|
fmt.Println("Successfully connected to the database")
|
||||||
|
|
||||||
// Ready the query builder
|
// Ready the query builder
|
||||||
ins.db = db
|
ins.db = db
|
||||||
qgen.Builder.SetConn(db)
|
qgen.Builder.SetConn(db)
|
||||||
return qgen.Builder.SetAdapter("mysql")
|
return qgen.Builder.SetAdapter("mysql")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) createTable(f os.FileInfo) error {
|
func (ins *MysqlInstaller) createTable(f os.FileInfo) error {
|
||||||
table := strings.TrimPrefix(f.Name(), "query_")
|
table := strings.TrimPrefix(f.Name(), "query_")
|
||||||
ext := filepath.Ext(table)
|
ext := filepath.Ext(table)
|
||||||
if ext != ".sql" {
|
if ext != ".sql" {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
table = strings.TrimSuffix(table, ext)
|
table = strings.TrimSuffix(table, ext)
|
||||||
|
|
||||||
// ? - This is mainly here for tests, although it might allow the installer to overwrite a production database, so we might want to proceed with caution
|
// ? - This is mainly here for tests, although it might allow the installer to overwrite a production database, so we might want to proceed with caution
|
||||||
q := "DROP TABLE IF EXISTS `" + table + "`;"
|
q := "DROP TABLE IF EXISTS `" + table + "`;"
|
||||||
_, err := ins.db.Exec(q)
|
_, err := ins.db.Exec(q)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("Failed query:", q)
|
fmt.Println("Failed query:", q)
|
||||||
fmt.Println("e:", err)
|
fmt.Println("e:", err)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
data, err := ioutil.ReadFile("./schema/mysql/" + f.Name())
|
data, err := ioutil.ReadFile("./schema/mysql/" + f.Name())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
data = bytes.TrimSpace(data)
|
data = bytes.TrimSpace(data)
|
||||||
|
|
||||||
q = string(data)
|
q = string(data)
|
||||||
_, err = ins.db.Exec(q)
|
_, err = ins.db.Exec(q)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Println("Failed query:", q)
|
fmt.Println("Failed query:", q)
|
||||||
fmt.Println("e:", err)
|
fmt.Println("e:", err)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
fmt.Printf("Created table '%s'\n", table)
|
fmt.Printf("Created table '%s'\n", table)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) TableDefs() (err error) {
|
func (ins *MysqlInstaller) TableDefs() (err error) {
|
||||||
fmt.Println("Creating the tables")
|
fmt.Println("Creating the tables")
|
||||||
files, err := ioutil.ReadDir("./schema/mysql/")
|
files, err := ioutil.ReadDir("./schema/mysql/")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = ins.db.Exec("SET FOREIGN_KEY_CHECKS = 0;")
|
_, err = ins.db.Exec("SET FOREIGN_KEY_CHECKS = 0;")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, f := range files {
|
for _, f := range files {
|
||||||
if !strings.HasPrefix(f.Name(), "query_") {
|
if !strings.HasPrefix(f.Name(), "query_") {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
err := ins.createTable(f)
|
err := ins.createTable(f)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
_, err = ins.db.Exec("SET FOREIGN_KEY_CHECKS = 1;")
|
_, err = ins.db.Exec("SET FOREIGN_KEY_CHECKS = 1;")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// ? - Moved this here since it was breaking the installer, we need to add this at some point
|
// ? - Moved this here since it was breaking the installer, we need to add this at some point
|
||||||
|
@ -185,50 +185,50 @@ func (ins *MysqlInstaller) TableDefs() (err error) {
|
||||||
/*INSERT INTO settings(`name`,`content`,`type`) VALUES ('meta_desc','','html-attribute');*/
|
/*INSERT INTO settings(`name`,`content`,`type`) VALUES ('meta_desc','','html-attribute');*/
|
||||||
|
|
||||||
func (ins *MysqlInstaller) InitialData() error {
|
func (ins *MysqlInstaller) InitialData() error {
|
||||||
fmt.Println("Seeding the tables")
|
fmt.Println("Seeding the tables")
|
||||||
data, err := ioutil.ReadFile("./schema/mysql/inserts.sql")
|
data, err := ioutil.ReadFile("./schema/mysql/inserts.sql")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
data = bytes.TrimSpace(data)
|
data = bytes.TrimSpace(data)
|
||||||
|
|
||||||
statements := bytes.Split(data, []byte(";"))
|
statements := bytes.Split(data, []byte(";"))
|
||||||
for key, sBytes := range statements {
|
for key, sBytes := range statements {
|
||||||
statement := string(sBytes)
|
statement := string(sBytes)
|
||||||
if statement == "" {
|
if statement == "" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
statement += ";"
|
statement += ";"
|
||||||
|
|
||||||
fmt.Println("Executing query #" + strconv.Itoa(key) + " " + statement)
|
fmt.Println("Executing query #" + strconv.Itoa(key) + " " + statement)
|
||||||
_, err = ins.db.Exec(statement)
|
_, err = ins.db.Exec(statement)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) CreateAdmin() error {
|
func (ins *MysqlInstaller) CreateAdmin() error {
|
||||||
return createAdmin()
|
return createAdmin()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) DBHost() string {
|
func (ins *MysqlInstaller) DBHost() string {
|
||||||
return ins.dbHost
|
return ins.dbHost
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) DBUsername() string {
|
func (ins *MysqlInstaller) DBUsername() string {
|
||||||
return ins.dbUsername
|
return ins.dbUsername
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) DBPassword() string {
|
func (ins *MysqlInstaller) DBPassword() string {
|
||||||
return ins.dbPassword
|
return ins.dbPassword
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) DBName() string {
|
func (ins *MysqlInstaller) DBName() string {
|
||||||
return ins.dbName
|
return ins.dbName
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *MysqlInstaller) DBPort() string {
|
func (ins *MysqlInstaller) DBPort() string {
|
||||||
return ins.dbPort
|
return ins.dbPort
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,105 +8,105 @@
|
||||||
package install
|
package install
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"database/sql"
|
"database/sql"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/Azareal/Gosora/query_gen"
|
"github.com/Azareal/Gosora/query_gen"
|
||||||
_ "github.com/go-sql-driver/mysql"
|
_ "github.com/go-sql-driver/mysql"
|
||||||
)
|
)
|
||||||
|
|
||||||
// We don't need SSL to run an installer... Do we?
|
// We don't need SSL to run an installer... Do we?
|
||||||
var dbSslmode = "disable"
|
var dbSslmode = "disable"
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
adapters["pgsql"] = &PgsqlInstaller{dbHost: ""}
|
adapters["pgsql"] = &PgsqlInstaller{dbHost: ""}
|
||||||
}
|
}
|
||||||
|
|
||||||
type PgsqlInstaller struct {
|
type PgsqlInstaller struct {
|
||||||
db *sql.DB
|
db *sql.DB
|
||||||
dbHost string
|
dbHost string
|
||||||
dbUsername string
|
dbUsername string
|
||||||
dbPassword string
|
dbPassword string
|
||||||
dbName string
|
dbName string
|
||||||
dbPort string
|
dbPort string
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *PgsqlInstaller) SetConfig(dbHost string, dbUsername string, dbPassword string, dbName string, dbPort string) {
|
func (ins *PgsqlInstaller) SetConfig(dbHost string, dbUsername string, dbPassword string, dbName string, dbPort string) {
|
||||||
ins.dbHost = dbHost
|
ins.dbHost = dbHost
|
||||||
ins.dbUsername = dbUsername
|
ins.dbUsername = dbUsername
|
||||||
ins.dbPassword = dbPassword
|
ins.dbPassword = dbPassword
|
||||||
ins.dbName = dbName
|
ins.dbName = dbName
|
||||||
ins.dbPort = dbPort
|
ins.dbPort = dbPort
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *PgsqlInstaller) Name() string {
|
func (ins *PgsqlInstaller) Name() string {
|
||||||
return "pgsql"
|
return "pgsql"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *PgsqlInstaller) DefaultPort() string {
|
func (ins *PgsqlInstaller) DefaultPort() string {
|
||||||
return "5432"
|
return "5432"
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *PgsqlInstaller) InitDatabase() (err error) {
|
func (ins *PgsqlInstaller) InitDatabase() (err error) {
|
||||||
_dbPassword := ins.dbPassword
|
_dbPassword := ins.dbPassword
|
||||||
if _dbPassword != "" {
|
if _dbPassword != "" {
|
||||||
_dbPassword = " password=" + pgEscapeBit(_dbPassword)
|
_dbPassword = " password=" + pgEscapeBit(_dbPassword)
|
||||||
}
|
}
|
||||||
db, err := sql.Open("postgres", "host='"+pgEscapeBit(ins.dbHost)+"' port='"+pgEscapeBit(ins.dbPort)+"' user='"+pgEscapeBit(ins.dbUsername)+"' dbname='"+pgEscapeBit(ins.dbName)+"'"+_dbPassword+" sslmode='"+dbSslmode+"'")
|
db, err := sql.Open("postgres", "host='"+pgEscapeBit(ins.dbHost)+"' port='"+pgEscapeBit(ins.dbPort)+"' user='"+pgEscapeBit(ins.dbUsername)+"' dbname='"+pgEscapeBit(ins.dbName)+"'"+_dbPassword+" sslmode='"+dbSslmode+"'")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Make sure that the connection is alive..
|
// Make sure that the connection is alive..
|
||||||
err = db.Ping()
|
err = db.Ping()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
fmt.Println("Successfully connected to the database")
|
fmt.Println("Successfully connected to the database")
|
||||||
|
|
||||||
// TODO: Create the database, if it doesn't exist
|
// TODO: Create the database, if it doesn't exist
|
||||||
|
|
||||||
// Ready the query builder
|
// Ready the query builder
|
||||||
ins.db = db
|
ins.db = db
|
||||||
qgen.Builder.SetConn(db)
|
qgen.Builder.SetConn(db)
|
||||||
return qgen.Builder.SetAdapter("pgsql")
|
return qgen.Builder.SetAdapter("pgsql")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *PgsqlInstaller) TableDefs() (err error) {
|
func (ins *PgsqlInstaller) TableDefs() (err error) {
|
||||||
return errors.New("TableDefs() not implemented")
|
return errors.New("TableDefs() not implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *PgsqlInstaller) InitialData() (err error) {
|
func (ins *PgsqlInstaller) InitialData() (err error) {
|
||||||
return errors.New("InitialData() not implemented")
|
return errors.New("InitialData() not implemented")
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *PgsqlInstaller) CreateAdmin() error {
|
func (ins *PgsqlInstaller) CreateAdmin() error {
|
||||||
return createAdmin()
|
return createAdmin()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *PgsqlInstaller) DBHost() string {
|
func (ins *PgsqlInstaller) DBHost() string {
|
||||||
return ins.dbHost
|
return ins.dbHost
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *PgsqlInstaller) DBUsername() string {
|
func (ins *PgsqlInstaller) DBUsername() string {
|
||||||
return ins.dbUsername
|
return ins.dbUsername
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *PgsqlInstaller) DBPassword() string {
|
func (ins *PgsqlInstaller) DBPassword() string {
|
||||||
return ins.dbPassword
|
return ins.dbPassword
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *PgsqlInstaller) DBName() string {
|
func (ins *PgsqlInstaller) DBName() string {
|
||||||
return ins.dbName
|
return ins.dbName
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ins *PgsqlInstaller) DBPort() string {
|
func (ins *PgsqlInstaller) DBPort() string {
|
||||||
return ins.dbPort
|
return ins.dbPort
|
||||||
}
|
}
|
||||||
|
|
||||||
func pgEscapeBit(bit string) string {
|
func pgEscapeBit(bit string) string {
|
||||||
// TODO: Write a custom parser, so that backslashes work properly in the sql.Open string. Do something similar for the database driver, if possible?
|
// TODO: Write a custom parser, so that backslashes work properly in the sql.Open string. Do something similar for the database driver, if possible?
|
||||||
return strings.Replace(bit, "'", "\\'", -1)
|
return strings.Replace(bit, "'", "\\'", -1)
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,20 +8,20 @@ const saltLength int = 32
|
||||||
|
|
||||||
// Generate a cryptographically secure set of random bytes..
|
// Generate a cryptographically secure set of random bytes..
|
||||||
func GenerateSafeString(length int) (string, error) {
|
func GenerateSafeString(length int) (string, error) {
|
||||||
rb := make([]byte, length)
|
rb := make([]byte, length)
|
||||||
_, err := rand.Read(rb)
|
_, err := rand.Read(rb)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
return base64.StdEncoding.EncodeToString(rb), nil
|
return base64.StdEncoding.EncodeToString(rb), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate a bcrypt hash
|
// Generate a bcrypt hash
|
||||||
// Note: The salt is in the hash, therefore the salt value is blank
|
// Note: The salt is in the hash, therefore the salt value is blank
|
||||||
func BcryptGeneratePassword(password string) (hash string, salt string, err error) {
|
func BcryptGeneratePassword(password string) (hash string, salt string, err error) {
|
||||||
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", "", err
|
return "", "", err
|
||||||
}
|
}
|
||||||
return string(hashedPassword), salt, nil
|
return string(hashedPassword), salt, nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -1 +0,0 @@
|
||||||
0.1.0-dev
|
|
5498
misc_test.go
5498
misc_test.go
File diff suppressed because it is too large
Load Diff
110
mysql.go
110
mysql.go
|
@ -2,81 +2,81 @@
|
||||||
|
|
||||||
/*
|
/*
|
||||||
*
|
*
|
||||||
* Gosora MySQL Interface
|
* Gosora MySQL Interface
|
||||||
* Copyright Azareal 2016 - 2020
|
* Copyright Azareal 2016 - 2020
|
||||||
*
|
*
|
||||||
*/
|
*/
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
|
|
||||||
c "github.com/Azareal/Gosora/common"
|
c "github.com/Azareal/Gosora/common"
|
||||||
qgen "github.com/Azareal/Gosora/query_gen"
|
qgen "github.com/Azareal/Gosora/query_gen"
|
||||||
_ "github.com/go-sql-driver/mysql"
|
_ "github.com/go-sql-driver/mysql"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
var dbCollation = "utf8mb4_general_ci"
|
var dbCollation = "utf8mb4_general_ci"
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
dbAdapter = "mysql"
|
dbAdapter = "mysql"
|
||||||
_initDatabase = initMySQL
|
_initDatabase = initMySQL
|
||||||
}
|
}
|
||||||
|
|
||||||
func initMySQL() (err error) {
|
func initMySQL() (err error) {
|
||||||
err = qgen.Builder.Init("mysql", map[string]string{
|
err = qgen.Builder.Init("mysql", map[string]string{
|
||||||
"host": c.DbConfig.Host,
|
"host": c.DbConfig.Host,
|
||||||
"port": c.DbConfig.Port,
|
"port": c.DbConfig.Port,
|
||||||
"name": c.DbConfig.Dbname,
|
"name": c.DbConfig.Dbname,
|
||||||
"username": c.DbConfig.Username,
|
"username": c.DbConfig.Username,
|
||||||
"password": c.DbConfig.Password,
|
"password": c.DbConfig.Password,
|
||||||
"collation": dbCollation,
|
"collation": dbCollation,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the number of max open connections
|
// Set the number of max open connections
|
||||||
db = qgen.Builder.GetConn()
|
db = qgen.Builder.GetConn()
|
||||||
db.SetMaxOpenConns(64)
|
db.SetMaxOpenConns(64)
|
||||||
db.SetMaxIdleConns(32)
|
db.SetMaxIdleConns(32)
|
||||||
//db.SetConnMaxLifetime(time.Second * 60 * 5) // Just in case we accumulate some bad connections due to the MySQL driver being stupid
|
//db.SetConnMaxLifetime(time.Second * 60 * 5) // Just in case we accumulate some bad connections due to the MySQL driver being stupid
|
||||||
|
|
||||||
// Only hold connections open for five seconds to avoid accumulating a large number of stale connections
|
// Only hold connections open for five seconds to avoid accumulating a large number of stale connections
|
||||||
//db.SetConnMaxLifetime(5 * time.Second)
|
//db.SetConnMaxLifetime(5 * time.Second)
|
||||||
db.SetConnMaxLifetime(c.DBTimeout())
|
db.SetConnMaxLifetime(c.DBTimeout())
|
||||||
|
|
||||||
// Build the generated prepared statements, we are going to slowly move the queries over to the query generator rather than writing them all by hand, this'll make it easier for us to implement database adapters for other databases like PostgreSQL, MSSQL, SQlite, etc.
|
// Build the generated prepared statements, we are going to slowly move the queries over to the query generator rather than writing them all by hand, this'll make it easier for us to implement database adapters for other databases like PostgreSQL, MSSQL, SQlite, etc.
|
||||||
err = _gen_mysql()
|
err = _gen_mysql()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Is there a less noisy way of doing this for tests?
|
// TODO: Is there a less noisy way of doing this for tests?
|
||||||
/*log.Print("Preparing getActivityFeedByWatcher statement.")
|
/*log.Print("Preparing getActivityFeedByWatcher statement.")
|
||||||
stmts.getActivityFeedByWatcher, err = db.Prepare("SELECT activity_stream_matches.asid, activity_stream.actor, activity_stream.targetUser, activity_stream.event, activity_stream.elementType, activity_stream.elementID, activity_stream.createdAt FROM `activity_stream_matches` INNER JOIN `activity_stream` ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE `watcher` = ? ORDER BY activity_stream.asid DESC LIMIT 16")
|
stmts.getActivityFeedByWatcher, err = db.Prepare("SELECT activity_stream_matches.asid, activity_stream.actor, activity_stream.targetUser, activity_stream.event, activity_stream.elementType, activity_stream.elementID, activity_stream.createdAt FROM `activity_stream_matches` INNER JOIN `activity_stream` ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE `watcher` = ? ORDER BY activity_stream.asid DESC LIMIT 16")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
log.Print("Preparing getActivityFeedByWatcher statement.")
|
log.Print("Preparing getActivityFeedByWatcher statement.")
|
||||||
stmts.getActivityFeedByWatcher, err = db.Prepare("SELECT activity_stream_matches.asid, activity_stream.actor, activity_stream.targetUser, activity_stream.event, activity_stream.elementType, activity_stream.elementID, activity_stream.createdAt FROM activity_stream_matches INNER JOIN activity_stream ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE watcher=? ORDER BY activity_stream.asid DESC LIMIT ?")
|
stmts.getActivityFeedByWatcher, err = db.Prepare("SELECT activity_stream_matches.asid, activity_stream.actor, activity_stream.targetUser, activity_stream.event, activity_stream.elementType, activity_stream.elementID, activity_stream.createdAt FROM activity_stream_matches INNER JOIN activity_stream ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE watcher=? ORDER BY activity_stream.asid DESC LIMIT ?")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
/*log.Print("Preparing getActivityFeedByWatcherAfter statement.")
|
/*log.Print("Preparing getActivityFeedByWatcherAfter statement.")
|
||||||
stmts.getActivityFeedByWatcherAfter, err = db.Prepare("SELECT activity_stream_matches.asid, activity_stream.actor, activity_stream.targetUser, activity_stream.event, activity_stream.elementType, activity_stream.elementID, activity_stream.createdAt FROM activity_stream_matches INNER JOIN activity_stream ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE watcher=? AND asid => ? ORDER BY activity_stream.asid DESC LIMIT ?")
|
stmts.getActivityFeedByWatcherAfter, err = db.Prepare("SELECT activity_stream_matches.asid, activity_stream.actor, activity_stream.targetUser, activity_stream.event, activity_stream.elementType, activity_stream.elementID, activity_stream.createdAt FROM activity_stream_matches INNER JOIN activity_stream ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE watcher=? AND asid => ? ORDER BY activity_stream.asid DESC LIMIT ?")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}*/
|
}*/
|
||||||
|
|
||||||
log.Print("Preparing getActivityCountByWatcher statement.")
|
log.Print("Preparing getActivityCountByWatcher statement.")
|
||||||
stmts.getActivityCountByWatcher, err = db.Prepare("SELECT count(*) FROM activity_stream_matches INNER JOIN activity_stream ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE watcher=?")
|
stmts.getActivityCountByWatcher, err = db.Prepare("SELECT count(*) FROM activity_stream_matches INNER JOIN activity_stream ON activity_stream_matches.asid = activity_stream.asid AND activity_stream_matches.watcher != activity_stream.actor WHERE watcher=?")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return errors.WithStack(err)
|
return errors.WithStack(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,24 +1,24 @@
|
||||||
{
|
{
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"newcap": false,
|
"newcap": false,
|
||||||
"node": true,
|
"node": true,
|
||||||
"expr": true,
|
"expr": true,
|
||||||
"supernew": true,
|
"supernew": true,
|
||||||
"laxbreak": true,
|
"laxbreak": true,
|
||||||
"white": true,
|
"white": true,
|
||||||
"globals": {
|
"globals": {
|
||||||
"define": true,
|
"define": true,
|
||||||
"test": true,
|
"test": true,
|
||||||
"expect": true,
|
"expect": true,
|
||||||
"module": true,
|
"module": true,
|
||||||
"asyncTest": true,
|
"asyncTest": true,
|
||||||
"start": true,
|
"start": true,
|
||||||
"ok": true,
|
"ok": true,
|
||||||
"equal": true,
|
"equal": true,
|
||||||
"notEqual": true,
|
"notEqual": true,
|
||||||
"deepEqual": true,
|
"deepEqual": true,
|
||||||
"window": true,
|
"window": true,
|
||||||
"document": true,
|
"document": true,
|
||||||
"performance": true
|
"performance": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -33,9 +33,9 @@ Demo: http://rubaxa.github.io/Sortable/
|
||||||
### Usage
|
### Usage
|
||||||
```html
|
```html
|
||||||
<ul id="items">
|
<ul id="items">
|
||||||
<li>item 1</li>
|
<li>item 1</li>
|
||||||
<li>item 2</li>
|
<li>item 2</li>
|
||||||
<li>item 3</li>
|
<li>item 3</li>
|
||||||
</ul>
|
</ul>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -53,79 +53,79 @@ You can use any element for the list and its elements, not just `ul`/`li`. Here
|
||||||
### Options
|
### Options
|
||||||
```js
|
```js
|
||||||
var sortable = new Sortable(el, {
|
var sortable = new Sortable(el, {
|
||||||
group: "name", // or { name: "...", pull: [true, false, clone], put: [true, false, array] }
|
group: "name", // or { name: "...", pull: [true, false, clone], put: [true, false, array] }
|
||||||
sort: true, // sorting inside list
|
sort: true, // sorting inside list
|
||||||
delay: 0, // time in milliseconds to define when the sorting should start
|
delay: 0, // time in milliseconds to define when the sorting should start
|
||||||
disabled: false, // Disables the sortable if set to true.
|
disabled: false, // Disables the sortable if set to true.
|
||||||
store: null, // @see Store
|
store: null, // @see Store
|
||||||
animation: 150, // ms, animation speed moving items when sorting, `0` — without animation
|
animation: 150, // ms, animation speed moving items when sorting, `0` — without animation
|
||||||
handle: ".my-handle", // Drag handle selector within list items
|
handle: ".my-handle", // Drag handle selector within list items
|
||||||
filter: ".ignore-elements", // Selectors that do not lead to dragging (String or Function)
|
filter: ".ignore-elements", // Selectors that do not lead to dragging (String or Function)
|
||||||
draggable: ".item", // Specifies which items inside the element should be sortable
|
draggable: ".item", // Specifies which items inside the element should be sortable
|
||||||
ghostClass: "sortable-ghost", // Class name for the drop placeholder
|
ghostClass: "sortable-ghost", // Class name for the drop placeholder
|
||||||
chosenClass: "sortable-chosen", // Class name for the chosen item
|
chosenClass: "sortable-chosen", // Class name for the chosen item
|
||||||
dataIdAttr: 'data-id',
|
dataIdAttr: 'data-id',
|
||||||
|
|
||||||
forceFallback: false, // ignore the HTML5 DnD behaviour and force the fallback to kick in
|
forceFallback: false, // ignore the HTML5 DnD behaviour and force the fallback to kick in
|
||||||
fallbackClass: "sortable-fallback" // Class name for the cloned DOM Element when using forceFallback
|
fallbackClass: "sortable-fallback" // Class name for the cloned DOM Element when using forceFallback
|
||||||
fallbackOnBody: false // Appends the cloned DOM Element into the Document's Body
|
fallbackOnBody: false // Appends the cloned DOM Element into the Document's Body
|
||||||
|
|
||||||
scroll: true, // or HTMLElement
|
scroll: true, // or HTMLElement
|
||||||
scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling.
|
scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling.
|
||||||
scrollSpeed: 10, // px
|
scrollSpeed: 10, // px
|
||||||
|
|
||||||
setData: function (dataTransfer, dragEl) {
|
setData: function (dataTransfer, dragEl) {
|
||||||
dataTransfer.setData('Text', dragEl.textContent);
|
dataTransfer.setData('Text', dragEl.textContent);
|
||||||
},
|
},
|
||||||
|
|
||||||
// dragging started
|
// dragging started
|
||||||
onStart: function (/**Event*/evt) {
|
onStart: function (/**Event*/evt) {
|
||||||
evt.oldIndex; // element index within parent
|
evt.oldIndex; // element index within parent
|
||||||
},
|
},
|
||||||
|
|
||||||
// dragging ended
|
// dragging ended
|
||||||
onEnd: function (/**Event*/evt) {
|
onEnd: function (/**Event*/evt) {
|
||||||
evt.oldIndex; // element's old index within parent
|
evt.oldIndex; // element's old index within parent
|
||||||
evt.newIndex; // element's new index within parent
|
evt.newIndex; // element's new index within parent
|
||||||
},
|
},
|
||||||
|
|
||||||
// Element is dropped into the list from another list
|
// Element is dropped into the list from another list
|
||||||
onAdd: function (/**Event*/evt) {
|
onAdd: function (/**Event*/evt) {
|
||||||
var itemEl = evt.item; // dragged HTMLElement
|
var itemEl = evt.item; // dragged HTMLElement
|
||||||
evt.from; // previous list
|
evt.from; // previous list
|
||||||
// + indexes from onEnd
|
// + indexes from onEnd
|
||||||
},
|
},
|
||||||
|
|
||||||
// Changed sorting within list
|
// Changed sorting within list
|
||||||
onUpdate: function (/**Event*/evt) {
|
onUpdate: function (/**Event*/evt) {
|
||||||
var itemEl = evt.item; // dragged HTMLElement
|
var itemEl = evt.item; // dragged HTMLElement
|
||||||
// + indexes from onEnd
|
// + indexes from onEnd
|
||||||
},
|
},
|
||||||
|
|
||||||
// Called by any change to the list (add / update / remove)
|
// Called by any change to the list (add / update / remove)
|
||||||
onSort: function (/**Event*/evt) {
|
onSort: function (/**Event*/evt) {
|
||||||
// same properties as onUpdate
|
// same properties as onUpdate
|
||||||
},
|
},
|
||||||
|
|
||||||
// Element is removed from the list into another list
|
// Element is removed from the list into another list
|
||||||
onRemove: function (/**Event*/evt) {
|
onRemove: function (/**Event*/evt) {
|
||||||
// same properties as onUpdate
|
// same properties as onUpdate
|
||||||
},
|
},
|
||||||
|
|
||||||
// Attempt to drag a filtered element
|
// Attempt to drag a filtered element
|
||||||
onFilter: function (/**Event*/evt) {
|
onFilter: function (/**Event*/evt) {
|
||||||
var itemEl = evt.item; // HTMLElement receiving the `mousedown|tapstart` event.
|
var itemEl = evt.item; // HTMLElement receiving the `mousedown|tapstart` event.
|
||||||
},
|
},
|
||||||
|
|
||||||
// Event when you move an item in the list or between lists
|
// Event when you move an item in the list or between lists
|
||||||
onMove: function (/**Event*/evt) {
|
onMove: function (/**Event*/evt) {
|
||||||
// Example: http://jsbin.com/tuyafe/1/edit?js,output
|
// Example: http://jsbin.com/tuyafe/1/edit?js,output
|
||||||
evt.dragged; // dragged HTMLElement
|
evt.dragged; // dragged HTMLElement
|
||||||
evt.draggedRect; // TextRectangle {left, top, right и bottom}
|
evt.draggedRect; // TextRectangle {left, top, right и bottom}
|
||||||
evt.related; // HTMLElement on which have guided
|
evt.related; // HTMLElement on which have guided
|
||||||
evt.relatedRect; // TextRectangle
|
evt.relatedRect; // TextRectangle
|
||||||
// return false; — for cancel
|
// return false; — for cancel
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -172,9 +172,9 @@ Demo: http://jsbin.com/xiloqu/1/edit?html,js,output
|
||||||
var sortable = Sortable.create(list);
|
var sortable = Sortable.create(list);
|
||||||
|
|
||||||
document.getElementById("switcher").onclick = function () {
|
document.getElementById("switcher").onclick = function () {
|
||||||
var state = sortable.option("disabled"); // get
|
var state = sortable.option("disabled"); // get
|
||||||
|
|
||||||
sortable.option("disabled", !state); // set
|
sortable.option("disabled", !state); // set
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -191,21 +191,21 @@ Demo: http://jsbin.com/newize/1/edit?html,js,output
|
||||||
|
|
||||||
```js
|
```js
|
||||||
Sortable.create(el, {
|
Sortable.create(el, {
|
||||||
handle: ".my-handle"
|
handle: ".my-handle"
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<ul>
|
<ul>
|
||||||
<li><span class="my-handle">::</span> list item text one
|
<li><span class="my-handle">::</span> list item text one
|
||||||
<li><span class="my-handle">::</span> list item text two
|
<li><span class="my-handle">::</span> list item text two
|
||||||
</ul>
|
</ul>
|
||||||
```
|
```
|
||||||
|
|
||||||
```css
|
```css
|
||||||
.my-handle {
|
.my-handle {
|
||||||
cursor: move;
|
cursor: move;
|
||||||
cursor: -webkit-grabbing;
|
cursor: -webkit-grabbing;
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -218,18 +218,18 @@ Sortable.create(el, {
|
||||||
|
|
||||||
```js
|
```js
|
||||||
Sortable.create(list, {
|
Sortable.create(list, {
|
||||||
filter: ".js-remove, .js-edit",
|
filter: ".js-remove, .js-edit",
|
||||||
onFilter: function (evt) {
|
onFilter: function (evt) {
|
||||||
var item = evt.item,
|
var item = evt.item,
|
||||||
ctrl = evt.target;
|
ctrl = evt.target;
|
||||||
|
|
||||||
if (Sortable.utils.is(ctrl, ".js-remove")) { // Click on remove button
|
if (Sortable.utils.is(ctrl, ".js-remove")) { // Click on remove button
|
||||||
item.parentNode.removeChild(item); // remove sortable item
|
item.parentNode.removeChild(item); // remove sortable item
|
||||||
}
|
}
|
||||||
else if (Sortable.utils.is(ctrl, ".js-edit")) { // Click on edit link
|
else if (Sortable.utils.is(ctrl, ".js-edit")) { // Click on edit link
|
||||||
// ...
|
// ...
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -326,35 +326,35 @@ Demo: http://jsbin.com/naduvo/1/edit?html,js,output
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<div ng-app="myApp" ng-controller="demo">
|
<div ng-app="myApp" ng-controller="demo">
|
||||||
<ul ng-sortable>
|
<ul ng-sortable>
|
||||||
<li ng-repeat="item in items">{{item}}</li>
|
<li ng-repeat="item in items">{{item}}</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<ul ng-sortable="{ group: 'foobar' }">
|
<ul ng-sortable="{ group: 'foobar' }">
|
||||||
<li ng-repeat="item in foo">{{item}}</li>
|
<li ng-repeat="item in foo">{{item}}</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<ul ng-sortable="barConfig">
|
<ul ng-sortable="barConfig">
|
||||||
<li ng-repeat="item in bar">{{item}}</li>
|
<li ng-repeat="item in bar">{{item}}</li>
|
||||||
</ul>
|
</ul>
|
||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
```js
|
```js
|
||||||
angular.module('myApp', ['ng-sortable'])
|
angular.module('myApp', ['ng-sortable'])
|
||||||
.controller('demo', ['$scope', function ($scope) {
|
.controller('demo', ['$scope', function ($scope) {
|
||||||
$scope.items = ['item 1', 'item 2'];
|
$scope.items = ['item 1', 'item 2'];
|
||||||
$scope.foo = ['foo 1', '..'];
|
$scope.foo = ['foo 1', '..'];
|
||||||
$scope.bar = ['bar 1', '..'];
|
$scope.bar = ['bar 1', '..'];
|
||||||
$scope.barConfig = {
|
$scope.barConfig = {
|
||||||
group: 'foobar',
|
group: 'foobar',
|
||||||
animation: 150,
|
animation: 150,
|
||||||
onSort: function (/** ngSortEvent */evt){
|
onSort: function (/** ngSortEvent */evt){
|
||||||
// @see https://github.com/RubaXa/Sortable/blob/master/ng-sortable.js#L18-L24
|
// @see https://github.com/RubaXa/Sortable/blob/master/ng-sortable.js#L18-L24
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}]);
|
}]);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
|
@ -369,23 +369,23 @@ See [more options](react-sortable-mixin.js#L26).
|
||||||
|
|
||||||
```jsx
|
```jsx
|
||||||
var SortableList = React.createClass({
|
var SortableList = React.createClass({
|
||||||
mixins: [SortableMixin],
|
mixins: [SortableMixin],
|
||||||
|
|
||||||
getInitialState: function() {
|
getInitialState: function() {
|
||||||
return {
|
return {
|
||||||
items: ['Mixin', 'Sortable']
|
items: ['Mixin', 'Sortable']
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
handleSort: function (/** Event */evt) { /*..*/ },
|
handleSort: function (/** Event */evt) { /*..*/ },
|
||||||
|
|
||||||
render: function() {
|
render: function() {
|
||||||
return <ul>{
|
return <ul>{
|
||||||
this.state.items.map(function (text) {
|
this.state.items.map(function (text) {
|
||||||
return <li>{text}</li>
|
return <li>{text}</li>
|
||||||
})
|
})
|
||||||
}</ul>
|
}</ul>
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
React.render(<SortableList />, document.body);
|
React.render(<SortableList />, document.body);
|
||||||
|
@ -395,51 +395,51 @@ React.render(<SortableList />, document.body);
|
||||||
// Groups
|
// Groups
|
||||||
//
|
//
|
||||||
var AllUsers = React.createClass({
|
var AllUsers = React.createClass({
|
||||||
mixins: [SortableMixin],
|
mixins: [SortableMixin],
|
||||||
|
|
||||||
sortableOptions: {
|
sortableOptions: {
|
||||||
ref: "user",
|
ref: "user",
|
||||||
group: "shared",
|
group: "shared",
|
||||||
model: "users"
|
model: "users"
|
||||||
},
|
},
|
||||||
|
|
||||||
getInitialState: function() {
|
getInitialState: function() {
|
||||||
return { users: ['Abbi', 'Adela', 'Bud', 'Cate', 'Davis', 'Eric']; };
|
return { users: ['Abbi', 'Adela', 'Bud', 'Cate', 'Davis', 'Eric']; };
|
||||||
},
|
},
|
||||||
|
|
||||||
render: function() {
|
render: function() {
|
||||||
return (
|
return (
|
||||||
<h1>Users</h1>
|
<h1>Users</h1>
|
||||||
<ul ref="user">{
|
<ul ref="user">{
|
||||||
this.state.users.map(function (text) {
|
this.state.users.map(function (text) {
|
||||||
return <li>{text}</li>
|
return <li>{text}</li>
|
||||||
})
|
})
|
||||||
}</ul>
|
}</ul>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
var ApprovedUsers = React.createClass({
|
var ApprovedUsers = React.createClass({
|
||||||
mixins: [SortableMixin],
|
mixins: [SortableMixin],
|
||||||
sortableOptions: { group: "shared" },
|
sortableOptions: { group: "shared" },
|
||||||
|
|
||||||
getInitialState: function() {
|
getInitialState: function() {
|
||||||
return { items: ['Hal', 'Judy']; };
|
return { items: ['Hal', 'Judy']; };
|
||||||
},
|
},
|
||||||
|
|
||||||
render: function() {
|
render: function() {
|
||||||
return <ul>{
|
return <ul>{
|
||||||
this.state.items.map(function (text) {
|
this.state.items.map(function (text) {
|
||||||
return <li>{text}</li>
|
return <li>{text}</li>
|
||||||
})
|
})
|
||||||
}</ul>
|
}</ul>
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
React.render(<div>
|
React.render(<div>
|
||||||
<AllUsers/>
|
<AllUsers/>
|
||||||
<hr/>
|
<hr/>
|
||||||
<ApprovedUsers/>
|
<ApprovedUsers/>
|
||||||
</div>, document.body);
|
</div>, document.body);
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -453,11 +453,11 @@ Include [knockout-sortable.js](knockout-sortable.js)
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<div data-bind="sortable: {foreach: yourObservableArray, options: {/* sortable options here */}}">
|
<div data-bind="sortable: {foreach: yourObservableArray, options: {/* sortable options here */}}">
|
||||||
<!-- optional item template here -->
|
<!-- optional item template here -->
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div data-bind="draggable: {foreach: yourObservableArray, options: {/* sortable options here */}}">
|
<div data-bind="draggable: {foreach: yourObservableArray, options: {/* sortable options here */}}">
|
||||||
<!-- optional item template here -->
|
<!-- optional item template here -->
|
||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -466,8 +466,8 @@ Using this bindingHandler sorts the observableArray when the user sorts the HTML
|
||||||
The sortable/draggable bindingHandlers supports the same syntax as Knockouts built in [template](http://knockoutjs.com/documentation/template-binding.html) binding except for the `data` option, meaning that you could supply the name of a template or specify a separate templateEngine. The difference between the sortable and draggable handlers is that the draggable has the sortable `group` option set to `{pull:'clone',put: false}` and the `sort` option set to false by default (overridable).
|
The sortable/draggable bindingHandlers supports the same syntax as Knockouts built in [template](http://knockoutjs.com/documentation/template-binding.html) binding except for the `data` option, meaning that you could supply the name of a template or specify a separate templateEngine. The difference between the sortable and draggable handlers is that the draggable has the sortable `group` option set to `{pull:'clone',put: false}` and the `sort` option set to false by default (overridable).
|
||||||
|
|
||||||
Other attributes are:
|
Other attributes are:
|
||||||
* options: an object that contains settings for the underlaying sortable, ie `group`,`handle`, events etc.
|
* options: an object that contains settings for the underlaying sortable, ie `group`,`handle`, events etc.
|
||||||
* collection: if your `foreach` array is a computed then you would supply the underlaying observableArray that you would like to sort here.
|
* collection: if your `foreach` array is a computed then you would supply the underlaying observableArray that you would like to sort here.
|
||||||
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
@ -527,35 +527,35 @@ Saving and restoring of the sort.
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<ul>
|
<ul>
|
||||||
<li data-id="1">order</li>
|
<li data-id="1">order</li>
|
||||||
<li data-id="2">save</li>
|
<li data-id="2">save</li>
|
||||||
<li data-id="3">restore</li>
|
<li data-id="3">restore</li>
|
||||||
</ul>
|
</ul>
|
||||||
```
|
```
|
||||||
|
|
||||||
```js
|
```js
|
||||||
Sortable.create(el, {
|
Sortable.create(el, {
|
||||||
group: "localStorage-example",
|
group: "localStorage-example",
|
||||||
store: {
|
store: {
|
||||||
/**
|
/**
|
||||||
* Get the order of elements. Called once during initialization.
|
* Get the order of elements. Called once during initialization.
|
||||||
* @param {Sortable} sortable
|
* @param {Sortable} sortable
|
||||||
* @returns {Array}
|
* @returns {Array}
|
||||||
*/
|
*/
|
||||||
get: function (sortable) {
|
get: function (sortable) {
|
||||||
var order = localStorage.getItem(sortable.options.group);
|
var order = localStorage.getItem(sortable.options.group);
|
||||||
return order ? order.split('|') : [];
|
return order ? order.split('|') : [];
|
||||||
},
|
},
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Save the order of elements. Called onEnd (when the item is dropped).
|
* Save the order of elements. Called onEnd (when the item is dropped).
|
||||||
* @param {Sortable} sortable
|
* @param {Sortable} sortable
|
||||||
*/
|
*/
|
||||||
set: function (sortable) {
|
set: function (sortable) {
|
||||||
var order = sortable.toArray();
|
var order = sortable.toArray();
|
||||||
localStorage.setItem(sortable.options.group, order.join('|'));
|
localStorage.setItem(sortable.options.group, order.join('|'));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
|
@ -578,11 +578,11 @@ Demo: http://jsbin.com/luxero/2/edit?html,js,output
|
||||||
|
|
||||||
<!-- Simple List -->
|
<!-- Simple List -->
|
||||||
<ul id="simpleList" class="list-group">
|
<ul id="simpleList" class="list-group">
|
||||||
<li class="list-group-item">This is <a href="http://rubaxa.github.io/Sortable/">Sortable</a></li>
|
<li class="list-group-item">This is <a href="http://rubaxa.github.io/Sortable/">Sortable</a></li>
|
||||||
<li class="list-group-item">It works with Bootstrap...</li>
|
<li class="list-group-item">It works with Bootstrap...</li>
|
||||||
<li class="list-group-item">...out of the box.</li>
|
<li class="list-group-item">...out of the box.</li>
|
||||||
<li class="list-group-item">It has support for touch devices.</li>
|
<li class="list-group-item">It has support for touch devices.</li>
|
||||||
<li class="list-group-item">Just drag some elements around.</li>
|
<li class="list-group-item">Just drag some elements around.</li>
|
||||||
</ul>
|
</ul>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,10 +1,10 @@
|
||||||
{
|
{
|
||||||
"name": "Sortable",
|
"name": "Sortable",
|
||||||
"main": [
|
"main": [
|
||||||
"Sortable.js",
|
"Sortable.js",
|
||||||
"ng-sortable.js",
|
"ng-sortable.js",
|
||||||
"knockout-sortable.js",
|
"knockout-sortable.js",
|
||||||
"react-sortable-mixin.js"
|
"react-sortable-mixin.js"
|
||||||
],
|
],
|
||||||
"homepage": "http://rubaxa.github.io/Sortable/",
|
"homepage": "http://rubaxa.github.io/Sortable/",
|
||||||
"authors": [
|
"authors": [
|
||||||
|
@ -20,7 +20,7 @@
|
||||||
"and",
|
"and",
|
||||||
"drop",
|
"drop",
|
||||||
"dnd",
|
"dnd",
|
||||||
"web-components"
|
"web-components"
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"ignore": [
|
"ignore": [
|
||||||
|
@ -31,5 +31,5 @@
|
||||||
],
|
],
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"polymer": "Polymer/polymer#~1.1.4",
|
"polymer": "Polymer/polymer#~1.1.4",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,61 +1,61 @@
|
||||||
/**
|
/**
|
||||||
* jQuery plugin for Sortable
|
* jQuery plugin for Sortable
|
||||||
* @author RubaXa <trash@rubaxa.org>
|
* @author RubaXa <trash@rubaxa.org>
|
||||||
* @license MIT
|
* @license MIT
|
||||||
*/
|
*/
|
||||||
(function (factory) {
|
(function (factory) {
|
||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
if (typeof define === "function" && define.amd) {
|
if (typeof define === "function" && define.amd) {
|
||||||
define(["jquery"], factory);
|
define(["jquery"], factory);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
/* jshint sub:true */
|
/* jshint sub:true */
|
||||||
factory(jQuery);
|
factory(jQuery);
|
||||||
}
|
}
|
||||||
})(function ($) {
|
})(function ($) {
|
||||||
"use strict";
|
"use strict";
|
||||||
|
|
||||||
|
|
||||||
/* CODE */
|
/* CODE */
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* jQuery plugin for Sortable
|
* jQuery plugin for Sortable
|
||||||
* @param {Object|String} options
|
* @param {Object|String} options
|
||||||
* @param {..*} [args]
|
* @param {..*} [args]
|
||||||
* @returns {jQuery|*}
|
* @returns {jQuery|*}
|
||||||
*/
|
*/
|
||||||
$.fn.sortable = function (options) {
|
$.fn.sortable = function (options) {
|
||||||
var retVal,
|
var retVal,
|
||||||
args = arguments;
|
args = arguments;
|
||||||
|
|
||||||
this.each(function () {
|
this.each(function () {
|
||||||
var $el = $(this),
|
var $el = $(this),
|
||||||
sortable = $el.data('sortable');
|
sortable = $el.data('sortable');
|
||||||
|
|
||||||
if (!sortable && (options instanceof Object || !options)) {
|
if (!sortable && (options instanceof Object || !options)) {
|
||||||
sortable = new Sortable(this, options);
|
sortable = new Sortable(this, options);
|
||||||
$el.data('sortable', sortable);
|
$el.data('sortable', sortable);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (sortable) {
|
if (sortable) {
|
||||||
if (options === 'widget') {
|
if (options === 'widget') {
|
||||||
return sortable;
|
return sortable;
|
||||||
}
|
}
|
||||||
else if (options === 'destroy') {
|
else if (options === 'destroy') {
|
||||||
sortable.destroy();
|
sortable.destroy();
|
||||||
$el.removeData('sortable');
|
$el.removeData('sortable');
|
||||||
}
|
}
|
||||||
else if (typeof sortable[options] === 'function') {
|
else if (typeof sortable[options] === 'function') {
|
||||||
retVal = sortable[options].apply(sortable, [].slice.call(args, 1));
|
retVal = sortable[options].apply(sortable, [].slice.call(args, 1));
|
||||||
}
|
}
|
||||||
else if (options in sortable.options) {
|
else if (options in sortable.options) {
|
||||||
retVal = sortable.option.apply(sortable, args);
|
retVal = sortable.option.apply(sortable, args);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return (retVal === void 0) ? this : retVal;
|
return (retVal === void 0) ? this : retVal;
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
|
@ -2,8 +2,8 @@
|
||||||
|
|
||||||
(() => {
|
(() => {
|
||||||
addInitHook("end_init", () => {
|
addInitHook("end_init", () => {
|
||||||
$("#dash_username input").click(()=>{
|
$("#dash_username input").click(()=>{
|
||||||
$("#dash_username button").show();
|
$("#dash_username button").show();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
})()
|
})()
|
|
@ -1,74 +1,74 @@
|
||||||
function memStuff(window,document,Chartist) {
|
function memStuff(window,document,Chartist) {
|
||||||
'use strict';
|
'use strict';
|
||||||
Chartist.plugins = Chartist.plugins || {};
|
Chartist.plugins = Chartist.plugins || {};
|
||||||
Chartist.plugins.byteUnits = function(options) {
|
Chartist.plugins.byteUnits = function(options) {
|
||||||
options = Chartist.extend({},{},options);
|
options = Chartist.extend({},{},options);
|
||||||
|
|
||||||
return function byteUnits(chart) {
|
return function byteUnits(chart) {
|
||||||
if(!chart instanceof Chartist.Line) return;
|
if(!chart instanceof Chartist.Line) return;
|
||||||
|
|
||||||
chart.on('created', function() {
|
chart.on('created', function() {
|
||||||
log("running created")
|
log("running created")
|
||||||
const vbits = document.getElementsByClassName("ct-vertical");
|
const vbits = document.getElementsByClassName("ct-vertical");
|
||||||
if(vbits==null) return;
|
if(vbits==null) return;
|
||||||
|
|
||||||
let tbits = [];
|
let tbits = [];
|
||||||
for(let i=0; i<vbits.length; i++) {
|
for(let i=0; i<vbits.length; i++) {
|
||||||
tbits[i] = vbits[i].innerHTML;
|
tbits[i] = vbits[i].innerHTML;
|
||||||
}
|
}
|
||||||
log("tbits",tbits);
|
log("tbits",tbits);
|
||||||
|
|
||||||
const calc = (places) => {
|
const calc = (places) => {
|
||||||
if(places==3) return;
|
if(places==3) return;
|
||||||
|
|
||||||
const matcher = vbits[0].innerHTML;
|
const matcher = vbits[0].innerHTML;
|
||||||
let allMatch = true;
|
let allMatch = true;
|
||||||
for(let i=0; i<tbits.length; i++) {
|
for(let i=0; i<tbits.length; i++) {
|
||||||
let val = convertByteUnit(tbits[i], places);
|
let val = convertByteUnit(tbits[i], places);
|
||||||
if(val!=matcher) allMatch = false;
|
if(val!=matcher) allMatch = false;
|
||||||
vbits[i].innerHTML = val;
|
vbits[i].innerHTML = val;
|
||||||
}
|
}
|
||||||
if(allMatch) calc(places + 1);
|
if(allMatch) calc(places + 1);
|
||||||
}
|
}
|
||||||
calc(0);
|
calc(0);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function perfStuff(window,document,Chartist) {
|
function perfStuff(window,document,Chartist) {
|
||||||
'use strict';
|
'use strict';
|
||||||
Chartist.plugins = Chartist.plugins || {};
|
Chartist.plugins = Chartist.plugins || {};
|
||||||
Chartist.plugins.perfUnits = function(options) {
|
Chartist.plugins.perfUnits = function(options) {
|
||||||
options = Chartist.extend({},{},options);
|
options = Chartist.extend({},{},options);
|
||||||
|
|
||||||
return function perfUnits(chart) {
|
return function perfUnits(chart) {
|
||||||
if(!chart instanceof Chartist.Line) return;
|
if(!chart instanceof Chartist.Line) return;
|
||||||
|
|
||||||
chart.on('created', function() {
|
chart.on('created', function() {
|
||||||
log("running created")
|
log("running created")
|
||||||
const vbits = document.getElementsByClassName("ct-vertical");
|
const vbits = document.getElementsByClassName("ct-vertical");
|
||||||
if(vbits==null) return;
|
if(vbits==null) return;
|
||||||
|
|
||||||
let tbits = [];
|
let tbits = [];
|
||||||
for(let i=0; i<vbits.length; i++) {
|
for(let i=0; i<vbits.length; i++) {
|
||||||
tbits[i] = vbits[i].innerHTML;
|
tbits[i] = vbits[i].innerHTML;
|
||||||
}
|
}
|
||||||
log("tbits:",tbits);
|
log("tbits:",tbits);
|
||||||
|
|
||||||
const calc = (places) => {
|
const calc = (places) => {
|
||||||
if(places==3) return;
|
if(places==3) return;
|
||||||
|
|
||||||
const matcher = vbits[0].innerHTML;
|
const matcher = vbits[0].innerHTML;
|
||||||
let allMatch = true;
|
let allMatch = true;
|
||||||
for(let i=0; i<tbits.length; i++) {
|
for(let i=0; i<tbits.length; i++) {
|
||||||
let val = convertPerfUnit(tbits[i], places);
|
let val = convertPerfUnit(tbits[i], places);
|
||||||
if(val!=matcher) allMatch = false;
|
if(val!=matcher) allMatch = false;
|
||||||
vbits[i].innerHTML = val;
|
vbits[i].innerHTML = val;
|
||||||
}
|
}
|
||||||
if(allMatch) calc(places + 1);
|
if(allMatch) calc(places + 1);
|
||||||
}
|
}
|
||||||
calc(0);
|
calc(0);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
@ -81,19 +81,19 @@ const Terabyte = Gigabyte * 1024;
|
||||||
const Petabyte = Terabyte * 1024;
|
const Petabyte = Terabyte * 1024;
|
||||||
|
|
||||||
function convertByteUnit(bytes, places = 0) {
|
function convertByteUnit(bytes, places = 0) {
|
||||||
let o;
|
let o;
|
||||||
if(bytes >= Petabyte) o = [bytes / Petabyte, "PB"];
|
if(bytes >= Petabyte) o = [bytes / Petabyte, "PB"];
|
||||||
else if(bytes >= Terabyte) o = [bytes / Terabyte, "TB"];
|
else if(bytes >= Terabyte) o = [bytes / Terabyte, "TB"];
|
||||||
else if(bytes >= Gigabyte) o = [bytes / Gigabyte, "GB"];
|
else if(bytes >= Gigabyte) o = [bytes / Gigabyte, "GB"];
|
||||||
else if(bytes >= Megabyte) o = [bytes / Megabyte, "MB"];
|
else if(bytes >= Megabyte) o = [bytes / Megabyte, "MB"];
|
||||||
else if(bytes >= Kilobyte) o = [bytes / Kilobyte, "KB"];
|
else if(bytes >= Kilobyte) o = [bytes / Kilobyte, "KB"];
|
||||||
else o = [bytes,"b"];
|
else o = [bytes,"b"];
|
||||||
|
|
||||||
if(places==0) return Math.ceil(o[0]) + o[1];
|
if(places==0) return Math.ceil(o[0]) + o[1];
|
||||||
else {
|
else {
|
||||||
let ex = Math.pow(10, places);
|
let ex = Math.pow(10, places);
|
||||||
return (Math.round(o[0], ex) / ex) + o[1];
|
return (Math.round(o[0], ex) / ex) + o[1];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let ms = 1000;
|
let ms = 1000;
|
||||||
|
@ -102,89 +102,89 @@ let min = sec * 60;
|
||||||
let hour = min * 60;
|
let hour = min * 60;
|
||||||
let day = hour * 24;
|
let day = hour * 24;
|
||||||
function convertPerfUnit(quan, places = 0) {
|
function convertPerfUnit(quan, places = 0) {
|
||||||
let o;
|
let o;
|
||||||
if(quan >= day) o = [quan / day, "d"];
|
if(quan >= day) o = [quan / day, "d"];
|
||||||
else if(quan >= hour) o = [quan / hour, "h"];
|
else if(quan >= hour) o = [quan / hour, "h"];
|
||||||
else if(quan >= min) o = [quan / min, "m"];
|
else if(quan >= min) o = [quan / min, "m"];
|
||||||
else if(quan >= sec) o = [quan / sec, "s"];
|
else if(quan >= sec) o = [quan / sec, "s"];
|
||||||
else if(quan >= ms) o = [quan / ms, "ms"];
|
else if(quan >= ms) o = [quan / ms, "ms"];
|
||||||
else o = [quan,"μs"];
|
else o = [quan,"μs"];
|
||||||
|
|
||||||
if(places==0) return Math.ceil(o[0]) + o[1];
|
if(places==0) return Math.ceil(o[0]) + o[1];
|
||||||
else {
|
else {
|
||||||
let ex = Math.pow(10, places);
|
let ex = Math.pow(10, places);
|
||||||
return (Math.round(o[0], ex) / ex) + o[1];
|
return (Math.round(o[0], ex) / ex) + o[1];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Fully localise this
|
// TODO: Fully localise this
|
||||||
// TODO: Load rawLabels and seriesData dynamically rather than potentially fiddling with nonces for the CSP?
|
// TODO: Load rawLabels and seriesData dynamically rather than potentially fiddling with nonces for the CSP?
|
||||||
function buildStatsChart(rawLabels, seriesData, timeRange, legendNames, typ=0) {
|
function buildStatsChart(rawLabels, seriesData, timeRange, legendNames, typ=0) {
|
||||||
log("buildStatsChart");
|
log("buildStatsChart");
|
||||||
log("seriesData",seriesData);
|
log("seriesData",seriesData);
|
||||||
let labels = [];
|
let labels = [];
|
||||||
let aphrases = phraseBox["analytics"];
|
let aphrases = phraseBox["analytics"];
|
||||||
if(timeRange=="one-year") {
|
if(timeRange=="one-year") {
|
||||||
labels = [aphrases["analytics.now"],"1" + aphrases["analytics.months_short"]];
|
labels = [aphrases["analytics.now"],"1" + aphrases["analytics.months_short"]];
|
||||||
for(let i = 2; i < 12; i++) {
|
for(let i = 2; i < 12; i++) {
|
||||||
labels.push(i + aphrases["analytics.months_short"]);
|
labels.push(i + aphrases["analytics.months_short"]);
|
||||||
}
|
}
|
||||||
} else if(timeRange=="three-months") {
|
} else if(timeRange=="three-months") {
|
||||||
labels = [aphrases["analytics.now"],"3" + aphrases["analytics.days_short"]]
|
labels = [aphrases["analytics.now"],"3" + aphrases["analytics.days_short"]]
|
||||||
for(let i = 6; i < 90; i = i + 3) {
|
for(let i = 6; i < 90; i = i + 3) {
|
||||||
if (i%2==0) labels.push("");
|
if (i%2==0) labels.push("");
|
||||||
else labels.push(i + aphrases["analytics.days_short"]);
|
else labels.push(i + aphrases["analytics.days_short"]);
|
||||||
}
|
}
|
||||||
} else if(timeRange=="one-month") {
|
} else if(timeRange=="one-month") {
|
||||||
labels = [aphrases["analytics.now"],"1" + aphrases["analytics.days_short"]];
|
labels = [aphrases["analytics.now"],"1" + aphrases["analytics.days_short"]];
|
||||||
for(let i = 2; i < 30; i++) {
|
for(let i = 2; i < 30; i++) {
|
||||||
if (i%2==0) labels.push("");
|
if (i%2==0) labels.push("");
|
||||||
else labels.push(i + aphrases["analytics.days_short"]);
|
else labels.push(i + aphrases["analytics.days_short"]);
|
||||||
}
|
}
|
||||||
} else if(timeRange=="one-week") {
|
} else if(timeRange=="one-week") {
|
||||||
labels = [aphrases["analytics.now"]];
|
labels = [aphrases["analytics.now"]];
|
||||||
for(let i = 2; i < 14; i++) {
|
for(let i = 2; i < 14; i++) {
|
||||||
if (i%2==0) labels.push("");
|
if (i%2==0) labels.push("");
|
||||||
else labels.push(Math.floor(i/2) + aphrases["analytics.days"]);
|
else labels.push(Math.floor(i/2) + aphrases["analytics.days"]);
|
||||||
}
|
}
|
||||||
} else if (timeRange=="two-days" || timeRange == "one-day" || timeRange == "twelve-hours") {
|
} else if (timeRange=="two-days" || timeRange == "one-day" || timeRange == "twelve-hours") {
|
||||||
for(const i in rawLabels) {
|
for(const i in rawLabels) {
|
||||||
if (i%2==0) {
|
if (i%2==0) {
|
||||||
labels.push("");
|
labels.push("");
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let date = new Date(rawLabels[i]*1000);
|
let date = new Date(rawLabels[i]*1000);
|
||||||
log("date",date);
|
log("date",date);
|
||||||
let minutes = "0" + date.getMinutes();
|
let minutes = "0" + date.getMinutes();
|
||||||
let label = date.getHours() + ":" + minutes.substr(-2);
|
let label = date.getHours() + ":" + minutes.substr(-2);
|
||||||
log("label",label);
|
log("label",label);
|
||||||
labels.push(label);
|
labels.push(label);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for(const i in rawLabels) {
|
for(const i in rawLabels) {
|
||||||
let date = new Date(rawLabels[i]*1000);
|
let date = new Date(rawLabels[i]*1000);
|
||||||
log("date",date);
|
log("date",date);
|
||||||
let minutes = "0" + date.getMinutes();
|
let minutes = "0" + date.getMinutes();
|
||||||
let label = date.getHours() + ":" + minutes.substr(-2);
|
let label = date.getHours() + ":" + minutes.substr(-2);
|
||||||
log("label",label);
|
log("label",label);
|
||||||
labels.push(label);
|
labels.push(label);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
labels = labels.reverse()
|
labels = labels.reverse()
|
||||||
for(let i = 0; i < seriesData.length; i++) {
|
for(let i = 0; i < seriesData.length; i++) {
|
||||||
seriesData[i] = seriesData[i].reverse();
|
seriesData[i] = seriesData[i].reverse();
|
||||||
}
|
}
|
||||||
|
|
||||||
let config = {height: '250px', plugins:[]};
|
let config = {height: '250px', plugins:[]};
|
||||||
if(legendNames.length > 0) config.plugins = [
|
if(legendNames.length > 0) config.plugins = [
|
||||||
Chartist.plugins.legend({legendNames: legendNames})
|
Chartist.plugins.legend({legendNames: legendNames})
|
||||||
];
|
];
|
||||||
if(typ==1) config.plugins.push(Chartist.plugins.byteUnits());
|
if(typ==1) config.plugins.push(Chartist.plugins.byteUnits());
|
||||||
else if(typ==2) config.plugins.push(Chartist.plugins.perfUnits());
|
else if(typ==2) config.plugins.push(Chartist.plugins.perfUnits());
|
||||||
Chartist.Line('.ct_chart', {
|
Chartist.Line('.ct_chart', {
|
||||||
labels: labels,
|
labels: labels,
|
||||||
series: seriesData,
|
series: seriesData,
|
||||||
}, config);
|
}, config);
|
||||||
}
|
}
|
||||||
|
|
||||||
runInitHook("analytics_loaded");
|
runInitHook("analytics_loaded");
|
File diff suppressed because one or more lines are too long
|
@ -1,12 +1,12 @@
|
||||||
(() => {
|
(() => {
|
||||||
addInitHook("end_init", () => {
|
addInitHook("end_init", () => {
|
||||||
$(".create_convo_link").click((event) => {
|
$(".create_convo_link").click((event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
$(".convo_create_form").removeClass("auto_hide");
|
$(".convo_create_form").removeClass("auto_hide");
|
||||||
});
|
});
|
||||||
$(".convo_create_form .close_form").click((event) => {
|
$(".convo_create_form .close_form").click((event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
$(".convo_create_form").addClass("auto_hide");
|
$(".convo_create_form").addClass("auto_hide");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
})();
|
})();
|
1940
public/global.js
1940
public/global.js
File diff suppressed because it is too large
Load Diff
|
@ -1,66 +1,66 @@
|
||||||
.emoji-wysiwyg-editor {
|
.emoji-wysiwyg-editor {
|
||||||
border: 1px solid #d0d0d0;
|
border: 1px solid #d0d0d0;
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
outline: none;
|
outline: none;
|
||||||
}
|
}
|
||||||
.emoji-wysiwyg-editor img {
|
.emoji-wysiwyg-editor img {
|
||||||
width: 20px;
|
width: 20px;
|
||||||
height: 20px;
|
height: 20px;
|
||||||
vertical-align: middle;
|
vertical-align: middle;
|
||||||
margin: -3px 0 0 0;
|
margin: -3px 0 0 0;
|
||||||
}
|
}
|
||||||
.emoji-menu {
|
.emoji-menu {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
z-index: 999;
|
z-index: 999;
|
||||||
width: 180px;
|
width: 180px;
|
||||||
margin-left: -100px;
|
margin-left: -100px;
|
||||||
padding: 0;
|
padding: 0;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
-webkit-box-sizing: border-box;
|
-webkit-box-sizing: border-box;
|
||||||
-moz-box-sizing: border-box;
|
-moz-box-sizing: border-box;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
.emoji-menu > div {
|
.emoji-menu > div {
|
||||||
max-height: 200px;
|
max-height: 200px;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
width: 200px;
|
width: 200px;
|
||||||
-webkit-overflow-scrolling: touch;
|
-webkit-overflow-scrolling: touch;
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
-webkit-border-radius: 3px;
|
-webkit-border-radius: 3px;
|
||||||
-moz-border-radius: 3px;
|
-moz-border-radius: 3px;
|
||||||
border-radius: 3px;
|
border-radius: 3px;
|
||||||
-webkit-box-sizing: border-box;
|
-webkit-box-sizing: border-box;
|
||||||
-moz-box-sizing: border-box;
|
-moz-box-sizing: border-box;
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
-webkit-box-shadow: 0 1px 5px rgba(0,0,0,0.3);
|
-webkit-box-shadow: 0 1px 5px rgba(0,0,0,0.3);
|
||||||
-moz-box-shadow: 0 1px 5px rgba(0,0,0,0.3);
|
-moz-box-shadow: 0 1px 5px rgba(0,0,0,0.3);
|
||||||
box-shadow: 0 1px 5px rgba(0,0,0,0.3);
|
box-shadow: 0 1px 5px rgba(0,0,0,0.3);
|
||||||
padding-top: 40px;
|
padding-top: 40px;
|
||||||
}
|
}
|
||||||
.emoji-menu img {
|
.emoji-menu img {
|
||||||
width: 25px;
|
width: 25px;
|
||||||
height: 25px;
|
height: 25px;
|
||||||
vertical-align: middle;
|
vertical-align: middle;
|
||||||
border: 0 none;
|
border: 0 none;
|
||||||
}
|
}
|
||||||
.emoji-menu a {
|
.emoji-menu a {
|
||||||
margin: -1px 0 0 -1px;
|
margin: -1px 0 0 -1px;
|
||||||
border: 1px solid #f2f2f2;
|
border: 1px solid #f2f2f2;
|
||||||
padding: 5px;
|
padding: 5px;
|
||||||
display: block;
|
display: block;
|
||||||
float: left;
|
float: left;
|
||||||
}
|
}
|
||||||
.emoji-menu a:hover {
|
.emoji-menu a:hover {
|
||||||
background-color: #fffae7;
|
background-color: #fffae7;
|
||||||
}
|
}
|
||||||
.emoji-menu:after {
|
.emoji-menu:after {
|
||||||
content: ' ';
|
content: ' ';
|
||||||
display: block;
|
display: block;
|
||||||
clear: left;
|
clear: left;
|
||||||
}
|
}
|
||||||
.emoji-menu a .label {
|
.emoji-menu a .label {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.emoji-menu div {
|
.emoji-menu div {
|
||||||
|
@ -69,29 +69,29 @@
|
||||||
}
|
}
|
||||||
|
|
||||||
.emoji-menu .group-selector {
|
.emoji-menu .group-selector {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
list-style-type: none;
|
list-style-type: none;
|
||||||
height: 40px;
|
height: 40px;
|
||||||
top: 0;
|
top: 0;
|
||||||
left: 0;
|
left: 0;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
background-color: rgb(255,255,255);
|
background-color: rgb(255,255,255);
|
||||||
background-color: rgba(255,255,255, .9);
|
background-color: rgba(255,255,255, .9);
|
||||||
}
|
}
|
||||||
.emoji-menu .group-selector li {
|
.emoji-menu .group-selector li {
|
||||||
height: 15px;
|
height: 15px;
|
||||||
width: 17px;
|
width: 17px;
|
||||||
padding: 5px;
|
padding: 5px;
|
||||||
}
|
}
|
||||||
.emoji-menu .group-selector a:last-child li {
|
.emoji-menu .group-selector a:last-child li {
|
||||||
width: 15px;
|
width: 15px;
|
||||||
}
|
}
|
||||||
.emoji-menu .group-selector a {
|
.emoji-menu .group-selector a {
|
||||||
color: #EB7878;
|
color: #EB7878;
|
||||||
text-decoration: none;
|
text-decoration: none;
|
||||||
border: none;
|
border: none;
|
||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
}
|
}
|
||||||
.emoji-menu .group-selector a:hover, .emoji-menu .group-selector a.active {
|
.emoji-menu .group-selector a:hover, .emoji-menu .group-selector a.active {
|
||||||
color:#000000;
|
color:#000000;
|
||||||
}
|
}
|
|
@ -16,470 +16,470 @@
|
||||||
|
|
||||||
(function($, window, document) {
|
(function($, window, document) {
|
||||||
|
|
||||||
var ELEMENT_NODE = 1;
|
var ELEMENT_NODE = 1;
|
||||||
var TEXT_NODE = 3;
|
var TEXT_NODE = 3;
|
||||||
var TAGS_BLOCK = ['p', 'div', 'pre', 'form'];
|
var TAGS_BLOCK = ['p', 'div', 'pre', 'form'];
|
||||||
var KEY_ESC = 27;
|
var KEY_ESC = 27;
|
||||||
var KEY_TAB = 9;
|
var KEY_TAB = 9;
|
||||||
|
|
||||||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||||
|
|
||||||
$.emojiarea = {
|
$.emojiarea = {
|
||||||
path: '',
|
path: '',
|
||||||
icons: {},
|
icons: {},
|
||||||
defaults: {
|
defaults: {
|
||||||
button: null,
|
button: null,
|
||||||
buttonLabel: 'Emojis',
|
buttonLabel: 'Emojis',
|
||||||
buttonPosition: 'after'
|
buttonPosition: 'after'
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
$.fn.emojiarea = function(options) {
|
$.fn.emojiarea = function(options) {
|
||||||
options = $.extend({}, $.emojiarea.defaults, options);
|
options = $.extend({}, $.emojiarea.defaults, options);
|
||||||
return this.each(function() {
|
return this.each(function() {
|
||||||
var $textarea = $(this);
|
var $textarea = $(this);
|
||||||
if ('contentEditable' in document.body && options.wysiwyg !== false) {
|
if ('contentEditable' in document.body && options.wysiwyg !== false) {
|
||||||
new EmojiArea_WYSIWYG($textarea, options);
|
new EmojiArea_WYSIWYG($textarea, options);
|
||||||
} else {
|
} else {
|
||||||
new EmojiArea_Plain($textarea, options);
|
new EmojiArea_Plain($textarea, options);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||||
|
|
||||||
var util = {};
|
var util = {};
|
||||||
|
|
||||||
util.restoreSelection = (function() {
|
util.restoreSelection = (function() {
|
||||||
if (window.getSelection) {
|
if (window.getSelection) {
|
||||||
return function(savedSelection) {
|
return function(savedSelection) {
|
||||||
var sel = window.getSelection();
|
var sel = window.getSelection();
|
||||||
sel.removeAllRanges();
|
sel.removeAllRanges();
|
||||||
for (var i = 0, len = savedSelection.length; i < len; ++i) {
|
for (var i = 0, len = savedSelection.length; i < len; ++i) {
|
||||||
sel.addRange(savedSelection[i]);
|
sel.addRange(savedSelection[i]);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
} else if (document.selection && document.selection.createRange) {
|
} else if (document.selection && document.selection.createRange) {
|
||||||
return function(savedSelection) {
|
return function(savedSelection) {
|
||||||
if (savedSelection) {
|
if (savedSelection) {
|
||||||
savedSelection.select();
|
savedSelection.select();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
util.saveSelection = (function() {
|
util.saveSelection = (function() {
|
||||||
if (window.getSelection) {
|
if (window.getSelection) {
|
||||||
return function() {
|
return function() {
|
||||||
var sel = window.getSelection(), ranges = [];
|
var sel = window.getSelection(), ranges = [];
|
||||||
if (sel.rangeCount) {
|
if (sel.rangeCount) {
|
||||||
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
|
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
|
||||||
ranges.push(sel.getRangeAt(i));
|
ranges.push(sel.getRangeAt(i));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return ranges;
|
return ranges;
|
||||||
};
|
};
|
||||||
} else if (document.selection && document.selection.createRange) {
|
} else if (document.selection && document.selection.createRange) {
|
||||||
return function() {
|
return function() {
|
||||||
var sel = document.selection;
|
var sel = document.selection;
|
||||||
return (sel.type.toLowerCase() !== 'none') ? sel.createRange() : null;
|
return (sel.type.toLowerCase() !== 'none') ? sel.createRange() : null;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
util.replaceSelection = (function() {
|
util.replaceSelection = (function() {
|
||||||
if (window.getSelection) {
|
if (window.getSelection) {
|
||||||
return function(content) {
|
return function(content) {
|
||||||
var range, sel = window.getSelection();
|
var range, sel = window.getSelection();
|
||||||
var node = typeof content === 'string' ? document.createTextNode(content) : content;
|
var node = typeof content === 'string' ? document.createTextNode(content) : content;
|
||||||
if (sel.getRangeAt && sel.rangeCount) {
|
if (sel.getRangeAt && sel.rangeCount) {
|
||||||
range = sel.getRangeAt(0);
|
range = sel.getRangeAt(0);
|
||||||
range.deleteContents();
|
range.deleteContents();
|
||||||
range.insertNode(document.createTextNode(' '));
|
range.insertNode(document.createTextNode(' '));
|
||||||
range.insertNode(node);
|
range.insertNode(node);
|
||||||
range.setStart(node, 0);
|
range.setStart(node, 0);
|
||||||
|
|
||||||
window.setTimeout(function() {
|
window.setTimeout(function() {
|
||||||
range = document.createRange();
|
range = document.createRange();
|
||||||
range.setStartAfter(node);
|
range.setStartAfter(node);
|
||||||
range.collapse(true);
|
range.collapse(true);
|
||||||
sel.removeAllRanges();
|
sel.removeAllRanges();
|
||||||
sel.addRange(range);
|
sel.addRange(range);
|
||||||
}, 0);
|
}, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (document.selection && document.selection.createRange) {
|
} else if (document.selection && document.selection.createRange) {
|
||||||
return function(content) {
|
return function(content) {
|
||||||
var range = document.selection.createRange();
|
var range = document.selection.createRange();
|
||||||
if (typeof content === 'string') {
|
if (typeof content === 'string') {
|
||||||
range.text = content;
|
range.text = content;
|
||||||
} else {
|
} else {
|
||||||
range.pasteHTML(content.outerHTML);
|
range.pasteHTML(content.outerHTML);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
util.insertAtCursor = function(text, el) {
|
util.insertAtCursor = function(text, el) {
|
||||||
text = ' ' + text;
|
text = ' ' + text;
|
||||||
var val = el.value, endIndex, startIndex, range;
|
var val = el.value, endIndex, startIndex, range;
|
||||||
if (typeof el.selectionStart != 'undefined' && typeof el.selectionEnd != 'undefined') {
|
if (typeof el.selectionStart != 'undefined' && typeof el.selectionEnd != 'undefined') {
|
||||||
startIndex = el.selectionStart;
|
startIndex = el.selectionStart;
|
||||||
endIndex = el.selectionEnd;
|
endIndex = el.selectionEnd;
|
||||||
el.value = val.substring(0, startIndex) + text + val.substring(el.selectionEnd);
|
el.value = val.substring(0, startIndex) + text + val.substring(el.selectionEnd);
|
||||||
el.selectionStart = el.selectionEnd = startIndex + text.length;
|
el.selectionStart = el.selectionEnd = startIndex + text.length;
|
||||||
} else if (typeof document.selection != 'undefined' && typeof document.selection.createRange != 'undefined') {
|
} else if (typeof document.selection != 'undefined' && typeof document.selection.createRange != 'undefined') {
|
||||||
el.focus();
|
el.focus();
|
||||||
range = document.selection.createRange();
|
range = document.selection.createRange();
|
||||||
range.text = text;
|
range.text = text;
|
||||||
range.select();
|
range.select();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
util.extend = function(a, b) {
|
util.extend = function(a, b) {
|
||||||
if (typeof a === 'undefined' || !a) { a = {}; }
|
if (typeof a === 'undefined' || !a) { a = {}; }
|
||||||
if (typeof b === 'object') {
|
if (typeof b === 'object') {
|
||||||
for (var key in b) {
|
for (var key in b) {
|
||||||
if (b.hasOwnProperty(key)) {
|
if (b.hasOwnProperty(key)) {
|
||||||
a[key] = b[key];
|
a[key] = b[key];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return a;
|
return a;
|
||||||
};
|
};
|
||||||
|
|
||||||
util.escapeRegex = function(str) {
|
util.escapeRegex = function(str) {
|
||||||
return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
|
return (str + '').replace(/([.?*+^$[\]\\(){}|-])/g, '\\$1');
|
||||||
};
|
};
|
||||||
|
|
||||||
util.htmlEntities = function(str) {
|
util.htmlEntities = function(str) {
|
||||||
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||||
};
|
};
|
||||||
|
|
||||||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||||
|
|
||||||
var EmojiArea = function() {};
|
var EmojiArea = function() {};
|
||||||
|
|
||||||
EmojiArea.prototype.setup = function() {
|
EmojiArea.prototype.setup = function() {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
this.$editor.on('focus', function() { self.hasFocus = true; });
|
this.$editor.on('focus', function() { self.hasFocus = true; });
|
||||||
this.$editor.on('blur', function() { self.hasFocus = false; });
|
this.$editor.on('blur', function() { self.hasFocus = false; });
|
||||||
|
|
||||||
this.setupButton();
|
this.setupButton();
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiArea.prototype.setupButton = function() {
|
EmojiArea.prototype.setupButton = function() {
|
||||||
var self = this;
|
var self = this;
|
||||||
var $button;
|
var $button;
|
||||||
|
|
||||||
if (this.options.button) {
|
if (this.options.button) {
|
||||||
$button = $(this.options.button);
|
$button = $(this.options.button);
|
||||||
} else if (this.options.button !== false) {
|
} else if (this.options.button !== false) {
|
||||||
$button = $('<a href="javascript:void(0)">');
|
$button = $('<a href="javascript:void(0)">');
|
||||||
$button.html(this.options.buttonLabel);
|
$button.html(this.options.buttonLabel);
|
||||||
$button.addClass('emoji-button');
|
$button.addClass('emoji-button');
|
||||||
$button.attr({title: this.options.buttonLabel});
|
$button.attr({title: this.options.buttonLabel});
|
||||||
this.$editor[this.options.buttonPosition]($button);
|
this.$editor[this.options.buttonPosition]($button);
|
||||||
} else {
|
} else {
|
||||||
$button = $('');
|
$button = $('');
|
||||||
}
|
}
|
||||||
|
|
||||||
$button.on('click', function(e) {
|
$button.on('click', function(e) {
|
||||||
EmojiMenu.show(self);
|
EmojiMenu.show(self);
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
});
|
});
|
||||||
|
|
||||||
this.$button = $button;
|
this.$button = $button;
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiArea.createIcon = function(group, emoji) {
|
EmojiArea.createIcon = function(group, emoji) {
|
||||||
var filename = $.emojiarea.icons[group]['icons'][emoji];
|
var filename = $.emojiarea.icons[group]['icons'][emoji];
|
||||||
var path = $.emojiarea.path || '';
|
var path = $.emojiarea.path || '';
|
||||||
if (path.length && path.charAt(path.length - 1) !== '/') {
|
if (path.length && path.charAt(path.length - 1) !== '/') {
|
||||||
path += '/';
|
path += '/';
|
||||||
}
|
}
|
||||||
return '<img src="' + path + filename + '" alt="' + util.htmlEntities(emoji) + '">';
|
return '<img src="' + path + filename + '" alt="' + util.htmlEntities(emoji) + '">';
|
||||||
};
|
};
|
||||||
|
|
||||||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Editor (plain-text)
|
* Editor (plain-text)
|
||||||
*
|
*
|
||||||
* @constructor
|
* @constructor
|
||||||
* @param {object} $textarea
|
* @param {object} $textarea
|
||||||
* @param {object} options
|
* @param {object} options
|
||||||
*/
|
*/
|
||||||
|
|
||||||
var EmojiArea_Plain = function($textarea, options) {
|
var EmojiArea_Plain = function($textarea, options) {
|
||||||
this.options = options;
|
this.options = options;
|
||||||
this.$textarea = $textarea;
|
this.$textarea = $textarea;
|
||||||
this.$editor = $textarea;
|
this.$editor = $textarea;
|
||||||
this.setup();
|
this.setup();
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiArea_Plain.prototype.insert = function(group, emoji) {
|
EmojiArea_Plain.prototype.insert = function(group, emoji) {
|
||||||
if (!$.emojiarea.icons[group]['icons'].hasOwnProperty(emoji)) return;
|
if (!$.emojiarea.icons[group]['icons'].hasOwnProperty(emoji)) return;
|
||||||
util.insertAtCursor(emoji, this.$textarea[0]);
|
util.insertAtCursor(emoji, this.$textarea[0]);
|
||||||
this.$textarea.trigger('change');
|
this.$textarea.trigger('change');
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiArea_Plain.prototype.val = function() {
|
EmojiArea_Plain.prototype.val = function() {
|
||||||
return this.$textarea.val();
|
return this.$textarea.val();
|
||||||
};
|
};
|
||||||
|
|
||||||
util.extend(EmojiArea_Plain.prototype, EmojiArea.prototype);
|
util.extend(EmojiArea_Plain.prototype, EmojiArea.prototype);
|
||||||
|
|
||||||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Editor (rich)
|
* Editor (rich)
|
||||||
*
|
*
|
||||||
* @constructor
|
* @constructor
|
||||||
* @param {object} $textarea
|
* @param {object} $textarea
|
||||||
* @param {object} options
|
* @param {object} options
|
||||||
*/
|
*/
|
||||||
|
|
||||||
var EmojiArea_WYSIWYG = function($textarea, options) {
|
var EmojiArea_WYSIWYG = function($textarea, options) {
|
||||||
var self = this;
|
var self = this;
|
||||||
|
|
||||||
this.options = options;
|
this.options = options;
|
||||||
this.$textarea = $textarea;
|
this.$textarea = $textarea;
|
||||||
this.$editor = $('<div>').addClass('emoji-wysiwyg-editor');
|
this.$editor = $('<div>').addClass('emoji-wysiwyg-editor');
|
||||||
this.$editor.text($textarea.val());
|
this.$editor.text($textarea.val());
|
||||||
this.$editor.attr({contenteditable: 'true'});
|
this.$editor.attr({contenteditable: 'true'});
|
||||||
this.$editor.on('blur keyup paste', function() { return self.onChange.apply(self, arguments); });
|
this.$editor.on('blur keyup paste', function() { return self.onChange.apply(self, arguments); });
|
||||||
this.$editor.on('mousedown focus', function() { document.execCommand('enableObjectResizing', false, false); });
|
this.$editor.on('mousedown focus', function() { document.execCommand('enableObjectResizing', false, false); });
|
||||||
this.$editor.on('blur', function() { document.execCommand('enableObjectResizing', true, true); });
|
this.$editor.on('blur', function() { document.execCommand('enableObjectResizing', true, true); });
|
||||||
|
|
||||||
var html = this.$editor.text();
|
var html = this.$editor.text();
|
||||||
var emojis = $.emojiarea.icons;
|
var emojis = $.emojiarea.icons;
|
||||||
for (var group in emojis) {
|
for (var group in emojis) {
|
||||||
for (var key in emojis[group]['icons']) {
|
for (var key in emojis[group]['icons']) {
|
||||||
if (emojis[group]['icons'].hasOwnProperty(key)) {
|
if (emojis[group]['icons'].hasOwnProperty(key)) {
|
||||||
html = html.replace(new RegExp(util.escapeRegex(key), 'g'), EmojiArea.createIcon(group, key));
|
html = html.replace(new RegExp(util.escapeRegex(key), 'g'), EmojiArea.createIcon(group, key));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.$editor.html(html);
|
this.$editor.html(html);
|
||||||
|
|
||||||
$textarea.hide().after(this.$editor);
|
$textarea.hide().after(this.$editor);
|
||||||
|
|
||||||
this.setup();
|
this.setup();
|
||||||
|
|
||||||
this.$button.on('mousedown', function() {
|
this.$button.on('mousedown', function() {
|
||||||
if (self.hasFocus) {
|
if (self.hasFocus) {
|
||||||
self.selection = util.saveSelection();
|
self.selection = util.saveSelection();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiArea_WYSIWYG.prototype.onChange = function() {
|
EmojiArea_WYSIWYG.prototype.onChange = function() {
|
||||||
this.$textarea.val(this.val()).trigger('change');
|
this.$textarea.val(this.val()).trigger('change');
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiArea_WYSIWYG.prototype.insert = function(group, emoji) {
|
EmojiArea_WYSIWYG.prototype.insert = function(group, emoji) {
|
||||||
var content;
|
var content;
|
||||||
var $img = $(EmojiArea.createIcon(group, emoji));
|
var $img = $(EmojiArea.createIcon(group, emoji));
|
||||||
if ($img[0].attachEvent) {
|
if ($img[0].attachEvent) {
|
||||||
$img[0].attachEvent('onresizestart', function(e) { e.returnValue = false; }, false);
|
$img[0].attachEvent('onresizestart', function(e) { e.returnValue = false; }, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.$editor.trigger('focus');
|
this.$editor.trigger('focus');
|
||||||
if (this.selection) {
|
if (this.selection) {
|
||||||
util.restoreSelection(this.selection);
|
util.restoreSelection(this.selection);
|
||||||
}
|
}
|
||||||
try { util.replaceSelection($img[0]); } catch (e) {}
|
try { util.replaceSelection($img[0]); } catch (e) {}
|
||||||
this.onChange();
|
this.onChange();
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiArea_WYSIWYG.prototype.val = function() {
|
EmojiArea_WYSIWYG.prototype.val = function() {
|
||||||
var lines = [];
|
var lines = [];
|
||||||
var line = [];
|
var line = [];
|
||||||
|
|
||||||
var flush = function() {
|
var flush = function() {
|
||||||
lines.push(line.join(''));
|
lines.push(line.join(''));
|
||||||
line = [];
|
line = [];
|
||||||
};
|
};
|
||||||
|
|
||||||
var sanitizeNode = function(node) {
|
var sanitizeNode = function(node) {
|
||||||
if (node.nodeType === TEXT_NODE) {
|
if (node.nodeType === TEXT_NODE) {
|
||||||
line.push(node.nodeValue);
|
line.push(node.nodeValue);
|
||||||
} else if (node.nodeType === ELEMENT_NODE) {
|
} else if (node.nodeType === ELEMENT_NODE) {
|
||||||
var tagName = node.tagName.toLowerCase();
|
var tagName = node.tagName.toLowerCase();
|
||||||
var isBlock = TAGS_BLOCK.indexOf(tagName) !== -1;
|
var isBlock = TAGS_BLOCK.indexOf(tagName) !== -1;
|
||||||
|
|
||||||
if (isBlock && line.length) flush();
|
if (isBlock && line.length) flush();
|
||||||
|
|
||||||
if (tagName === 'img') {
|
if (tagName === 'img') {
|
||||||
var alt = node.getAttribute('alt') || '';
|
var alt = node.getAttribute('alt') || '';
|
||||||
if (alt) line.push(alt);
|
if (alt) line.push(alt);
|
||||||
return;
|
return;
|
||||||
} else if (tagName === 'br') {
|
} else if (tagName === 'br') {
|
||||||
flush();
|
flush();
|
||||||
}
|
}
|
||||||
|
|
||||||
var children = node.childNodes;
|
var children = node.childNodes;
|
||||||
for (var i = 0; i < children.length; i++) {
|
for (var i = 0; i < children.length; i++) {
|
||||||
sanitizeNode(children[i]);
|
sanitizeNode(children[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isBlock && line.length) flush();
|
if (isBlock && line.length) flush();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
var children = this.$editor[0].childNodes;
|
var children = this.$editor[0].childNodes;
|
||||||
for (var i = 0; i < children.length; i++) {
|
for (var i = 0; i < children.length; i++) {
|
||||||
sanitizeNode(children[i]);
|
sanitizeNode(children[i]);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (line.length) flush();
|
if (line.length) flush();
|
||||||
|
|
||||||
return lines.join('\n');
|
return lines.join('\n');
|
||||||
};
|
};
|
||||||
|
|
||||||
util.extend(EmojiArea_WYSIWYG.prototype, EmojiArea.prototype);
|
util.extend(EmojiArea_WYSIWYG.prototype, EmojiArea.prototype);
|
||||||
|
|
||||||
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Emoji Dropdown Menu
|
* Emoji Dropdown Menu
|
||||||
*
|
*
|
||||||
* @constructor
|
* @constructor
|
||||||
* @param {object} emojiarea
|
* @param {object} emojiarea
|
||||||
*/
|
*/
|
||||||
var EmojiMenu = function() {
|
var EmojiMenu = function() {
|
||||||
var self = this;
|
var self = this;
|
||||||
var $body = $(document.body);
|
var $body = $(document.body);
|
||||||
var $window = $(window);
|
var $window = $(window);
|
||||||
|
|
||||||
this.visible = false;
|
this.visible = false;
|
||||||
this.emojiarea = null;
|
this.emojiarea = null;
|
||||||
this.$menu = $('<div>');
|
this.$menu = $('<div>');
|
||||||
this.$menu.addClass('emoji-menu');
|
this.$menu.addClass('emoji-menu');
|
||||||
this.$menu.hide();
|
this.$menu.hide();
|
||||||
this.$items = $('<div>').appendTo(this.$menu);
|
this.$items = $('<div>').appendTo(this.$menu);
|
||||||
|
|
||||||
$body.append(this.$menu);
|
$body.append(this.$menu);
|
||||||
|
|
||||||
$body.on('keydown', function(e) {
|
$body.on('keydown', function(e) {
|
||||||
if (e.keyCode === KEY_ESC || e.keyCode === KEY_TAB) {
|
if (e.keyCode === KEY_ESC || e.keyCode === KEY_TAB) {
|
||||||
self.hide();
|
self.hide();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
$body.on('mouseup', function() {
|
$body.on('mouseup', function() {
|
||||||
self.hide();
|
self.hide();
|
||||||
});
|
});
|
||||||
|
|
||||||
$window.on('resize', function() {
|
$window.on('resize', function() {
|
||||||
if (self.visible) self.reposition();
|
if (self.visible) self.reposition();
|
||||||
});
|
});
|
||||||
|
|
||||||
this.$menu.on('mouseup', 'a', function(e) {
|
this.$menu.on('mouseup', 'a', function(e) {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
return false;
|
return false;
|
||||||
});
|
});
|
||||||
|
|
||||||
this.$menu.on('click', 'a', function(e) {
|
this.$menu.on('click', 'a', function(e) {
|
||||||
var emoji = $('.label', $(this)).text();
|
var emoji = $('.label', $(this)).text();
|
||||||
var group = $('.label', $(this)).parent().parent().attr('group');
|
var group = $('.label', $(this)).parent().parent().attr('group');
|
||||||
if(group && emoji !== ''){
|
if(group && emoji !== ''){
|
||||||
window.setTimeout(function() {
|
window.setTimeout(function() {
|
||||||
self.onItemSelected.apply(self, [group, emoji]);
|
self.onItemSelected.apply(self, [group, emoji]);
|
||||||
}, 0);
|
}, 0);
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
this.load();
|
this.load();
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiMenu.prototype.onItemSelected = function(group, emoji) {
|
EmojiMenu.prototype.onItemSelected = function(group, emoji) {
|
||||||
this.emojiarea.insert(group, emoji);
|
this.emojiarea.insert(group, emoji);
|
||||||
this.hide();
|
this.hide();
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiMenu.prototype.load = function() {
|
EmojiMenu.prototype.load = function() {
|
||||||
var html = [];
|
var html = [];
|
||||||
var groups = [];
|
var groups = [];
|
||||||
var options = $.emojiarea.icons;
|
var options = $.emojiarea.icons;
|
||||||
var path = $.emojiarea.path;
|
var path = $.emojiarea.path;
|
||||||
if (path.length && path.charAt(path.length - 1) !== '/') {
|
if (path.length && path.charAt(path.length - 1) !== '/') {
|
||||||
path += '/';
|
path += '/';
|
||||||
}
|
}
|
||||||
groups.push('<ul class="group-selector">');
|
groups.push('<ul class="group-selector">');
|
||||||
for (var group in options) {
|
for (var group in options) {
|
||||||
groups.push('<a href="#group_' + group + '" class="tab_switch"><li>' + options[group]['name'] + '</li></a>');
|
groups.push('<a href="#group_' + group + '" class="tab_switch"><li>' + options[group]['name'] + '</li></a>');
|
||||||
html.push('<div class="select_group" group="' + group + '" id="group_' + group + '">');
|
html.push('<div class="select_group" group="' + group + '" id="group_' + group + '">');
|
||||||
for (var key in options[group]['icons']) {
|
for (var key in options[group]['icons']) {
|
||||||
if (options[group]['icons'].hasOwnProperty(key)) {
|
if (options[group]['icons'].hasOwnProperty(key)) {
|
||||||
var filename = options[key];
|
var filename = options[key];
|
||||||
html.push('<a href="javascript:void(0)" title="' + util.htmlEntities(key) + '">' + EmojiArea.createIcon(group, key) + '<span class="label">' + util.htmlEntities(key) + '</span></a>');
|
html.push('<a href="javascript:void(0)" title="' + util.htmlEntities(key) + '">' + EmojiArea.createIcon(group, key) + '<span class="label">' + util.htmlEntities(key) + '</span></a>');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
html.push('</div>');
|
html.push('</div>');
|
||||||
}
|
}
|
||||||
groups.push('</ul>');
|
groups.push('</ul>');
|
||||||
this.$items.html(html.join(''));
|
this.$items.html(html.join(''));
|
||||||
this.$menu.prepend(groups.join(''));
|
this.$menu.prepend(groups.join(''));
|
||||||
this.$menu.find('.tab_switch').each(function(i) {
|
this.$menu.find('.tab_switch').each(function(i) {
|
||||||
if (i != 0) {
|
if (i != 0) {
|
||||||
var select = $(this).attr('href');
|
var select = $(this).attr('href');
|
||||||
$(select).hide();
|
$(select).hide();
|
||||||
} else {
|
} else {
|
||||||
$(this).addClass('active');
|
$(this).addClass('active');
|
||||||
}
|
}
|
||||||
$(this).click(function() {
|
$(this).click(function() {
|
||||||
$(this).addClass('active');
|
$(this).addClass('active');
|
||||||
$(this).siblings().removeClass('active');
|
$(this).siblings().removeClass('active');
|
||||||
$('.select_group').hide();
|
$('.select_group').hide();
|
||||||
var select = $(this).attr('href');
|
var select = $(this).attr('href');
|
||||||
$(select).show();
|
$(select).show();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiMenu.prototype.reposition = function() {
|
EmojiMenu.prototype.reposition = function() {
|
||||||
var $button = this.emojiarea.$button;
|
var $button = this.emojiarea.$button;
|
||||||
var offset = $button.offset();
|
var offset = $button.offset();
|
||||||
offset.top += $button.outerHeight();
|
offset.top += $button.outerHeight();
|
||||||
offset.left += Math.round($button.outerWidth() / 2);
|
offset.left += Math.round($button.outerWidth() / 2);
|
||||||
|
|
||||||
this.$menu.css({
|
this.$menu.css({
|
||||||
top: offset.top,
|
top: offset.top,
|
||||||
left: offset.left
|
left: offset.left
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiMenu.prototype.hide = function(callback) {
|
EmojiMenu.prototype.hide = function(callback) {
|
||||||
if (this.emojiarea) {
|
if (this.emojiarea) {
|
||||||
this.emojiarea.menu = null;
|
this.emojiarea.menu = null;
|
||||||
this.emojiarea.$button.removeClass('on');
|
this.emojiarea.$button.removeClass('on');
|
||||||
this.emojiarea = null;
|
this.emojiarea = null;
|
||||||
}
|
}
|
||||||
this.visible = false;
|
this.visible = false;
|
||||||
this.$menu.hide();
|
this.$menu.hide();
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiMenu.prototype.show = function(emojiarea) {
|
EmojiMenu.prototype.show = function(emojiarea) {
|
||||||
if (this.emojiarea && this.emojiarea === emojiarea) return;
|
if (this.emojiarea && this.emojiarea === emojiarea) return;
|
||||||
this.emojiarea = emojiarea;
|
this.emojiarea = emojiarea;
|
||||||
this.emojiarea.menu = this;
|
this.emojiarea.menu = this;
|
||||||
|
|
||||||
this.reposition();
|
this.reposition();
|
||||||
this.$menu.show();
|
this.$menu.show();
|
||||||
this.visible = true;
|
this.visible = true;
|
||||||
};
|
};
|
||||||
|
|
||||||
EmojiMenu.show = (function() {
|
EmojiMenu.show = (function() {
|
||||||
var menu = null;
|
var menu = null;
|
||||||
return function(emojiarea) {
|
return function(emojiarea) {
|
||||||
menu = menu || new EmojiMenu();
|
menu = menu || new EmojiMenu();
|
||||||
menu.show(emojiarea);
|
menu.show(emojiarea);
|
||||||
};
|
};
|
||||||
})();
|
})();
|
||||||
|
|
||||||
})(jQuery, window, document);
|
})(jQuery, window, document);
|
646
public/member.js
646
public/member.js
|
@ -2,356 +2,356 @@
|
||||||
var imageExts = ["png","jpg","jpe","jpeg","jif","jfi","jfif","svg","bmp","gif","tiff","tif","webp"];
|
var imageExts = ["png","jpg","jpe","jpeg","jif","jfi","jfif","svg","bmp","gif","tiff","tif","webp"];
|
||||||
|
|
||||||
(() => {
|
(() => {
|
||||||
function copyToClipboard(str) {
|
function copyToClipboard(str) {
|
||||||
const el=document.createElement('textarea');
|
const el=document.createElement('textarea');
|
||||||
el.value=str;
|
el.value=str;
|
||||||
el.setAttribute('readonly','');
|
el.setAttribute('readonly','');
|
||||||
el.style.position='absolute';
|
el.style.position='absolute';
|
||||||
el.style.left='-9999px';
|
el.style.left='-9999px';
|
||||||
document.body.appendChild(el);
|
document.body.appendChild(el);
|
||||||
el.select();
|
el.select();
|
||||||
document.execCommand('copy');
|
document.execCommand('copy');
|
||||||
document.body.removeChild(el);
|
document.body.removeChild(el);
|
||||||
}
|
}
|
||||||
|
|
||||||
function uploadFileHandler(fileList, maxFiles=5, step1 = () => {}, step2 = () => {}) {
|
function uploadFileHandler(fileList, maxFiles=5, step1 = () => {}, step2 = () => {}) {
|
||||||
let files = [];
|
let files = [];
|
||||||
for(var i=0; i<fileList.length && i<5; i++) files[i] = fileList[i];
|
for(var i=0; i<fileList.length && i<5; i++) files[i] = fileList[i];
|
||||||
|
|
||||||
let totalSize = 0;
|
let totalSize = 0;
|
||||||
for(let i=0; i<files.length; i++) {
|
for(let i=0; i<files.length; i++) {
|
||||||
log("file "+i,files[i]);
|
log("file "+i,files[i]);
|
||||||
totalSize += files[i]["size"];
|
totalSize += files[i]["size"];
|
||||||
}
|
}
|
||||||
if(totalSize > me.Site.MaxReqSize) throw("You can't upload this much at once, max: "+me.Site.MaxReqSize);
|
if(totalSize > me.Site.MaxReqSize) throw("You can't upload this much at once, max: "+me.Site.MaxReqSize);
|
||||||
|
|
||||||
for(let i=0; i<files.length; i++) {
|
for(let i=0; i<files.length; i++) {
|
||||||
let fname = files[i]["name"];
|
let fname = files[i]["name"];
|
||||||
let f = e => {
|
let f = e => {
|
||||||
step1(e,fname)
|
step1(e,fname)
|
||||||
|
|
||||||
let reader = new FileReader();
|
let reader = new FileReader();
|
||||||
reader.onload = e2 => {
|
reader.onload = e2 => {
|
||||||
crypto.subtle.digest('SHA-256',e2.target.result)
|
crypto.subtle.digest('SHA-256',e2.target.result)
|
||||||
.then(hash => {
|
.then(hash => {
|
||||||
const hashArray = Array.from(new Uint8Array(hash))
|
const hashArray = Array.from(new Uint8Array(hash))
|
||||||
return hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('')
|
return hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('')
|
||||||
}).then(hash => step2(e,hash,fname));
|
}).then(hash => step2(e,hash,fname));
|
||||||
}
|
}
|
||||||
reader.readAsArrayBuffer(files[i]);
|
reader.readAsArrayBuffer(files[i]);
|
||||||
};
|
};
|
||||||
|
|
||||||
let ext = getExt(fname);
|
let ext = getExt(fname);
|
||||||
// TODO: Push ImageFileExts to the client from the server in some sort of gen.js?
|
// TODO: Push ImageFileExts to the client from the server in some sort of gen.js?
|
||||||
let isImage = imageExts.includes(ext);
|
let isImage = imageExts.includes(ext);
|
||||||
if(isImage) {
|
if(isImage) {
|
||||||
let reader = new FileReader();
|
let reader = new FileReader();
|
||||||
reader.onload = f;
|
reader.onload = f;
|
||||||
reader.readAsDataURL(files[i]);
|
reader.readAsDataURL(files[i]);
|
||||||
} else f(null);
|
} else f(null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attachment Manager
|
// Attachment Manager
|
||||||
function uploadAttachHandler2() {
|
function uploadAttachHandler2() {
|
||||||
let post = this.closest(".post_item");
|
let post = this.closest(".post_item");
|
||||||
let fileDock = this.closest(".attach_edit_bay");
|
let fileDock = this.closest(".attach_edit_bay");
|
||||||
try {
|
try {
|
||||||
uploadFileHandler(this.files, 5, () => {},
|
uploadFileHandler(this.files, 5, () => {},
|
||||||
(e,hash,fname) => {
|
(e,hash,fname) => {
|
||||||
log("hash",hash);
|
log("hash",hash);
|
||||||
let formData = new FormData();
|
let formData = new FormData();
|
||||||
formData.append("s",me.User.S);
|
formData.append("s",me.User.S);
|
||||||
for(let i=0; i<this.files.length; i++) formData.append("upload_files",this.files[i]);
|
for(let i=0; i<this.files.length; i++) formData.append("upload_files",this.files[i]);
|
||||||
bindAttachManager();
|
bindAttachManager();
|
||||||
|
|
||||||
let req = new XMLHttpRequest();
|
let req = new XMLHttpRequest();
|
||||||
req.addEventListener("load", () => {
|
req.addEventListener("load", () => {
|
||||||
let data = JSON.parse(req.responseText);
|
let data = JSON.parse(req.responseText);
|
||||||
//log("rdata",data);
|
//log("rdata",data);
|
||||||
let fileItem = document.createElement("div");
|
let fileItem = document.createElement("div");
|
||||||
let ext = getExt(fname);
|
let ext = getExt(fname);
|
||||||
// TODO: Push ImageFileExts to the client from the server in some sort of gen.js?
|
// TODO: Push ImageFileExts to the client from the server in some sort of gen.js?
|
||||||
let isImage = imageExts.includes(ext);
|
let isImage = imageExts.includes(ext);
|
||||||
let c = "";
|
let c = "";
|
||||||
if(isImage) c = " attach_image_holder"
|
if(isImage) c = " attach_image_holder"
|
||||||
fileItem.className = "attach_item attach_item_item"+c;
|
fileItem.className = "attach_item attach_item_item"+c;
|
||||||
fileItem.innerHTML = Tmpl_topic_c_attach_item({
|
fileItem.innerHTML = Tmpl_topic_c_attach_item({
|
||||||
ID: data.elems[hash+"."+ext],
|
ID: data.elems[hash+"."+ext],
|
||||||
ImgSrc: isImage ? e.target.result : "",
|
ImgSrc: isImage ? e.target.result : "",
|
||||||
Path: hash+"."+ext,
|
Path: hash+"."+ext,
|
||||||
FullPath: "//" + window.location.host + "/attachs/" + hash + "." + ext,
|
FullPath: "//" + window.location.host + "/attachs/" + hash + "." + ext,
|
||||||
});
|
});
|
||||||
fileDock.insertBefore(fileItem,fileDock.querySelector(".attach_item_buttons"));
|
fileDock.insertBefore(fileItem,fileDock.querySelector(".attach_item_buttons"));
|
||||||
|
|
||||||
post.classList.add("has_attachs");
|
post.classList.add("has_attachs");
|
||||||
bindAttachItems();
|
bindAttachItems();
|
||||||
});
|
});
|
||||||
req.open("POST","//"+window.location.host+"/"+fileDock.getAttribute("type")+"/attach/add/submit/"+fileDock.getAttribute("id"));
|
req.open("POST","//"+window.location.host+"/"+fileDock.getAttribute("type")+"/attach/add/submit/"+fileDock.getAttribute("id"));
|
||||||
req.send(formData);
|
req.send(formData);
|
||||||
});
|
});
|
||||||
} catch(e) {
|
} catch(e) {
|
||||||
// TODO: Use a notice instead
|
// TODO: Use a notice instead
|
||||||
log("e",e);
|
log("e",e);
|
||||||
alert(e);
|
alert(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Quick Topic / Quick Reply
|
// Quick Topic / Quick Reply
|
||||||
function uploadAttachHandler() {
|
function uploadAttachHandler() {
|
||||||
try {
|
try {
|
||||||
uploadFileHandler(this.files,5,(e,fname) => {
|
uploadFileHandler(this.files,5,(e,fname) => {
|
||||||
// TODO: Use client templates here
|
// TODO: Use client templates here
|
||||||
let fileDock = document.getElementById("upload_file_dock");
|
let fileDock = document.getElementById("upload_file_dock");
|
||||||
let fileItem = document.createElement("label");
|
let fileItem = document.createElement("label");
|
||||||
log("fileItem",fileItem);
|
log("fileItem",fileItem);
|
||||||
|
|
||||||
let ext = getExt(fname);
|
let ext = getExt(fname);
|
||||||
// TODO: Push ImageFileExts to the client from the server in some sort of gen.js?
|
// TODO: Push ImageFileExts to the client from the server in some sort of gen.js?
|
||||||
let isImage = imageExts.includes(ext);
|
let isImage = imageExts.includes(ext);
|
||||||
fileItem.innerText = "."+ext;
|
fileItem.innerText = "."+ext;
|
||||||
fileItem.className = "formbutton uploadItem";
|
fileItem.className = "formbutton uploadItem";
|
||||||
// TODO: Check if this is actually an image
|
// TODO: Check if this is actually an image
|
||||||
if(isImage) fileItem.style.backgroundImage = "url("+e.target.result+")";
|
if(isImage) fileItem.style.backgroundImage = "url("+e.target.result+")";
|
||||||
|
|
||||||
fileDock.appendChild(fileItem);
|
fileDock.appendChild(fileItem);
|
||||||
},(e,hash,fname) => {
|
},(e,hash,fname) => {
|
||||||
log("hash",hash);
|
log("hash",hash);
|
||||||
let ext = getExt(fname)
|
let ext = getExt(fname)
|
||||||
let con = document.getElementById("input_content")
|
let con = document.getElementById("input_content")
|
||||||
log("con.value",con.value);
|
log("con.value",con.value);
|
||||||
|
|
||||||
let attachItem;
|
let attachItem;
|
||||||
if(con.value=="") attachItem = "//"+window.location.host+"/attachs/"+hash+"."+ext;
|
if(con.value=="") attachItem = "//"+window.location.host+"/attachs/"+hash+"."+ext;
|
||||||
else attachItem = "\r\n//"+window.location.host+"/attachs/"+hash+"."+ext;
|
else attachItem = "\r\n//"+window.location.host+"/attachs/"+hash+"."+ext;
|
||||||
con.value = con.value + attachItem;
|
con.value = con.value + attachItem;
|
||||||
log("con.value",con.value);
|
log("con.value",con.value);
|
||||||
|
|
||||||
// For custom / third party text editors
|
// For custom / third party text editors
|
||||||
attachItemCallback(attachItem);
|
attachItemCallback(attachItem);
|
||||||
});
|
});
|
||||||
} catch(e) {
|
} catch(e) {
|
||||||
// TODO: Use a notice instead
|
// TODO: Use a notice instead
|
||||||
log("e",e);
|
log("e",e);
|
||||||
alert(e);
|
alert(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function bindAttachManager() {
|
function bindAttachManager() {
|
||||||
let uploadFiles = document.getElementsByClassName("upload_files_post");
|
let uploadFiles = document.getElementsByClassName("upload_files_post");
|
||||||
if(uploadFiles==null) return;
|
if(uploadFiles==null) return;
|
||||||
for(let i=0; i<uploadFiles.length; i++) {
|
for(let i=0; i<uploadFiles.length; i++) {
|
||||||
let uploader = uploadFiles[i];
|
let uploader = uploadFiles[i];
|
||||||
uploader.value = "";
|
uploader.value = "";
|
||||||
uploader.removeEventListener("change", uploadAttachHandler2, false);
|
uploader.removeEventListener("change", uploadAttachHandler2, false);
|
||||||
uploader.addEventListener("change", uploadAttachHandler2, false);
|
uploader.addEventListener("change", uploadAttachHandler2, false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//addInitHook("before_init_bind_page", () => {
|
//addInitHook("before_init_bind_page", () => {
|
||||||
//log("in member.js before_init_bind_page")
|
//log("in member.js before_init_bind_page")
|
||||||
addInitHook("end_bind_topic", () => {
|
addInitHook("end_bind_topic", () => {
|
||||||
log("in member.js end_bind_topic")
|
log("in member.js end_bind_topic")
|
||||||
|
|
||||||
let changeListener = (files,h) => {
|
let changeListener = (files,h) => {
|
||||||
if(files!=null) {
|
if(files!=null) {
|
||||||
files.removeEventListener("change", h, false);
|
files.removeEventListener("change", h, false);
|
||||||
files.addEventListener("change", h, false);
|
files.addEventListener("change", h, false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let uploadFiles = document.getElementById("upload_files");
|
let uploadFiles = document.getElementById("upload_files");
|
||||||
changeListener(uploadFiles,uploadAttachHandler);
|
changeListener(uploadFiles,uploadAttachHandler);
|
||||||
let uploadFilesOp = document.getElementById("upload_files_op");
|
let uploadFilesOp = document.getElementById("upload_files_op");
|
||||||
changeListener(uploadFilesOp,uploadAttachHandler2);
|
changeListener(uploadFilesOp,uploadAttachHandler2);
|
||||||
bindAttachManager();
|
bindAttachManager();
|
||||||
|
|
||||||
function bindAttachItems() {
|
function bindAttachItems() {
|
||||||
$(".attach_item_select").unbind("click");
|
$(".attach_item_select").unbind("click");
|
||||||
$(".attach_item_copy").unbind("click");
|
$(".attach_item_copy").unbind("click");
|
||||||
$(".attach_item_select").click(function(){
|
$(".attach_item_select").click(function(){
|
||||||
let hold = $(this).closest(".attach_item");
|
let hold = $(this).closest(".attach_item");
|
||||||
if(hold.hasClass("attach_item_selected")) hold.removeClass("attach_item_selected");
|
if(hold.hasClass("attach_item_selected")) hold.removeClass("attach_item_selected");
|
||||||
else hold.addClass("attach_item_selected");
|
else hold.addClass("attach_item_selected");
|
||||||
});
|
});
|
||||||
$(".attach_item_copy").click(function(){
|
$(".attach_item_copy").click(function(){
|
||||||
let hold = $(this).closest(".attach_item");
|
let hold = $(this).closest(".attach_item");
|
||||||
let pathNode = hold.find(".attach_item_path");
|
let pathNode = hold.find(".attach_item_path");
|
||||||
copyToClipboard(pathNode.attr("fullPath"));
|
copyToClipboard(pathNode.attr("fullPath"));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
bindAttachItems();
|
bindAttachItems();
|
||||||
|
|
||||||
$(".attach_item_delete").unbind("click");
|
$(".attach_item_delete").unbind("click");
|
||||||
$(".attach_item_delete").click(function(){
|
$(".attach_item_delete").click(function(){
|
||||||
let formData = new URLSearchParams();
|
let formData = new URLSearchParams();
|
||||||
formData.append("s",me.User.S);
|
formData.append("s",me.User.S);
|
||||||
|
|
||||||
let post = this.closest(".post_item");
|
let post = this.closest(".post_item");
|
||||||
let aidList = "";
|
let aidList = "";
|
||||||
let elems = post.getElementsByClassName("attach_item_selected");
|
let elems = post.getElementsByClassName("attach_item_selected");
|
||||||
if(elems==null) return;
|
if(elems==null) return;
|
||||||
|
|
||||||
for(let i = 0; i < elems.length; i++) {
|
for(let i = 0; i < elems.length; i++) {
|
||||||
let pathNode = elems[i].querySelector(".attach_item_path");
|
let pathNode = elems[i].querySelector(".attach_item_path");
|
||||||
log("pathNode",pathNode);
|
log("pathNode",pathNode);
|
||||||
aidList += pathNode.getAttribute("aid")+",";
|
aidList += pathNode.getAttribute("aid")+",";
|
||||||
elems[i].remove();
|
elems[i].remove();
|
||||||
}
|
}
|
||||||
if(aidList.length > 0) aidList = aidList.slice(0, -1);
|
if(aidList.length > 0) aidList = aidList.slice(0, -1);
|
||||||
log("aidList",aidList)
|
log("aidList",aidList)
|
||||||
formData.append("aids",aidList);
|
formData.append("aids",aidList);
|
||||||
|
|
||||||
let ec = 0;
|
let ec = 0;
|
||||||
let e = post.getElementsByClassName("attach_item_item");
|
let e = post.getElementsByClassName("attach_item_item");
|
||||||
if(e!=null) ec = e.length;
|
if(e!=null) ec = e.length;
|
||||||
if(ec==0) post.classList.remove("has_attachs");
|
if(ec==0) post.classList.remove("has_attachs");
|
||||||
|
|
||||||
let req = new XMLHttpRequest();
|
let req = new XMLHttpRequest();
|
||||||
let fileDock = this.closest(".attach_edit_bay");
|
let fileDock = this.closest(".attach_edit_bay");
|
||||||
req.open("POST","//"+window.location.host+"/"+fileDock.getAttribute("type")+"/attach/remove/submit/"+fileDock.getAttribute("id"),true);
|
req.open("POST","//"+window.location.host+"/"+fileDock.getAttribute("type")+"/attach/remove/submit/"+fileDock.getAttribute("id"),true);
|
||||||
req.send(formData);
|
req.send(formData);
|
||||||
|
|
||||||
bindAttachItems();
|
bindAttachItems();
|
||||||
bindAttachManager();
|
bindAttachManager();
|
||||||
});
|
});
|
||||||
|
|
||||||
function addPollInput() {
|
function addPollInput() {
|
||||||
log("clicked on pollinputinput");
|
log("clicked on pollinputinput");
|
||||||
let dataPollInput = $(this).parent().attr("data-pollinput");
|
let dataPollInput = $(this).parent().attr("data-pollinput");
|
||||||
log("dataPollInput",dataPollInput);
|
log("dataPollInput",dataPollInput);
|
||||||
if(dataPollInput==undefined) return;
|
if(dataPollInput==undefined) return;
|
||||||
if(dataPollInput!=(pollInputIndex-1)) return;
|
if(dataPollInput!=(pollInputIndex-1)) return;
|
||||||
$(".poll_content_row .formitem").append(Tmpl_topic_c_poll_input({
|
$(".poll_content_row .formitem").append(Tmpl_topic_c_poll_input({
|
||||||
Index: pollInputIndex,
|
Index: pollInputIndex,
|
||||||
Place: phraseBox["topic"]["topic.reply_add_poll_option"].replace("%d",pollInputIndex),
|
Place: phraseBox["topic"]["topic.reply_add_poll_option"].replace("%d",pollInputIndex),
|
||||||
}));
|
}));
|
||||||
pollInputIndex++;
|
pollInputIndex++;
|
||||||
log("new pollInputIndex",pollInputIndex);
|
log("new pollInputIndex",pollInputIndex);
|
||||||
$(".pollinputinput").off("click");
|
$(".pollinputinput").off("click");
|
||||||
$(".pollinputinput").click(addPollInput);
|
$(".pollinputinput").click(addPollInput);
|
||||||
}
|
}
|
||||||
|
|
||||||
let pollInputIndex = 1;
|
let pollInputIndex = 1;
|
||||||
$("#add_poll_button").unbind("click");
|
$("#add_poll_button").unbind("click");
|
||||||
$("#add_poll_button").click(ev => {
|
$("#add_poll_button").click(ev => {
|
||||||
ev.preventDefault();
|
ev.preventDefault();
|
||||||
$(".poll_content_row").removeClass("auto_hide");
|
$(".poll_content_row").removeClass("auto_hide");
|
||||||
$("#has_poll_input").val("1");
|
$("#has_poll_input").val("1");
|
||||||
$(".pollinputinput").click(addPollInput);
|
$(".pollinputinput").click(addPollInput);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
//});
|
//});
|
||||||
function modCancel() {
|
function modCancel() {
|
||||||
log("enter modCancel");
|
log("enter modCancel");
|
||||||
if(!$(".mod_floater").hasClass("auto_hide")) $(".mod_floater").addClass("auto_hide")
|
if(!$(".mod_floater").hasClass("auto_hide")) $(".mod_floater").addClass("auto_hide")
|
||||||
$(".moderate_link").unbind("click");
|
$(".moderate_link").unbind("click");
|
||||||
$(".moderate_link").removeClass("moderate_open");
|
$(".moderate_link").removeClass("moderate_open");
|
||||||
$(".pre_opt").addClass("auto_hide");
|
$(".pre_opt").addClass("auto_hide");
|
||||||
$(".mod_floater_submit").unbind("click");
|
$(".mod_floater_submit").unbind("click");
|
||||||
$("#topicsItemList,#forumItemList").removeClass("topics_moderate");
|
$("#topicsItemList,#forumItemList").removeClass("topics_moderate");
|
||||||
$(".topic_selected").removeClass("topic_selected");
|
$(".topic_selected").removeClass("topic_selected");
|
||||||
// ! Be careful not to trample bindings elsewhere
|
// ! Be careful not to trample bindings elsewhere
|
||||||
$(".topic_row").unbind("click");
|
$(".topic_row").unbind("click");
|
||||||
$("#mod_topic_mover").addClass("auto_hide");
|
$("#mod_topic_mover").addClass("auto_hide");
|
||||||
}
|
}
|
||||||
function modCancelBind() {
|
function modCancelBind() {
|
||||||
log("enter modCancelBind")
|
log("enter modCancelBind")
|
||||||
$(".moderate_link").unbind("click");
|
$(".moderate_link").unbind("click");
|
||||||
$(".moderate_open").click(ev => {
|
$(".moderate_open").click(ev => {
|
||||||
modCancel();
|
modCancel();
|
||||||
$(".moderate_open").unbind("click");
|
$(".moderate_open").unbind("click");
|
||||||
modLinkBind();
|
modLinkBind();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
function modLinkBind() {
|
function modLinkBind() {
|
||||||
log("enter modLinkBind");
|
log("enter modLinkBind");
|
||||||
$(".moderate_link").click(ev => {
|
$(".moderate_link").click(ev => {
|
||||||
log("enter .moderate_link");
|
log("enter .moderate_link");
|
||||||
ev.preventDefault();
|
ev.preventDefault();
|
||||||
$(".pre_opt").removeClass("auto_hide");
|
$(".pre_opt").removeClass("auto_hide");
|
||||||
$(".moderate_link").addClass("moderate_open");
|
$(".moderate_link").addClass("moderate_open");
|
||||||
selectedTopics=[];
|
selectedTopics=[];
|
||||||
modCancelBind();
|
modCancelBind();
|
||||||
$("#topicsItemList,#forumItemList").addClass("topics_moderate");
|
$("#topicsItemList,#forumItemList").addClass("topics_moderate");
|
||||||
$(".topic_row").each(function(){
|
$(".topic_row").each(function(){
|
||||||
$(this).click(function(){
|
$(this).click(function(){
|
||||||
if(!this.classList.contains("can_mod")) return;
|
if(!this.classList.contains("can_mod")) return;
|
||||||
let tid = parseInt($(this).attr("data-tid"),10);
|
let tid = parseInt($(this).attr("data-tid"),10);
|
||||||
let sel = this.classList.contains("topic_selected");
|
let sel = this.classList.contains("topic_selected");
|
||||||
if(sel) {
|
if(sel) {
|
||||||
for(var i=0; i<selectedTopics.length; i++){
|
for(var i=0; i<selectedTopics.length; i++){
|
||||||
if(selectedTopics[i]===tid) selectedTopics.splice(i, 1);
|
if(selectedTopics[i]===tid) selectedTopics.splice(i, 1);
|
||||||
}
|
}
|
||||||
} else selectedTopics.push(tid);
|
} else selectedTopics.push(tid);
|
||||||
if(selectedTopics.length==1) {
|
if(selectedTopics.length==1) {
|
||||||
var msg = phraseBox["topic_list"]["topic_list.what_to_do_single"];
|
var msg = phraseBox["topic_list"]["topic_list.what_to_do_single"];
|
||||||
} else {
|
} else {
|
||||||
var msg = "What do you want to do with these "+selectedTopics.length+" topics?";
|
var msg = "What do you want to do with these "+selectedTopics.length+" topics?";
|
||||||
}
|
}
|
||||||
$(".mod_floater_head span").html(msg);
|
$(".mod_floater_head span").html(msg);
|
||||||
if(!sel) {
|
if(!sel) {
|
||||||
$(this).addClass("topic_selected");
|
$(this).addClass("topic_selected");
|
||||||
$(".mod_floater").removeClass("auto_hide");
|
$(".mod_floater").removeClass("auto_hide");
|
||||||
} else {
|
} else {
|
||||||
$(this).removeClass("topic_selected");
|
$(this).removeClass("topic_selected");
|
||||||
}
|
}
|
||||||
if(selectedTopics.length==0 && !$(".mod_floater").hasClass("auto_hide")) $(".mod_floater").addClass("auto_hide");
|
if(selectedTopics.length==0 && !$(".mod_floater").hasClass("auto_hide")) $(".mod_floater").addClass("auto_hide");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
let bulkActionSender = (action,selectedTopics,fragBit) => {
|
let bulkActionSender = (action,selectedTopics,fragBit) => {
|
||||||
$.ajax({
|
$.ajax({
|
||||||
url: "/topic/"+action+"/submit/"+fragBit+"?s="+me.User.S,
|
url: "/topic/"+action+"/submit/"+fragBit+"?s="+me.User.S,
|
||||||
type: "POST",
|
type: "POST",
|
||||||
data: JSON.stringify(selectedTopics),
|
data: JSON.stringify(selectedTopics),
|
||||||
contentType: "application/json",
|
contentType: "application/json",
|
||||||
error: ajaxError,
|
error: ajaxError,
|
||||||
success: () => window.location.reload()
|
success: () => window.location.reload()
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
// TODO: Should we unbind this here to avoid binding multiple listeners to this accidentally?
|
// TODO: Should we unbind this here to avoid binding multiple listeners to this accidentally?
|
||||||
$(".mod_floater_submit").click(function(ev){
|
$(".mod_floater_submit").click(function(ev){
|
||||||
ev.preventDefault();
|
ev.preventDefault();
|
||||||
let selectNode = this.form.querySelector(".mod_floater_options");
|
let selectNode = this.form.querySelector(".mod_floater_options");
|
||||||
let optionNode = selectNode.options[selectNode.selectedIndex];
|
let optionNode = selectNode.options[selectNode.selectedIndex];
|
||||||
let action = optionNode.getAttribute("value");
|
let action = optionNode.getAttribute("value");
|
||||||
|
|
||||||
// Handle these specially
|
// Handle these specially
|
||||||
switch(action) {
|
switch(action) {
|
||||||
case "move":
|
case "move":
|
||||||
log("move action");
|
log("move action");
|
||||||
let modTopicMover = $("#mod_topic_mover");
|
let modTopicMover = $("#mod_topic_mover");
|
||||||
$("#mod_topic_mover").removeClass("auto_hide");
|
$("#mod_topic_mover").removeClass("auto_hide");
|
||||||
$("#mod_topic_mover .pane_row").unbind("click");
|
$("#mod_topic_mover .pane_row").unbind("click");
|
||||||
$("#mod_topic_mover .pane_row").click(function(){
|
$("#mod_topic_mover .pane_row").click(function(){
|
||||||
modTopicMover.find(".pane_row").removeClass("pane_selected");
|
modTopicMover.find(".pane_row").removeClass("pane_selected");
|
||||||
let fid = this.getAttribute("data-fid");
|
let fid = this.getAttribute("data-fid");
|
||||||
if(fid==null) return;
|
if(fid==null) return;
|
||||||
this.classList.add("pane_selected");
|
this.classList.add("pane_selected");
|
||||||
log("fid",fid);
|
log("fid",fid);
|
||||||
forumToMoveTo = fid;
|
forumToMoveTo = fid;
|
||||||
|
|
||||||
$("#mover_submit").unbind("click");
|
$("#mover_submit").unbind("click");
|
||||||
$("#mover_submit").click(ev => {
|
$("#mover_submit").click(ev => {
|
||||||
ev.preventDefault();
|
ev.preventDefault();
|
||||||
bulkActionSender("move",selectedTopics,forumToMoveTo);
|
bulkActionSender("move",selectedTopics,forumToMoveTo);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
bulkActionSender(action,selectedTopics,"");
|
bulkActionSender(action,selectedTopics,"");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
//addInitHook("after_init_bind_page", () => {
|
//addInitHook("after_init_bind_page", () => {
|
||||||
//addInitHook("before_init_bind_page", () => {
|
//addInitHook("before_init_bind_page", () => {
|
||||||
//log("in member.js before_init_bind_page 2")
|
//log("in member.js before_init_bind_page 2")
|
||||||
addInitHook("end_bind_page", () => {
|
addInitHook("end_bind_page", () => {
|
||||||
log("in member.js end_bind_page")
|
log("in member.js end_bind_page")
|
||||||
modCancel();
|
modCancel();
|
||||||
modLinkBind();
|
modLinkBind();
|
||||||
});
|
});
|
||||||
addInitHook("after_init_bind_page", () => addHook("end_unbind_page", () => modCancel()))
|
addInitHook("after_init_bind_page", () => addHook("end_unbind_page", () => modCancel()))
|
||||||
//});
|
//});
|
||||||
})()
|
})()
|
|
@ -1,5 +1,5 @@
|
||||||
(() => {
|
(() => {
|
||||||
addInitHook("end_init", () => {
|
addInitHook("end_init", () => {
|
||||||
formVars = {'perm_preset': ['can_moderate','can_post','read_only','no_access','default','custom']};
|
formVars = {'perm_preset': ['can_moderate','can_post','read_only','no_access','default','custom']};
|
||||||
});
|
});
|
||||||
})();
|
})();
|
|
@ -2,8 +2,8 @@
|
||||||
addInitHook("end_init", () => {
|
addInitHook("end_init", () => {
|
||||||
|
|
||||||
formVars = {
|
formVars = {
|
||||||
'forum_active': ['Hide','Show'],
|
'forum_active': ['Hide','Show'],
|
||||||
'forum_preset': ['all','announce','members','staff','admins','archive','custom']
|
'forum_preset': ['all','announce','members','staff','admins','archive','custom']
|
||||||
};
|
};
|
||||||
var forums = {};
|
var forums = {};
|
||||||
let items = document.getElementsByClassName("panel_forum_item");
|
let items = document.getElementsByClassName("panel_forum_item");
|
||||||
|
@ -11,48 +11,48 @@ for(let i=0; item=items[i]; i++) forums[i] = item.getAttribute("data-fid");
|
||||||
log("forums",forums);
|
log("forums",forums);
|
||||||
|
|
||||||
Sortable.create(document.getElementById("panel_forums"), {
|
Sortable.create(document.getElementById("panel_forums"), {
|
||||||
sort: true,
|
sort: true,
|
||||||
onEnd: (evt) => {
|
onEnd: (evt) => {
|
||||||
log("pre forums",forums)
|
log("pre forums",forums)
|
||||||
log("evt",evt)
|
log("evt",evt)
|
||||||
let oldFid = forums[evt.newIndex];
|
let oldFid = forums[evt.newIndex];
|
||||||
forums[evt.oldIndex] = oldFid;
|
forums[evt.oldIndex] = oldFid;
|
||||||
let newFid = evt.item.getAttribute("data-fid");
|
let newFid = evt.item.getAttribute("data-fid");
|
||||||
log("newFid",newFid);
|
log("newFid",newFid);
|
||||||
forums[evt.newIndex] = newFid;
|
forums[evt.newIndex] = newFid;
|
||||||
log("post forums",forums);
|
log("post forums",forums);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById("panel_forums_order_button").addEventListener("click", () => {
|
document.getElementById("panel_forums_order_button").addEventListener("click", () => {
|
||||||
let req = new XMLHttpRequest();
|
let req = new XMLHttpRequest();
|
||||||
if(!req) {
|
if(!req) {
|
||||||
log("Failed to create request");
|
log("Failed to create request");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
req.onreadystatechange = () => {
|
req.onreadystatechange = () => {
|
||||||
try {
|
try {
|
||||||
if(req.readyState!==XMLHttpRequest.DONE) return;
|
if(req.readyState!==XMLHttpRequest.DONE) return;
|
||||||
// TODO: Signal the error with a notice
|
// TODO: Signal the error with a notice
|
||||||
if(req.status!==200) return;
|
if(req.status!==200) return;
|
||||||
|
|
||||||
let resp = JSON.parse(req.responseText);
|
let resp = JSON.parse(req.responseText);
|
||||||
log("resp",resp);
|
log("resp",resp);
|
||||||
// TODO: Should we move other notices into TmplPhrases like this one?
|
// TODO: Should we move other notices into TmplPhrases like this one?
|
||||||
pushNotice(phraseBox["panel"]["panel.forums_order_updated"]);
|
pushNotice(phraseBox["panel"]["panel.forums_order_updated"]);
|
||||||
if(resp.success==1) return;
|
if(resp.success==1) return;
|
||||||
} catch(e) {
|
} catch(e) {
|
||||||
console.error("e",e)
|
console.error("e",e)
|
||||||
}
|
}
|
||||||
console.trace();
|
console.trace();
|
||||||
}
|
}
|
||||||
// ? - Is encodeURIComponent the right function for this?
|
// ? - Is encodeURIComponent the right function for this?
|
||||||
req.open("POST","/panel/forums/order/edit/submit/?s=" + encodeURIComponent(me.User.S));
|
req.open("POST","/panel/forums/order/edit/submit/?s=" + encodeURIComponent(me.User.S));
|
||||||
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
|
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
|
||||||
let items = "";
|
let items = "";
|
||||||
for(let i=0;item=forums[i];i++) items += item+",";
|
for(let i=0;item=forums[i];i++) items += item+",";
|
||||||
if(items.length > 0) items = items.slice(0,-1);
|
if(items.length > 0) items = items.slice(0,-1);
|
||||||
req.send("js=1&items={"+items+"}");
|
req.send("js=1&items={"+items+"}");
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
(() => {
|
(() => {
|
||||||
addInitHook("end_init", () => {
|
addInitHook("end_init", () => {
|
||||||
|
|
||||||
// TODO: Move this into a JS file to reduce the number of possible problems
|
// TODO: Move this into a JS file to reduce the number of possible problems
|
||||||
var menuItems = {};
|
var menuItems = {};
|
||||||
|
@ -7,49 +7,49 @@ let items = document.getElementsByClassName("panel_menu_item");
|
||||||
for(let i=0; item=items[i]; i++) menuItems[i] = item.getAttribute("data-miid");
|
for(let i=0; item=items[i]; i++) menuItems[i] = item.getAttribute("data-miid");
|
||||||
|
|
||||||
Sortable.create(document.getElementById("panel_menu_item_holder"), {
|
Sortable.create(document.getElementById("panel_menu_item_holder"), {
|
||||||
sort: true,
|
sort: true,
|
||||||
onEnd: evt => {
|
onEnd: evt => {
|
||||||
log("pre menuItems",menuItems)
|
log("pre menuItems",menuItems)
|
||||||
log("evt",evt)
|
log("evt",evt)
|
||||||
let oldMiid = menuItems[evt.newIndex];
|
let oldMiid = menuItems[evt.newIndex];
|
||||||
menuItems[evt.oldIndex] = oldMiid;
|
menuItems[evt.oldIndex] = oldMiid;
|
||||||
let newMiid = evt.item.getAttribute("data-miid");
|
let newMiid = evt.item.getAttribute("data-miid");
|
||||||
log("newMiid",newMiid);
|
log("newMiid",newMiid);
|
||||||
menuItems[evt.newIndex] = newMiid;
|
menuItems[evt.newIndex] = newMiid;
|
||||||
log("post menuItems",menuItems);
|
log("post menuItems",menuItems);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
document.getElementById("panel_menu_items_order_button").addEventListener("click", () => {
|
document.getElementById("panel_menu_items_order_button").addEventListener("click", () => {
|
||||||
let req = new XMLHttpRequest();
|
let req = new XMLHttpRequest();
|
||||||
if(!req) {
|
if(!req) {
|
||||||
log("Failed to create request");
|
log("Failed to create request");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
req.onreadystatechange = () => {
|
req.onreadystatechange = () => {
|
||||||
try {
|
try {
|
||||||
if(req.readyState!==XMLHttpRequest.DONE) return;
|
if(req.readyState!==XMLHttpRequest.DONE) return;
|
||||||
// TODO: Signal the error with a notice
|
// TODO: Signal the error with a notice
|
||||||
if(req.status===200) {
|
if(req.status===200) {
|
||||||
let resp = JSON.parse(req.responseText);
|
let resp = JSON.parse(req.responseText);
|
||||||
log("resp",resp);
|
log("resp",resp);
|
||||||
// TODO: Should we move other notices into TmplPhrases like this one?
|
// TODO: Should we move other notices into TmplPhrases like this one?
|
||||||
pushNotice(phraseBox["panel"]["panel.themes_menus_items_order_updated"]);
|
pushNotice(phraseBox["panel"]["panel.themes_menus_items_order_updated"]);
|
||||||
if(resp.success==1) return;
|
if(resp.success==1) return;
|
||||||
}
|
}
|
||||||
} catch(e) {
|
} catch(e) {
|
||||||
console.error("e",e)
|
console.error("e",e)
|
||||||
}
|
}
|
||||||
console.trace();
|
console.trace();
|
||||||
}
|
}
|
||||||
// ? - Is encodeURIComponent the right function for this?
|
// ? - Is encodeURIComponent the right function for this?
|
||||||
let spl = document.location.pathname.split("/");
|
let spl = document.location.pathname.split("/");
|
||||||
req.open("POST","/panel/themes/menus/item/order/edit/submit/"+parseInt(spl[spl.length-1],10)+"?s="+encodeURIComponent(me.User.S));
|
req.open("POST","/panel/themes/menus/item/order/edit/submit/"+parseInt(spl[spl.length-1],10)+"?s="+encodeURIComponent(me.User.S));
|
||||||
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
|
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
|
||||||
let items = "";
|
let items = "";
|
||||||
for(let i=0; item=menuItems[i];i++) items += item+",";
|
for(let i=0; item=menuItems[i];i++) items += item+",";
|
||||||
if(items.length > 0) items = items.slice(0,-1);
|
if(items.length > 0) items = items.slice(0,-1);
|
||||||
req.send("js=1&items={"+items+"}");
|
req.send("js=1&items={"+items+"}");
|
||||||
});
|
});
|
||||||
|
|
||||||
});
|
});
|
||||||
|
|
|
@ -1,23 +1,23 @@
|
||||||
function handle_profile_hashbit() {
|
function handle_profile_hashbit() {
|
||||||
var hash_class = "";
|
var hash_class = "";
|
||||||
switch(window.location.hash.substr(1)) {
|
switch(window.location.hash.substr(1)) {
|
||||||
case "ban_user":
|
case "ban_user":
|
||||||
hash_class = "ban_user_hash";
|
hash_class = "ban_user_hash";
|
||||||
break;
|
break;
|
||||||
case "delete_posts":
|
case "delete_posts":
|
||||||
hash_class = "delete_posts_hash";
|
hash_class = "delete_posts_hash";
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
log("Unknown hashbit");
|
log("Unknown hashbit");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
$(".hash_hide").hide();
|
$(".hash_hide").hide();
|
||||||
$("." + hash_class).show();
|
$("." + hash_class).show();
|
||||||
}
|
}
|
||||||
|
|
||||||
(() => {
|
(() => {
|
||||||
addInitHook("end_init", () => {
|
addInitHook("end_init", () => {
|
||||||
if(window.location.hash) handle_profile_hashbit();
|
if(window.location.hash) handle_profile_hashbit();
|
||||||
window.addEventListener("hashchange", handle_profile_hashbit, false);
|
window.addEventListener("hashchange", handle_profile_hashbit, false);
|
||||||
});
|
});
|
||||||
})();
|
})();
|
|
@ -1,14 +1,14 @@
|
||||||
(() => {
|
(() => {
|
||||||
addInitHook("end_init", () => {
|
addInitHook("end_init", () => {
|
||||||
fetch("/api/watches/")
|
fetch("/api/watches/")
|
||||||
.then(resp => {
|
.then(resp => {
|
||||||
if(resp.status!==200) {
|
if(resp.status!==200) {
|
||||||
log("err");
|
log("err");
|
||||||
log("resp",resp);
|
log("resp",resp);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
resp.text().then(d => eval(d));
|
resp.text().then(d => eval(d));
|
||||||
})
|
})
|
||||||
.catch(e => log("e",e));
|
.catch(e => log("e",e));
|
||||||
});
|
});
|
||||||
})()
|
})()
|
|
@ -1,64 +1,64 @@
|
||||||
"use strict";
|
"use strict";
|
||||||
$(document).ready(() => {
|
$(document).ready(() => {
|
||||||
let clickHandle = function(ev){
|
let clickHandle = function(ev){
|
||||||
log("in clickHandle")
|
log("in clickHandle")
|
||||||
ev.preventDefault();
|
ev.preventDefault();
|
||||||
let ep = $(this).closest(".editable_parent");
|
let ep = $(this).closest(".editable_parent");
|
||||||
ep.find(".hide_on_block_edit").addClass("edit_opened");
|
ep.find(".hide_on_block_edit").addClass("edit_opened");
|
||||||
ep.find(".show_on_block_edit").addClass("edit_opened");
|
ep.find(".show_on_block_edit").addClass("edit_opened");
|
||||||
ep.addClass("in_edit");
|
ep.addClass("in_edit");
|
||||||
|
|
||||||
ep.find(".widget_save").click(() => {
|
ep.find(".widget_save").click(() => {
|
||||||
ep.find(".hide_on_block_edit").removeClass("edit_opened");
|
ep.find(".hide_on_block_edit").removeClass("edit_opened");
|
||||||
ep.find(".show_on_block_edit").removeClass("edit_opened");
|
ep.find(".show_on_block_edit").removeClass("edit_opened");
|
||||||
ep.removeClass("in_edit");
|
ep.removeClass("in_edit");
|
||||||
});
|
});
|
||||||
|
|
||||||
ep.find(".widget_delete").click(function(ev) {
|
ep.find(".widget_delete").click(function(ev) {
|
||||||
ev.preventDefault();
|
ev.preventDefault();
|
||||||
ep.remove();
|
ep.remove();
|
||||||
let formData = new URLSearchParams();
|
let formData = new URLSearchParams();
|
||||||
formData.append("s",me.User.S);
|
formData.append("s",me.User.S);
|
||||||
let req = new XMLHttpRequest();
|
let req = new XMLHttpRequest();
|
||||||
let target = this.closest("a").getAttribute("href");
|
let target = this.closest("a").getAttribute("href");
|
||||||
req.open("POST",target,true);
|
req.open("POST",target,true);
|
||||||
req.send(formData);
|
req.send(formData);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
$(".widget_item a").click(clickHandle);
|
$(".widget_item a").click(clickHandle);
|
||||||
|
|
||||||
let changeHandle = function(ev){
|
let changeHandle = function(ev){
|
||||||
let wtype = this.options[this.selectedIndex].value;
|
let wtype = this.options[this.selectedIndex].value;
|
||||||
let typeBlock = this.closest(".widget_edit").querySelector(".wtypes");
|
let typeBlock = this.closest(".widget_edit").querySelector(".wtypes");
|
||||||
typeBlock.className = "wtypes wtype_"+wtype;
|
typeBlock.className = "wtypes wtype_"+wtype;
|
||||||
};
|
};
|
||||||
$(".wtype_sel").change(changeHandle);
|
$(".wtype_sel").change(changeHandle);
|
||||||
|
|
||||||
$(".widget_new a").click(function(ev){
|
$(".widget_new a").click(function(ev){
|
||||||
log("clicked widget_new a")
|
log("clicked widget_new a")
|
||||||
let widgetList = this.closest(".panel_widgets");
|
let widgetList = this.closest(".panel_widgets");
|
||||||
let widgetNew = this.closest(".widget_new");
|
let widgetNew = this.closest(".widget_new");
|
||||||
let widgetTmpl = document.getElementById("widgetTmpl").querySelector(".widget_item");
|
let widgetTmpl = document.getElementById("widgetTmpl").querySelector(".widget_item");
|
||||||
let n = widgetTmpl.cloneNode(true);
|
let n = widgetTmpl.cloneNode(true);
|
||||||
n.querySelector(".wside").value = this.getAttribute("data-dock");
|
n.querySelector(".wside").value = this.getAttribute("data-dock");
|
||||||
widgetList.insertBefore(n,widgetNew);
|
widgetList.insertBefore(n,widgetNew);
|
||||||
$(".widget_item a").unbind("click");
|
$(".widget_item a").unbind("click");
|
||||||
$(".widget_item a").click(clickHandle);
|
$(".widget_item a").click(clickHandle);
|
||||||
$(".wtype_sel").unbind("change");
|
$(".wtype_sel").unbind("change");
|
||||||
$(".wtype_sel").change(changeHandle);
|
$(".wtype_sel").change(changeHandle);
|
||||||
});
|
});
|
||||||
|
|
||||||
$(".widget_save").click(function(ev){
|
$(".widget_save").click(function(ev){
|
||||||
log("in .widget_save")
|
log("in .widget_save")
|
||||||
ev.preventDefault();
|
ev.preventDefault();
|
||||||
ev.stopPropagation();
|
ev.stopPropagation();
|
||||||
let pform = this.closest("form");
|
let pform = this.closest("form");
|
||||||
let dat = new URLSearchParams();
|
let dat = new URLSearchParams();
|
||||||
for (const pair of new FormData(pform)) dat.append(pair[0], pair[1]);
|
for (const pair of new FormData(pform)) dat.append(pair[0], pair[1]);
|
||||||
dat.append("s",me.User.S);
|
dat.append("s",me.User.S);
|
||||||
var req = new XMLHttpRequest();
|
var req = new XMLHttpRequest();
|
||||||
req.open("POST",pform.getAttribute("action"));
|
req.open("POST",pform.getAttribute("action"));
|
||||||
req.send(dat);
|
req.send(dat);
|
||||||
});
|
});
|
||||||
});
|
});
|
|
@ -1,8 +0,0 @@
|
||||||
echo "Updating Gosora"
|
|
||||||
git stash
|
|
||||||
git pull origin master
|
|
||||||
git stash apply
|
|
||||||
|
|
||||||
echo "Patching Gosora"
|
|
||||||
go build -ldflags="-s -w" -o Patcher "./patcher"
|
|
||||||
./Patcher
|
|
494
router.go
494
router.go
|
@ -2,214 +2,214 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
c "github.com/Azareal/Gosora/common"
|
c "github.com/Azareal/Gosora/common"
|
||||||
co "github.com/Azareal/Gosora/common/counters"
|
co "github.com/Azareal/Gosora/common/counters"
|
||||||
)
|
)
|
||||||
|
|
||||||
// TODO: Stop spilling these into the package scope?
|
// TODO: Stop spilling these into the package scope?
|
||||||
func init() {
|
func init() {
|
||||||
_ = time.Now()
|
_ = time.Now()
|
||||||
co.SetRouteMapEnum(routeMapEnum)
|
co.SetRouteMapEnum(routeMapEnum)
|
||||||
co.SetReverseRouteMapEnum(reverseRouteMapEnum)
|
co.SetReverseRouteMapEnum(reverseRouteMapEnum)
|
||||||
co.SetAgentMapEnum(agentMapEnum)
|
co.SetAgentMapEnum(agentMapEnum)
|
||||||
co.SetReverseAgentMapEnum(reverseAgentMapEnum)
|
co.SetReverseAgentMapEnum(reverseAgentMapEnum)
|
||||||
co.SetOSMapEnum(osMapEnum)
|
co.SetOSMapEnum(osMapEnum)
|
||||||
co.SetReverseOSMapEnum(reverseOSMapEnum)
|
co.SetReverseOSMapEnum(reverseOSMapEnum)
|
||||||
|
|
||||||
g := func(n string) int {
|
g := func(n string) int {
|
||||||
a, ok := agentMapEnum[n]
|
a, ok := agentMapEnum[n]
|
||||||
if !ok {
|
if !ok {
|
||||||
panic("name not found in agentMapEnum")
|
panic("name not found in agentMapEnum")
|
||||||
}
|
}
|
||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
c.Chrome = g("chrome")
|
c.Chrome = g("chrome")
|
||||||
c.Firefox = g("firefox")
|
c.Firefox = g("firefox")
|
||||||
c.SimpleBots = []int{
|
c.SimpleBots = []int{
|
||||||
g("semrush"),
|
g("semrush"),
|
||||||
g("ahrefs"),
|
g("ahrefs"),
|
||||||
g("python"),
|
g("python"),
|
||||||
//g("go"),
|
//g("go"),
|
||||||
g("curl"),
|
g("curl"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type WriterIntercept struct {
|
type WriterIntercept struct {
|
||||||
http.ResponseWriter
|
http.ResponseWriter
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewWriterIntercept(w http.ResponseWriter) *WriterIntercept {
|
func NewWriterIntercept(w http.ResponseWriter) *WriterIntercept {
|
||||||
return &WriterIntercept{w}
|
return &WriterIntercept{w}
|
||||||
}
|
}
|
||||||
|
|
||||||
var wiMaxAge = "max-age=" + strconv.Itoa(int(c.Day))
|
var wiMaxAge = "max-age=" + strconv.Itoa(int(c.Day))
|
||||||
|
|
||||||
func (wi *WriterIntercept) WriteHeader(code int) {
|
func (wi *WriterIntercept) WriteHeader(code int) {
|
||||||
if code == 200 {
|
if code == 200 {
|
||||||
h := wi.ResponseWriter.Header()
|
h := wi.ResponseWriter.Header()
|
||||||
h.Set("Cache-Control", wiMaxAge)
|
h.Set("Cache-Control", wiMaxAge)
|
||||||
h.Set("Vary", "Accept-Encoding")
|
h.Set("Vary", "Accept-Encoding")
|
||||||
}
|
}
|
||||||
wi.ResponseWriter.WriteHeader(code)
|
wi.ResponseWriter.WriteHeader(code)
|
||||||
}
|
}
|
||||||
|
|
||||||
type GenRouter struct {
|
type GenRouter struct {
|
||||||
UploadHandler func(http.ResponseWriter, *http.Request)
|
UploadHandler func(http.ResponseWriter, *http.Request)
|
||||||
extraRoutes map[string]func(http.ResponseWriter, *http.Request, *c.User) c.RouteError
|
extraRoutes map[string]func(http.ResponseWriter, *http.Request, *c.User) c.RouteError
|
||||||
|
|
||||||
reqLogger *log.Logger
|
reqLogger *log.Logger
|
||||||
|
|
||||||
reqLog2 *RouterLog
|
reqLog2 *RouterLog
|
||||||
suspLog *RouterLog
|
suspLog *RouterLog
|
||||||
|
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
type RouterLogLog struct {
|
type RouterLogLog struct {
|
||||||
File *os.File
|
File *os.File
|
||||||
Log *log.Logger
|
Log *log.Logger
|
||||||
}
|
}
|
||||||
type RouterLog struct {
|
type RouterLog struct {
|
||||||
FileVal atomic.Value
|
FileVal atomic.Value
|
||||||
LogVal atomic.Value
|
LogVal atomic.Value
|
||||||
|
|
||||||
sync.RWMutex
|
sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *GenRouter) DailyTick() error {
|
func (r *GenRouter) DailyTick() error {
|
||||||
currentTime := time.Now()
|
currentTime := time.Now()
|
||||||
rotateLog := func(l *RouterLog, name string) error {
|
rotateLog := func(l *RouterLog, name string) error {
|
||||||
l.Lock()
|
l.Lock()
|
||||||
defer l.Unlock()
|
defer l.Unlock()
|
||||||
|
|
||||||
f := l.FileVal.Load().(*os.File)
|
f := l.FileVal.Load().(*os.File)
|
||||||
stat, e := f.Stat()
|
stat, e := f.Stat()
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if (stat.Size() < int64(c.Megabyte)) && (currentTime.Sub(c.StartTime).Hours() >= (24 * 7)) {
|
if (stat.Size() < int64(c.Megabyte)) && (currentTime.Sub(c.StartTime).Hours() >= (24 * 7)) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if e = f.Close(); e != nil {
|
if e = f.Close(); e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
|
|
||||||
stimestr := strconv.FormatInt(currentTime.Unix(), 10)
|
stimestr := strconv.FormatInt(currentTime.Unix(), 10)
|
||||||
f, e = os.OpenFile(c.Config.LogDir+name+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
|
f, e = os.OpenFile(c.Config.LogDir+name+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
|
||||||
if e != nil {
|
if e != nil {
|
||||||
return e
|
return e
|
||||||
}
|
}
|
||||||
lval := log.New(f, "", log.LstdFlags)
|
lval := log.New(f, "", log.LstdFlags)
|
||||||
l.FileVal.Store(f)
|
l.FileVal.Store(f)
|
||||||
l.LogVal.Store(lval)
|
l.LogVal.Store(lval)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if !c.Config.DisableSuspLog {
|
if !c.Config.DisableSuspLog {
|
||||||
err := rotateLog(r.suspLog, "reqs-susp-")
|
err := rotateLog(r.suspLog, "reqs-susp-")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return rotateLog(r.reqLog2, "reqs-")
|
return rotateLog(r.reqLog2, "reqs-")
|
||||||
}
|
}
|
||||||
|
|
||||||
type RouterConfig struct {
|
type RouterConfig struct {
|
||||||
Uploads http.Handler
|
Uploads http.Handler
|
||||||
DisableTick bool
|
DisableTick bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewGenRouter(cfg *RouterConfig) (*GenRouter, error) {
|
func NewGenRouter(cfg *RouterConfig) (*GenRouter, error) {
|
||||||
stimestr := strconv.FormatInt(c.StartTime.Unix(), 10)
|
stimestr := strconv.FormatInt(c.StartTime.Unix(), 10)
|
||||||
createLog := func(name, stimestr string) (*RouterLog, error) {
|
createLog := func(name, stimestr string) (*RouterLog, error) {
|
||||||
f, err := os.OpenFile(c.Config.LogDir+name+"-"+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
|
f, err := os.OpenFile(c.Config.LogDir+name+"-"+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
l := log.New(f, "", log.LstdFlags)
|
l := log.New(f, "", log.LstdFlags)
|
||||||
var aVal atomic.Value
|
var aVal atomic.Value
|
||||||
var aVal2 atomic.Value
|
var aVal2 atomic.Value
|
||||||
aVal.Store(f)
|
aVal.Store(f)
|
||||||
aVal2.Store(l)
|
aVal2.Store(l)
|
||||||
return &RouterLog{FileVal: aVal, LogVal: aVal2}, nil
|
return &RouterLog{FileVal: aVal, LogVal: aVal2}, nil
|
||||||
}
|
}
|
||||||
reqLog, err := createLog("reqs", stimestr)
|
reqLog, err := createLog("reqs", stimestr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
var suspReqLog *RouterLog
|
var suspReqLog *RouterLog
|
||||||
if !c.Config.DisableSuspLog {
|
if !c.Config.DisableSuspLog {
|
||||||
suspReqLog, err = createLog("reqs-susp", stimestr)
|
suspReqLog, err = createLog("reqs-susp", stimestr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
f3, err := os.OpenFile(c.Config.LogDir+"reqs-misc-"+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
|
f3, err := os.OpenFile(c.Config.LogDir+"reqs-misc-"+stimestr+".log", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0755)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
reqMiscLog := log.New(f3, "", log.LstdFlags)
|
reqMiscLog := log.New(f3, "", log.LstdFlags)
|
||||||
|
|
||||||
ro := &GenRouter{
|
ro := &GenRouter{
|
||||||
UploadHandler: func(w http.ResponseWriter, r *http.Request) {
|
UploadHandler: func(w http.ResponseWriter, r *http.Request) {
|
||||||
writ := NewWriterIntercept(w)
|
writ := NewWriterIntercept(w)
|
||||||
http.StripPrefix("/uploads/", cfg.Uploads).ServeHTTP(writ, r)
|
http.StripPrefix("/uploads/", cfg.Uploads).ServeHTTP(writ, r)
|
||||||
},
|
},
|
||||||
extraRoutes: make(map[string]func(http.ResponseWriter, *http.Request, *c.User) c.RouteError),
|
extraRoutes: make(map[string]func(http.ResponseWriter, *http.Request, *c.User) c.RouteError),
|
||||||
|
|
||||||
reqLogger: reqMiscLog,
|
reqLogger: reqMiscLog,
|
||||||
reqLog2: reqLog,
|
reqLog2: reqLog,
|
||||||
suspLog: suspReqLog,
|
suspLog: suspReqLog,
|
||||||
}
|
}
|
||||||
if !cfg.DisableTick {
|
if !cfg.DisableTick {
|
||||||
c.Tasks.Day.Add(ro.DailyTick)
|
c.Tasks.Day.Add(ro.DailyTick)
|
||||||
}
|
}
|
||||||
return ro, nil
|
return ro, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *GenRouter) handleError(err c.RouteError, w http.ResponseWriter, req *http.Request, u *c.User) {
|
func (r *GenRouter) handleError(err c.RouteError, w http.ResponseWriter, req *http.Request, u *c.User) {
|
||||||
if err.Handled() {
|
if err.Handled() {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if err.Type() == "system" {
|
if err.Type() == "system" {
|
||||||
c.InternalErrorJSQ(err, w, req, err.JSON())
|
c.InternalErrorJSQ(err, w, req, err.JSON())
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
c.LocalErrorJSQ(err.Error(), w, req, u, err.JSON())
|
c.LocalErrorJSQ(err.Error(), w, req, u, err.JSON())
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *GenRouter) Handle(_ string, _ http.Handler) {
|
func (r *GenRouter) Handle(_ string, _ http.Handler) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *GenRouter) HandleFunc(pattern string, h func(http.ResponseWriter, *http.Request, *c.User) c.RouteError) {
|
func (r *GenRouter) HandleFunc(pattern string, h func(http.ResponseWriter, *http.Request, *c.User) c.RouteError) {
|
||||||
r.Lock()
|
r.Lock()
|
||||||
defer r.Unlock()
|
defer r.Unlock()
|
||||||
r.extraRoutes[pattern] = h
|
r.extraRoutes[pattern] = h
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *GenRouter) RemoveFunc(pattern string) error {
|
func (r *GenRouter) RemoveFunc(pattern string) error {
|
||||||
r.Lock()
|
r.Lock()
|
||||||
defer r.Unlock()
|
defer r.Unlock()
|
||||||
_, ok := r.extraRoutes[pattern]
|
_, ok := r.extraRoutes[pattern]
|
||||||
if !ok {
|
if !ok {
|
||||||
return ErrNoRoute
|
return ErrNoRoute
|
||||||
}
|
}
|
||||||
delete(r.extraRoutes, pattern)
|
delete(r.extraRoutes, pattern)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *GenRouter) dumpRequest(req *http.Request, pre string, log *RouterLog) {
|
func (r *GenRouter) dumpRequest(req *http.Request, pre string, log *RouterLog) {
|
||||||
var sb strings.Builder
|
var sb strings.Builder
|
||||||
r.ddumpRequest(req, pre, log, &sb)
|
r.ddumpRequest(req, pre, log, &sb)
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Some of these sanitisations may be redundant
|
// TODO: Some of these sanitisations may be redundant
|
||||||
|
@ -217,115 +217,115 @@ var dumpReqLen = len("\nUA: \n Host: \nIP: \n") + 7
|
||||||
var dumpReqLen2 = len("\nHead : ") + 2
|
var dumpReqLen2 = len("\nHead : ") + 2
|
||||||
|
|
||||||
func (r *GenRouter) ddumpRequest(req *http.Request, pre string, l *RouterLog, sb *strings.Builder) {
|
func (r *GenRouter) ddumpRequest(req *http.Request, pre string, l *RouterLog, sb *strings.Builder) {
|
||||||
nfield := func(label, val string) {
|
nfield := func(label, val string) {
|
||||||
sb.WriteString(label)
|
sb.WriteString(label)
|
||||||
sb.WriteString(val)
|
sb.WriteString(val)
|
||||||
}
|
}
|
||||||
field := func(label, val string) {
|
field := func(label, val string) {
|
||||||
nfield(label, c.SanitiseSingleLine(val))
|
nfield(label, c.SanitiseSingleLine(val))
|
||||||
}
|
}
|
||||||
ua := req.UserAgent()
|
ua := req.UserAgent()
|
||||||
|
|
||||||
sb.Grow(dumpReqLen + len(pre) + len(ua) + len(req.Method) + len(req.Host) + (dumpReqLen2 * len(req.Header)))
|
sb.Grow(dumpReqLen + len(pre) + len(ua) + len(req.Method) + len(req.Host) + (dumpReqLen2 * len(req.Header)))
|
||||||
sb.WriteString(pre)
|
sb.WriteString(pre)
|
||||||
sb.WriteString("\n")
|
sb.WriteString("\n")
|
||||||
sb.WriteString(c.SanitiseSingleLine(req.Method))
|
sb.WriteString(c.SanitiseSingleLine(req.Method))
|
||||||
sb.WriteRune(' ')
|
sb.WriteRune(' ')
|
||||||
sb.WriteString(c.SanitiseSingleLine(req.URL.Path))
|
sb.WriteString(c.SanitiseSingleLine(req.URL.Path))
|
||||||
field("\nUA: ", ua)
|
field("\nUA: ", ua)
|
||||||
|
|
||||||
for key, val := range req.Header {
|
for key, val := range req.Header {
|
||||||
// Avoid logging this for security reasons
|
// Avoid logging this for security reasons
|
||||||
if key == "Cookie" {
|
if key == "Cookie" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
for _, vvalue := range val {
|
for _, vvalue := range val {
|
||||||
sb.WriteString("\nHead ")
|
sb.WriteString("\nHead ")
|
||||||
sb.WriteString(c.SanitiseSingleLine(key))
|
sb.WriteString(c.SanitiseSingleLine(key))
|
||||||
sb.WriteString(": ")
|
sb.WriteString(": ")
|
||||||
sb.WriteString(c.SanitiseSingleLine(vvalue))
|
sb.WriteString(c.SanitiseSingleLine(vvalue))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
field("\nHost: ", req.Host)
|
field("\nHost: ", req.Host)
|
||||||
if rawQuery := req.URL.RawQuery; rawQuery != "" {
|
if rawQuery := req.URL.RawQuery; rawQuery != "" {
|
||||||
field("\nURL.RawQuery: ", rawQuery)
|
field("\nURL.RawQuery: ", rawQuery)
|
||||||
}
|
}
|
||||||
if ref := req.Referer(); ref != "" {
|
if ref := req.Referer(); ref != "" {
|
||||||
field("\nRef: ", ref)
|
field("\nRef: ", ref)
|
||||||
}
|
}
|
||||||
nfield("\nIP: ", req.RemoteAddr)
|
nfield("\nIP: ", req.RemoteAddr)
|
||||||
sb.WriteString("\n")
|
sb.WriteString("\n")
|
||||||
|
|
||||||
str := sb.String()
|
str := sb.String()
|
||||||
l.RLock()
|
l.RLock()
|
||||||
l.LogVal.Load().(*log.Logger).Print(str)
|
l.LogVal.Load().(*log.Logger).Print(str)
|
||||||
l.RUnlock()
|
l.RUnlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *GenRouter) DumpRequest(req *http.Request, pre string) {
|
func (r *GenRouter) DumpRequest(req *http.Request, pre string) {
|
||||||
r.dumpRequest(req, pre, r.reqLog2)
|
r.dumpRequest(req, pre, r.reqLog2)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *GenRouter) unknownUA(req *http.Request) {
|
func (r *GenRouter) unknownUA(req *http.Request) {
|
||||||
if c.Dev.DebugMode {
|
if c.Dev.DebugMode {
|
||||||
var presb strings.Builder
|
var presb strings.Builder
|
||||||
presb.WriteString("Unknown UA: ")
|
presb.WriteString("Unknown UA: ")
|
||||||
for _, ch := range req.UserAgent() {
|
for _, ch := range req.UserAgent() {
|
||||||
presb.WriteString(strconv.Itoa(int(ch)))
|
presb.WriteString(strconv.Itoa(int(ch)))
|
||||||
presb.WriteRune(' ')
|
presb.WriteRune(' ')
|
||||||
}
|
}
|
||||||
r.ddumpRequest(req, "", r.reqLog2, &presb)
|
r.ddumpRequest(req, "", r.reqLog2, &presb)
|
||||||
} else {
|
} else {
|
||||||
r.reqLogger.Print("unknown ua: ", c.SanitiseSingleLine(req.UserAgent()))
|
r.reqLogger.Print("unknown ua: ", c.SanitiseSingleLine(req.UserAgent()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *GenRouter) susp1(req *http.Request) bool {
|
func (r *GenRouter) susp1(req *http.Request) bool {
|
||||||
if !strings.Contains(req.URL.Path, ".") {
|
if !strings.Contains(req.URL.Path, ".") {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if strings.Contains(req.URL.Path, "..") /* || strings.Contains(req.URL.Path,"--")*/ {
|
if strings.Contains(req.URL.Path, "..") /* || strings.Contains(req.URL.Path,"--")*/ {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
lp := strings.ToLower(req.URL.Path)
|
lp := strings.ToLower(req.URL.Path)
|
||||||
// TODO: Flag any requests which has a dot with anything but a number after that
|
// TODO: Flag any requests which has a dot with anything but a number after that
|
||||||
// TODO: Use HasSuffix to avoid over-scanning?
|
// TODO: Use HasSuffix to avoid over-scanning?
|
||||||
return strings.Contains(lp, ".php") || strings.Contains(lp, ".asp") || strings.Contains(lp, ".cgi") || strings.Contains(lp, ".py") || strings.Contains(lp, ".sql") || strings.Contains(lp, ".act") //.action
|
return strings.Contains(lp, ".php") || strings.Contains(lp, ".asp") || strings.Contains(lp, ".cgi") || strings.Contains(lp, ".py") || strings.Contains(lp, ".sql") || strings.Contains(lp, ".act") //.action
|
||||||
}
|
}
|
||||||
|
|
||||||
func (r *GenRouter) suspScan(req *http.Request) {
|
func (r *GenRouter) suspScan(req *http.Request) {
|
||||||
if c.Config.DisableSuspLog {
|
if c.Config.DisableSuspLog {
|
||||||
if c.Dev.FullReqLog {
|
if c.Dev.FullReqLog {
|
||||||
r.DumpRequest(req, "")
|
r.DumpRequest(req, "")
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Cover more suspicious strings and at a lower layer than this
|
// TODO: Cover more suspicious strings and at a lower layer than this
|
||||||
var ch rune
|
var ch rune
|
||||||
var susp bool
|
var susp bool
|
||||||
for _, ch = range req.URL.Path { //char
|
for _, ch = range req.URL.Path { //char
|
||||||
if ch != '&' && !(ch > 44 && ch < 58) && ch != '=' && ch != '?' && !(ch > 64 && ch < 91) && ch != '\\' && ch != '_' && !(ch > 96 && ch < 123) {
|
if ch != '&' && !(ch > 44 && ch < 58) && ch != '=' && ch != '?' && !(ch > 64 && ch < 91) && ch != '\\' && ch != '_' && !(ch > 96 && ch < 123) {
|
||||||
susp = true
|
susp = true
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Avoid logging the same request multiple times
|
// Avoid logging the same request multiple times
|
||||||
susp2 := r.susp1(req)
|
susp2 := r.susp1(req)
|
||||||
if susp && susp2 {
|
if susp && susp2 {
|
||||||
r.SuspiciousRequest(req, "Bad char '"+string(ch)+"' in path\nBad snippet in path")
|
r.SuspiciousRequest(req, "Bad char '"+string(ch)+"' in path\nBad snippet in path")
|
||||||
} else if susp {
|
} else if susp {
|
||||||
r.SuspiciousRequest(req, "Bad char '"+string(ch)+"' in path")
|
r.SuspiciousRequest(req, "Bad char '"+string(ch)+"' in path")
|
||||||
} else if susp2 {
|
} else if susp2 {
|
||||||
r.SuspiciousRequest(req, "Bad snippet in path")
|
r.SuspiciousRequest(req, "Bad snippet in path")
|
||||||
} else if c.Dev.FullReqLog {
|
} else if c.Dev.FullReqLog {
|
||||||
r.DumpRequest(req, "")
|
r.DumpRequest(req, "")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func isLocalHost(h string) bool {
|
func isLocalHost(h string) bool {
|
||||||
return h == "localhost" || h == "127.0.0.1" || h == "::1"
|
return h == "localhost" || h == "127.0.0.1" || h == "::1"
|
||||||
}
|
}
|
||||||
|
|
||||||
//var brPool = sync.Pool{}
|
//var brPool = sync.Pool{}
|
||||||
|
@ -334,12 +334,12 @@ var gzipPool = sync.Pool{}
|
||||||
//var uaBufPool = sync.Pool{}
|
//var uaBufPool = sync.Pool{}
|
||||||
|
|
||||||
func (r *GenRouter) responseWriter(w http.ResponseWriter) http.ResponseWriter {
|
func (r *GenRouter) responseWriter(w http.ResponseWriter) http.ResponseWriter {
|
||||||
/*if bzw, ok := w.(c.BrResponseWriter); ok {
|
/*if bzw, ok := w.(c.BrResponseWriter); ok {
|
||||||
w = bzw.ResponseWriter
|
w = bzw.ResponseWriter
|
||||||
w.Header().Del("Content-Encoding")
|
w.Header().Del("Content-Encoding")
|
||||||
} else */if gzw, ok := w.(c.GzipResponseWriter); ok {
|
} else */if gzw, ok := w.(c.GzipResponseWriter); ok {
|
||||||
w = gzw.ResponseWriter
|
w = gzw.ResponseWriter
|
||||||
w.Header().Del("Content-Encoding")
|
w.Header().Del("Content-Encoding")
|
||||||
}
|
}
|
||||||
return w
|
return w
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,96 +0,0 @@
|
||||||
@echo off
|
|
||||||
rem TODO: Make these deletes a little less noisy
|
|
||||||
del "template_*.go"
|
|
||||||
del "tmpl_*.go"
|
|
||||||
del "gen_*.go"
|
|
||||||
del ".\tmpl_client\template_*"
|
|
||||||
del ".\tmpl_client\tmpl_*"
|
|
||||||
del ".\common\gen_extend.go"
|
|
||||||
del "gosora.exe"
|
|
||||||
|
|
||||||
echo Generating the dynamic code
|
|
||||||
go generate
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the router generator
|
|
||||||
go build -ldflags="-s -w" ./router_gen
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the router generator
|
|
||||||
router_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the hook stub generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the hook stub generator
|
|
||||||
hook_stub_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Generating the JSON handlers
|
|
||||||
easyjson -pkg common
|
|
||||||
|
|
||||||
echo Building the hook generator
|
|
||||||
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the hook generator
|
|
||||||
hook_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the query generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/query_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the query generator
|
|
||||||
query_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the executable
|
|
||||||
go build -ldflags="-s -w" -o gosora.exe -tags no_ws
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the templates
|
|
||||||
gosora.exe -build-templates
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the executable... again
|
|
||||||
go build -ldflags="-s -w" -o gosora.exe -tags no_ws
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Running Gosora
|
|
||||||
gosora.exe
|
|
||||||
pause
|
|
98
run.bat
98
run.bat
|
@ -1,98 +0,0 @@
|
||||||
@echo off
|
|
||||||
rem TODO: Make these deletes a little less noisy
|
|
||||||
del "template_*.go"
|
|
||||||
del "tmpl_*.go"
|
|
||||||
del "gen_*.go"
|
|
||||||
del ".\tmpl_client\template_*"
|
|
||||||
del ".\tmpl_client\tmpl_*"
|
|
||||||
del ".\common\gen_extend.go"
|
|
||||||
del "gosora.exe"
|
|
||||||
|
|
||||||
echo Generating the dynamic code
|
|
||||||
go generate
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the router generator
|
|
||||||
go build -ldflags="-s -w" ./router_gen
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the router generator
|
|
||||||
router_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the hook stub generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the hook stub generator
|
|
||||||
hook_stub_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Generating the JSON handlers
|
|
||||||
easyjson -pkg common
|
|
||||||
|
|
||||||
echo Building the hook generator
|
|
||||||
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the hook generator
|
|
||||||
hook_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the query generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/query_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the query generator
|
|
||||||
query_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the executable
|
|
||||||
go build -ldflags="-s -w" -o gosora.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the templates
|
|
||||||
gosora.exe -build-templates
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the executable... again
|
|
||||||
go build -ldflags="-s -w" -gcflags="-d=ssa/check_bce/debug=1" -o gosora.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Running Gosora
|
|
||||||
gosora.exe
|
|
||||||
rem Or you could redirect the output to a file
|
|
||||||
rem gosora.exe > ./logs/ops.log 2>&1
|
|
||||||
pause
|
|
|
@ -1,96 +0,0 @@
|
||||||
@echo off
|
|
||||||
rem TODO: Make these deletes a little less noisy
|
|
||||||
del "template_*.go"
|
|
||||||
del "tmpl_*.go"
|
|
||||||
del "gen_*.go"
|
|
||||||
del ".\tmpl_client\template_*"
|
|
||||||
del ".\tmpl_client\tmpl_*"
|
|
||||||
del ".\common\gen_extend.go"
|
|
||||||
del "gosora.exe"
|
|
||||||
|
|
||||||
echo Generating the dynamic code
|
|
||||||
go generate
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the router generator
|
|
||||||
go build -ldflags="-s -w" ./router_gen
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the router generator
|
|
||||||
router_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the hook stub generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the hook stub generator
|
|
||||||
hook_stub_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Generating the JSON handlers
|
|
||||||
easyjson -pkg common
|
|
||||||
|
|
||||||
echo Building the hook generator
|
|
||||||
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the hook generator
|
|
||||||
hook_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the query generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/query_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the query generator
|
|
||||||
query_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the executable
|
|
||||||
go build -ldflags="-s -w" -o gosora.exe -tags mssql
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the templates
|
|
||||||
gosora.exe -build-templates
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the executable... again
|
|
||||||
go build -ldflags="-s -w" -o gosora.exe -tags mssql
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Running Gosora
|
|
||||||
gosora.exe
|
|
||||||
pause
|
|
|
@ -1,79 +0,0 @@
|
||||||
@echo off
|
|
||||||
rem TODO: Make these deletes a little less noisy
|
|
||||||
del "template_*.go"
|
|
||||||
del "tmpl_*.go"
|
|
||||||
del "gen_*.go"
|
|
||||||
del ".\tmpl_client\template_*"
|
|
||||||
del ".\tmpl_client\tmpl_*"
|
|
||||||
del ".\common\gen_extend.go"
|
|
||||||
del "gosora.exe"
|
|
||||||
|
|
||||||
echo Generating the dynamic code
|
|
||||||
go generate
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the router generator
|
|
||||||
go build -ldflags="-s -w" ./router_gen
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the router generator
|
|
||||||
router_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the hook stub generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the hook stub generator
|
|
||||||
hook_stub_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Generating the JSON handlers
|
|
||||||
easyjson -pkg common
|
|
||||||
|
|
||||||
echo Building the hook generator
|
|
||||||
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the hook generator
|
|
||||||
hook_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the query generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/query_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the query generator
|
|
||||||
query_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the executable
|
|
||||||
go test
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
pause
|
|
|
@ -1,79 +0,0 @@
|
||||||
@echo off
|
|
||||||
rem TODO: Make these deletes a little less noisy
|
|
||||||
del "template_*.go"
|
|
||||||
del "tmpl_*.go"
|
|
||||||
del "gen_*.go"
|
|
||||||
del ".\tmpl_client\template_*"
|
|
||||||
del ".\tmpl_client\tmpl_*"
|
|
||||||
del ".\common\gen_extend.go"
|
|
||||||
del "gosora.exe"
|
|
||||||
|
|
||||||
echo Generating the dynamic code
|
|
||||||
go generate
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the router generator
|
|
||||||
go build -ldflags="-s -w" ./router_gen
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the router generator
|
|
||||||
router_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the hook stub generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/hook_stub_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the hook stub generator
|
|
||||||
hook_stub_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Generating the JSON handlers
|
|
||||||
easyjson -pkg common
|
|
||||||
|
|
||||||
echo Building the hook generator
|
|
||||||
go build -tags hookgen -ldflags="-s -w" "./cmd/hook_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the hook generator
|
|
||||||
hook_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the query generator
|
|
||||||
go build -ldflags="-s -w" "./cmd/query_gen"
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
echo Running the query generator
|
|
||||||
query_gen.exe
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
|
|
||||||
echo Building the executable
|
|
||||||
go test -tags mssql
|
|
||||||
if %errorlevel% neq 0 (
|
|
||||||
pause
|
|
||||||
exit /b %errorlevel%
|
|
||||||
)
|
|
||||||
pause
|
|
|
@ -1,11 +1,11 @@
|
||||||
CREATE TABLE [activity_stream] (
|
CREATE TABLE [activity_stream] (
|
||||||
[asid] int not null IDENTITY,
|
[asid] int not null IDENTITY,
|
||||||
[actor] int not null,
|
[actor] int not null,
|
||||||
[targetUser] int not null,
|
[targetUser] int not null,
|
||||||
[event] nvarchar (50) not null,
|
[event] nvarchar (50) not null,
|
||||||
[elementType] nvarchar (50) not null,
|
[elementType] nvarchar (50) not null,
|
||||||
[elementID] int not null,
|
[elementID] int not null,
|
||||||
[createdAt] datetime not null,
|
[createdAt] datetime not null,
|
||||||
[extra] nvarchar (200) DEFAULT '' not null,
|
[extra] nvarchar (200) DEFAULT '' not null,
|
||||||
primary key([asid])
|
primary key([asid])
|
||||||
);
|
);
|
|
@ -1,5 +1,5 @@
|
||||||
CREATE TABLE [activity_stream_matches] (
|
CREATE TABLE [activity_stream_matches] (
|
||||||
[watcher] int not null,
|
[watcher] int not null,
|
||||||
[asid] int not null,
|
[asid] int not null,
|
||||||
foreign key([asid],[asid])
|
foreign key([asid],[asid])
|
||||||
);
|
);
|
|
@ -1,6 +1,6 @@
|
||||||
CREATE TABLE [activity_subscriptions] (
|
CREATE TABLE [activity_subscriptions] (
|
||||||
[user] int not null,
|
[user] int not null,
|
||||||
[targetID] int not null,
|
[targetID] int not null,
|
||||||
[targetType] nvarchar (50) not null,
|
[targetType] nvarchar (50) not null,
|
||||||
[level] int DEFAULT 0 not null
|
[level] int DEFAULT 0 not null
|
||||||
);
|
);
|
|
@ -1,9 +1,9 @@
|
||||||
CREATE TABLE [administration_logs] (
|
CREATE TABLE [administration_logs] (
|
||||||
[action] nvarchar (100) not null,
|
[action] nvarchar (100) not null,
|
||||||
[elementID] int not null,
|
[elementID] int not null,
|
||||||
[elementType] nvarchar (100) not null,
|
[elementType] nvarchar (100) not null,
|
||||||
[ipaddress] nvarchar (200) not null,
|
[ipaddress] nvarchar (200) not null,
|
||||||
[actorID] int not null,
|
[actorID] int not null,
|
||||||
[doneAt] datetime not null,
|
[doneAt] datetime not null,
|
||||||
[extra] nvarchar (MAX) not null
|
[extra] nvarchar (MAX) not null
|
||||||
);
|
);
|
|
@ -1,11 +1,11 @@
|
||||||
CREATE TABLE [attachments] (
|
CREATE TABLE [attachments] (
|
||||||
[attachID] int not null IDENTITY,
|
[attachID] int not null IDENTITY,
|
||||||
[sectionID] int DEFAULT 0 not null,
|
[sectionID] int DEFAULT 0 not null,
|
||||||
[sectionTable] nvarchar (200) DEFAULT 'forums' not null,
|
[sectionTable] nvarchar (200) DEFAULT 'forums' not null,
|
||||||
[originID] int not null,
|
[originID] int not null,
|
||||||
[originTable] nvarchar (200) DEFAULT 'replies' not null,
|
[originTable] nvarchar (200) DEFAULT 'replies' not null,
|
||||||
[uploadedBy] int not null,
|
[uploadedBy] int not null,
|
||||||
[path] nvarchar (200) not null,
|
[path] nvarchar (200) not null,
|
||||||
[extra] nvarchar (200) not null,
|
[extra] nvarchar (200) not null,
|
||||||
primary key([attachID])
|
primary key([attachID])
|
||||||
);
|
);
|
|
@ -1,8 +1,8 @@
|
||||||
CREATE TABLE [conversations] (
|
CREATE TABLE [conversations] (
|
||||||
[cid] int not null IDENTITY,
|
[cid] int not null IDENTITY,
|
||||||
[createdBy] int not null,
|
[createdBy] int not null,
|
||||||
[createdAt] datetime not null,
|
[createdAt] datetime not null,
|
||||||
[lastReplyAt] datetime not null,
|
[lastReplyAt] datetime not null,
|
||||||
[lastReplyBy] int not null,
|
[lastReplyBy] int not null,
|
||||||
primary key([cid])
|
primary key([cid])
|
||||||
);
|
);
|
|
@ -1,4 +1,4 @@
|
||||||
CREATE TABLE [conversations_participants] (
|
CREATE TABLE [conversations_participants] (
|
||||||
[uid] int not null,
|
[uid] int not null,
|
||||||
[cid] int not null
|
[cid] int not null
|
||||||
);
|
);
|
|
@ -1,8 +1,8 @@
|
||||||
CREATE TABLE [conversations_posts] (
|
CREATE TABLE [conversations_posts] (
|
||||||
[pid] int not null IDENTITY,
|
[pid] int not null IDENTITY,
|
||||||
[cid] int not null,
|
[cid] int not null,
|
||||||
[createdBy] int not null,
|
[createdBy] int not null,
|
||||||
[body] nvarchar (50) not null,
|
[body] nvarchar (50) not null,
|
||||||
[post] nvarchar (50) DEFAULT '' not null,
|
[post] nvarchar (50) DEFAULT '' not null,
|
||||||
primary key([pid])
|
primary key([pid])
|
||||||
);
|
);
|
|
@ -1,6 +1,6 @@
|
||||||
CREATE TABLE [emails] (
|
CREATE TABLE [emails] (
|
||||||
[email] nvarchar (200) not null,
|
[email] nvarchar (200) not null,
|
||||||
[uid] int not null,
|
[uid] int not null,
|
||||||
[validated] bit DEFAULT 0 not null,
|
[validated] bit DEFAULT 0 not null,
|
||||||
[token] nvarchar (200) DEFAULT '' not null
|
[token] nvarchar (200) DEFAULT '' not null
|
||||||
);
|
);
|
|
@ -1,15 +1,15 @@
|
||||||
CREATE TABLE [forums] (
|
CREATE TABLE [forums] (
|
||||||
[fid] int not null IDENTITY,
|
[fid] int not null IDENTITY,
|
||||||
[name] nvarchar (100) not null,
|
[name] nvarchar (100) not null,
|
||||||
[desc] nvarchar (200) not null,
|
[desc] nvarchar (200) not null,
|
||||||
[tmpl] nvarchar (200) DEFAULT '' not null,
|
[tmpl] nvarchar (200) DEFAULT '' not null,
|
||||||
[active] bit DEFAULT 1 not null,
|
[active] bit DEFAULT 1 not null,
|
||||||
[order] int DEFAULT 0 not null,
|
[order] int DEFAULT 0 not null,
|
||||||
[topicCount] int DEFAULT 0 not null,
|
[topicCount] int DEFAULT 0 not null,
|
||||||
[preset] nvarchar (100) DEFAULT '' not null,
|
[preset] nvarchar (100) DEFAULT '' not null,
|
||||||
[parentID] int DEFAULT 0 not null,
|
[parentID] int DEFAULT 0 not null,
|
||||||
[parentType] nvarchar (50) DEFAULT '' not null,
|
[parentType] nvarchar (50) DEFAULT '' not null,
|
||||||
[lastTopicID] int DEFAULT 0 not null,
|
[lastTopicID] int DEFAULT 0 not null,
|
||||||
[lastReplyerID] int DEFAULT 0 not null,
|
[lastReplyerID] int DEFAULT 0 not null,
|
||||||
primary key([fid])
|
primary key([fid])
|
||||||
);
|
);
|
|
@ -1,10 +1,10 @@
|
||||||
CREATE TABLE [forums_actions] (
|
CREATE TABLE [forums_actions] (
|
||||||
[faid] int not null IDENTITY,
|
[faid] int not null IDENTITY,
|
||||||
[fid] int not null,
|
[fid] int not null,
|
||||||
[runOnTopicCreation] bit DEFAULT 0 not null,
|
[runOnTopicCreation] bit DEFAULT 0 not null,
|
||||||
[runDaysAfterTopicCreation] int DEFAULT 0 not null,
|
[runDaysAfterTopicCreation] int DEFAULT 0 not null,
|
||||||
[runDaysAfterTopicLastReply] int DEFAULT 0 not null,
|
[runDaysAfterTopicLastReply] int DEFAULT 0 not null,
|
||||||
[action] nvarchar (50) not null,
|
[action] nvarchar (50) not null,
|
||||||
[extra] nvarchar (200) DEFAULT '' not null,
|
[extra] nvarchar (200) DEFAULT '' not null,
|
||||||
primary key([faid])
|
primary key([faid])
|
||||||
);
|
);
|
|
@ -1,7 +1,7 @@
|
||||||
CREATE TABLE [forums_permissions] (
|
CREATE TABLE [forums_permissions] (
|
||||||
[fid] int not null,
|
[fid] int not null,
|
||||||
[gid] int not null,
|
[gid] int not null,
|
||||||
[preset] nvarchar (100) DEFAULT '' not null,
|
[preset] nvarchar (100) DEFAULT '' not null,
|
||||||
[permissions] nvarchar (MAX) not null,
|
[permissions] nvarchar (MAX) not null,
|
||||||
primary key([fid],[gid])
|
primary key([fid],[gid])
|
||||||
);
|
);
|
|
@ -1,8 +1,8 @@
|
||||||
CREATE TABLE [likes] (
|
CREATE TABLE [likes] (
|
||||||
[weight] tinyint DEFAULT 1 not null,
|
[weight] tinyint DEFAULT 1 not null,
|
||||||
[targetItem] int not null,
|
[targetItem] int not null,
|
||||||
[targetType] nvarchar (50) DEFAULT 'replies' not null,
|
[targetType] nvarchar (50) DEFAULT 'replies' not null,
|
||||||
[sentBy] int not null,
|
[sentBy] int not null,
|
||||||
[createdAt] datetime not null,
|
[createdAt] datetime not null,
|
||||||
[recalc] tinyint DEFAULT 0 not null
|
[recalc] tinyint DEFAULT 0 not null
|
||||||
);
|
);
|
|
@ -1,8 +1,8 @@
|
||||||
CREATE TABLE [login_logs] (
|
CREATE TABLE [login_logs] (
|
||||||
[lid] int not null IDENTITY,
|
[lid] int not null IDENTITY,
|
||||||
[uid] int not null,
|
[uid] int not null,
|
||||||
[success] bool DEFAULT 0 not null,
|
[success] bool DEFAULT 0 not null,
|
||||||
[ipaddress] nvarchar (200) not null,
|
[ipaddress] nvarchar (200) not null,
|
||||||
[doneAt] datetime not null,
|
[doneAt] datetime not null,
|
||||||
primary key([lid])
|
primary key([lid])
|
||||||
);
|
);
|
|
@ -1,6 +1,6 @@
|
||||||
CREATE TABLE [memchunks] (
|
CREATE TABLE [memchunks] (
|
||||||
[count] int DEFAULT 0 not null,
|
[count] int DEFAULT 0 not null,
|
||||||
[stack] int DEFAULT 0 not null,
|
[stack] int DEFAULT 0 not null,
|
||||||
[heap] int DEFAULT 0 not null,
|
[heap] int DEFAULT 0 not null,
|
||||||
[createdAt] datetime not null
|
[createdAt] datetime not null
|
||||||
);
|
);
|
|
@ -1,18 +1,18 @@
|
||||||
CREATE TABLE [menu_items] (
|
CREATE TABLE [menu_items] (
|
||||||
[miid] int not null IDENTITY,
|
[miid] int not null IDENTITY,
|
||||||
[mid] int not null,
|
[mid] int not null,
|
||||||
[name] nvarchar (200) DEFAULT '' not null,
|
[name] nvarchar (200) DEFAULT '' not null,
|
||||||
[htmlID] nvarchar (200) DEFAULT '' not null,
|
[htmlID] nvarchar (200) DEFAULT '' not null,
|
||||||
[cssClass] nvarchar (200) DEFAULT '' not null,
|
[cssClass] nvarchar (200) DEFAULT '' not null,
|
||||||
[position] nvarchar (100) not null,
|
[position] nvarchar (100) not null,
|
||||||
[path] nvarchar (200) DEFAULT '' not null,
|
[path] nvarchar (200) DEFAULT '' not null,
|
||||||
[aria] nvarchar (200) DEFAULT '' not null,
|
[aria] nvarchar (200) DEFAULT '' not null,
|
||||||
[tooltip] nvarchar (200) DEFAULT '' not null,
|
[tooltip] nvarchar (200) DEFAULT '' not null,
|
||||||
[tmplName] nvarchar (200) DEFAULT '' not null,
|
[tmplName] nvarchar (200) DEFAULT '' not null,
|
||||||
[order] int DEFAULT 0 not null,
|
[order] int DEFAULT 0 not null,
|
||||||
[guestOnly] bit DEFAULT 0 not null,
|
[guestOnly] bit DEFAULT 0 not null,
|
||||||
[memberOnly] bit DEFAULT 0 not null,
|
[memberOnly] bit DEFAULT 0 not null,
|
||||||
[staffOnly] bit DEFAULT 0 not null,
|
[staffOnly] bit DEFAULT 0 not null,
|
||||||
[adminOnly] bit DEFAULT 0 not null,
|
[adminOnly] bit DEFAULT 0 not null,
|
||||||
primary key([miid])
|
primary key([miid])
|
||||||
);
|
);
|
|
@ -1,4 +1,4 @@
|
||||||
CREATE TABLE [menus] (
|
CREATE TABLE [menus] (
|
||||||
[mid] int not null IDENTITY,
|
[mid] int not null IDENTITY,
|
||||||
primary key([mid])
|
primary key([mid])
|
||||||
);
|
);
|
|
@ -1,4 +1,4 @@
|
||||||
CREATE TABLE [meta] (
|
CREATE TABLE [meta] (
|
||||||
[name] nvarchar (200) not null,
|
[name] nvarchar (200) not null,
|
||||||
[value] nvarchar (200) not null
|
[value] nvarchar (200) not null
|
||||||
);
|
);
|
|
@ -1,9 +1,9 @@
|
||||||
CREATE TABLE [moderation_logs] (
|
CREATE TABLE [moderation_logs] (
|
||||||
[action] nvarchar (100) not null,
|
[action] nvarchar (100) not null,
|
||||||
[elementID] int not null,
|
[elementID] int not null,
|
||||||
[elementType] nvarchar (100) not null,
|
[elementType] nvarchar (100) not null,
|
||||||
[ipaddress] nvarchar (200) not null,
|
[ipaddress] nvarchar (200) not null,
|
||||||
[actorID] int not null,
|
[actorID] int not null,
|
||||||
[doneAt] datetime not null,
|
[doneAt] datetime not null,
|
||||||
[extra] nvarchar (MAX) not null
|
[extra] nvarchar (MAX) not null
|
||||||
);
|
);
|
|
@ -1,9 +1,9 @@
|
||||||
CREATE TABLE [pages] (
|
CREATE TABLE [pages] (
|
||||||
[pid] int not null IDENTITY,
|
[pid] int not null IDENTITY,
|
||||||
[name] nvarchar (200) not null,
|
[name] nvarchar (200) not null,
|
||||||
[title] nvarchar (200) not null,
|
[title] nvarchar (200) not null,
|
||||||
[body] nvarchar (MAX) not null,
|
[body] nvarchar (MAX) not null,
|
||||||
[allowedGroups] nvarchar (MAX) not null,
|
[allowedGroups] nvarchar (MAX) not null,
|
||||||
[menuID] int DEFAULT -1 not null,
|
[menuID] int DEFAULT -1 not null,
|
||||||
primary key([pid])
|
primary key([pid])
|
||||||
);
|
);
|
|
@ -1,7 +1,7 @@
|
||||||
CREATE TABLE [password_resets] (
|
CREATE TABLE [password_resets] (
|
||||||
[email] nvarchar (200) not null,
|
[email] nvarchar (200) not null,
|
||||||
[uid] int not null,
|
[uid] int not null,
|
||||||
[validated] nvarchar (200) not null,
|
[validated] nvarchar (200) not null,
|
||||||
[token] nvarchar (200) not null,
|
[token] nvarchar (200) not null,
|
||||||
[createdAt] datetime not null
|
[createdAt] datetime not null
|
||||||
);
|
);
|
|
@ -1,6 +1,6 @@
|
||||||
CREATE TABLE [perfchunks] (
|
CREATE TABLE [perfchunks] (
|
||||||
[low] int DEFAULT 0 not null,
|
[low] int DEFAULT 0 not null,
|
||||||
[high] int DEFAULT 0 not null,
|
[high] int DEFAULT 0 not null,
|
||||||
[avg] int DEFAULT 0 not null,
|
[avg] int DEFAULT 0 not null,
|
||||||
[createdAt] datetime not null
|
[createdAt] datetime not null
|
||||||
);
|
);
|
|
@ -1,6 +1,6 @@
|
||||||
CREATE TABLE [plugins] (
|
CREATE TABLE [plugins] (
|
||||||
[uname] nvarchar (180) not null,
|
[uname] nvarchar (180) not null,
|
||||||
[active] bit DEFAULT 0 not null,
|
[active] bit DEFAULT 0 not null,
|
||||||
[installed] bit DEFAULT 0 not null,
|
[installed] bit DEFAULT 0 not null,
|
||||||
unique([uname])
|
unique([uname])
|
||||||
);
|
);
|
|
@ -1,9 +1,9 @@
|
||||||
CREATE TABLE [polls] (
|
CREATE TABLE [polls] (
|
||||||
[pollID] int not null IDENTITY,
|
[pollID] int not null IDENTITY,
|
||||||
[parentID] int DEFAULT 0 not null,
|
[parentID] int DEFAULT 0 not null,
|
||||||
[parentTable] nvarchar (100) DEFAULT 'topics' not null,
|
[parentTable] nvarchar (100) DEFAULT 'topics' not null,
|
||||||
[type] int DEFAULT 0 not null,
|
[type] int DEFAULT 0 not null,
|
||||||
[options] nvarchar (MAX) not null,
|
[options] nvarchar (MAX) not null,
|
||||||
[votes] int DEFAULT 0 not null,
|
[votes] int DEFAULT 0 not null,
|
||||||
primary key([pollID])
|
primary key([pollID])
|
||||||
);
|
);
|
|
@ -1,5 +1,5 @@
|
||||||
CREATE TABLE [polls_options] (
|
CREATE TABLE [polls_options] (
|
||||||
[pollID] int not null,
|
[pollID] int not null,
|
||||||
[option] int DEFAULT 0 not null,
|
[option] int DEFAULT 0 not null,
|
||||||
[votes] int DEFAULT 0 not null
|
[votes] int DEFAULT 0 not null
|
||||||
);
|
);
|
|
@ -1,5 +1,5 @@
|
||||||
CREATE TABLE [polls_voters] (
|
CREATE TABLE [polls_voters] (
|
||||||
[pollID] int not null,
|
[pollID] int not null,
|
||||||
[uid] int not null,
|
[uid] int not null,
|
||||||
[option] int DEFAULT 0 not null
|
[option] int DEFAULT 0 not null
|
||||||
);
|
);
|
|
@ -1,7 +1,7 @@
|
||||||
CREATE TABLE [polls_votes] (
|
CREATE TABLE [polls_votes] (
|
||||||
[pollID] int not null,
|
[pollID] int not null,
|
||||||
[uid] int not null,
|
[uid] int not null,
|
||||||
[option] int DEFAULT 0 not null,
|
[option] int DEFAULT 0 not null,
|
||||||
[castAt] datetime not null,
|
[castAt] datetime not null,
|
||||||
[ip] nvarchar (200) DEFAULT '' not null
|
[ip] nvarchar (200) DEFAULT '' not null
|
||||||
);
|
);
|
|
@ -1,4 +1,4 @@
|
||||||
CREATE TABLE [postchunks] (
|
CREATE TABLE [postchunks] (
|
||||||
[count] int DEFAULT 0 not null,
|
[count] int DEFAULT 0 not null,
|
||||||
[createdAt] datetime not null
|
[createdAt] datetime not null
|
||||||
);
|
);
|
|
@ -1,10 +1,10 @@
|
||||||
CREATE TABLE [registration_logs] (
|
CREATE TABLE [registration_logs] (
|
||||||
[rlid] int not null IDENTITY,
|
[rlid] int not null IDENTITY,
|
||||||
[username] nvarchar (100) not null,
|
[username] nvarchar (100) not null,
|
||||||
[email] nvarchar (100) not null,
|
[email] nvarchar (100) not null,
|
||||||
[failureReason] nvarchar (100) not null,
|
[failureReason] nvarchar (100) not null,
|
||||||
[success] bool DEFAULT 0 not null,
|
[success] bool DEFAULT 0 not null,
|
||||||
[ipaddress] nvarchar (200) not null,
|
[ipaddress] nvarchar (200) not null,
|
||||||
[doneAt] datetime not null,
|
[doneAt] datetime not null,
|
||||||
primary key([rlid])
|
primary key([rlid])
|
||||||
);
|
);
|
|
@ -1,19 +1,19 @@
|
||||||
CREATE TABLE [replies] (
|
CREATE TABLE [replies] (
|
||||||
[rid] int not null IDENTITY,
|
[rid] int not null IDENTITY,
|
||||||
[tid] int not null,
|
[tid] int not null,
|
||||||
[content] nvarchar (MAX) not null,
|
[content] nvarchar (MAX) not null,
|
||||||
[parsed_content] nvarchar (MAX) not null,
|
[parsed_content] nvarchar (MAX) not null,
|
||||||
[createdAt] datetime not null,
|
[createdAt] datetime not null,
|
||||||
[createdBy] int not null,
|
[createdBy] int not null,
|
||||||
[lastEdit] int DEFAULT 0 not null,
|
[lastEdit] int DEFAULT 0 not null,
|
||||||
[lastEditBy] int DEFAULT 0 not null,
|
[lastEditBy] int DEFAULT 0 not null,
|
||||||
[lastUpdated] datetime not null,
|
[lastUpdated] datetime not null,
|
||||||
[ip] nvarchar (200) DEFAULT '' not null,
|
[ip] nvarchar (200) DEFAULT '' not null,
|
||||||
[likeCount] int DEFAULT 0 not null,
|
[likeCount] int DEFAULT 0 not null,
|
||||||
[attachCount] int DEFAULT 0 not null,
|
[attachCount] int DEFAULT 0 not null,
|
||||||
[words] int DEFAULT 1 not null,
|
[words] int DEFAULT 1 not null,
|
||||||
[actionType] nvarchar (20) DEFAULT '' not null,
|
[actionType] nvarchar (20) DEFAULT '' not null,
|
||||||
[poll] int DEFAULT 0 not null,
|
[poll] int DEFAULT 0 not null,
|
||||||
primary key([rid]),
|
primary key([rid]),
|
||||||
fulltext key([content])
|
fulltext key([content])
|
||||||
);
|
);
|
|
@ -1,8 +1,8 @@
|
||||||
CREATE TABLE [revisions] (
|
CREATE TABLE [revisions] (
|
||||||
[reviseID] int not null IDENTITY,
|
[reviseID] int not null IDENTITY,
|
||||||
[content] nvarchar (MAX) not null,
|
[content] nvarchar (MAX) not null,
|
||||||
[contentID] int not null,
|
[contentID] int not null,
|
||||||
[contentType] nvarchar (100) DEFAULT 'replies' not null,
|
[contentType] nvarchar (100) DEFAULT 'replies' not null,
|
||||||
[createdAt] datetime not null,
|
[createdAt] datetime not null,
|
||||||
primary key([reviseID])
|
primary key([reviseID])
|
||||||
);
|
);
|
|
@ -1,7 +1,7 @@
|
||||||
CREATE TABLE [settings] (
|
CREATE TABLE [settings] (
|
||||||
[name] nvarchar (180) not null,
|
[name] nvarchar (180) not null,
|
||||||
[content] nvarchar (250) not null,
|
[content] nvarchar (250) not null,
|
||||||
[type] nvarchar (50) not null,
|
[type] nvarchar (50) not null,
|
||||||
[constraints] nvarchar (200) DEFAULT '' not null,
|
[constraints] nvarchar (200) DEFAULT '' not null,
|
||||||
unique([name])
|
unique([name])
|
||||||
);
|
);
|
|
@ -1,3 +1,3 @@
|
||||||
CREATE TABLE [sync] (
|
CREATE TABLE [sync] (
|
||||||
[last_update] datetime not null
|
[last_update] datetime not null
|
||||||
);
|
);
|
|
@ -1,5 +1,5 @@
|
||||||
CREATE TABLE [themes] (
|
CREATE TABLE [themes] (
|
||||||
[uname] nvarchar (180) not null,
|
[uname] nvarchar (180) not null,
|
||||||
[default] bit DEFAULT 0 not null,
|
[default] bit DEFAULT 0 not null,
|
||||||
unique([uname])
|
unique([uname])
|
||||||
);
|
);
|
|
@ -1,4 +1,4 @@
|
||||||
CREATE TABLE [topicchunks] (
|
CREATE TABLE [topicchunks] (
|
||||||
[count] int DEFAULT 0 not null,
|
[count] int DEFAULT 0 not null,
|
||||||
[createdAt] datetime not null
|
[createdAt] datetime not null
|
||||||
);
|
);
|
|
@ -1,28 +1,28 @@
|
||||||
CREATE TABLE [topics] (
|
CREATE TABLE [topics] (
|
||||||
[tid] int not null IDENTITY,
|
[tid] int not null IDENTITY,
|
||||||
[title] nvarchar (100) not null,
|
[title] nvarchar (100) not null,
|
||||||
[content] nvarchar (MAX) not null,
|
[content] nvarchar (MAX) not null,
|
||||||
[parsed_content] nvarchar (MAX) not null,
|
[parsed_content] nvarchar (MAX) not null,
|
||||||
[createdAt] datetime not null,
|
[createdAt] datetime not null,
|
||||||
[lastReplyAt] datetime not null,
|
[lastReplyAt] datetime not null,
|
||||||
[lastReplyBy] int not null,
|
[lastReplyBy] int not null,
|
||||||
[lastReplyID] int DEFAULT 0 not null,
|
[lastReplyID] int DEFAULT 0 not null,
|
||||||
[createdBy] int not null,
|
[createdBy] int not null,
|
||||||
[is_closed] bit DEFAULT 0 not null,
|
[is_closed] bit DEFAULT 0 not null,
|
||||||
[sticky] bit DEFAULT 0 not null,
|
[sticky] bit DEFAULT 0 not null,
|
||||||
[parentID] int DEFAULT 2 not null,
|
[parentID] int DEFAULT 2 not null,
|
||||||
[ip] nvarchar (200) DEFAULT '' not null,
|
[ip] nvarchar (200) DEFAULT '' not null,
|
||||||
[postCount] int DEFAULT 1 not null,
|
[postCount] int DEFAULT 1 not null,
|
||||||
[likeCount] int DEFAULT 0 not null,
|
[likeCount] int DEFAULT 0 not null,
|
||||||
[attachCount] int DEFAULT 0 not null,
|
[attachCount] int DEFAULT 0 not null,
|
||||||
[words] int DEFAULT 0 not null,
|
[words] int DEFAULT 0 not null,
|
||||||
[views] int DEFAULT 0 not null,
|
[views] int DEFAULT 0 not null,
|
||||||
[weekEvenViews] int DEFAULT 0 not null,
|
[weekEvenViews] int DEFAULT 0 not null,
|
||||||
[weekOddViews] int DEFAULT 0 not null,
|
[weekOddViews] int DEFAULT 0 not null,
|
||||||
[css_class] nvarchar (100) DEFAULT '' not null,
|
[css_class] nvarchar (100) DEFAULT '' not null,
|
||||||
[poll] int DEFAULT 0 not null,
|
[poll] int DEFAULT 0 not null,
|
||||||
[data] nvarchar (200) DEFAULT '' not null,
|
[data] nvarchar (200) DEFAULT '' not null,
|
||||||
primary key([tid]),
|
primary key([tid]),
|
||||||
fulltext key([title]),
|
fulltext key([title]),
|
||||||
fulltext key([content])
|
fulltext key([content])
|
||||||
);
|
);
|
|
@ -1,3 +1,3 @@
|
||||||
CREATE TABLE [updates] (
|
CREATE TABLE [updates] (
|
||||||
[dbVersion] int DEFAULT 0 not null
|
[dbVersion] int DEFAULT 0 not null
|
||||||
);
|
);
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue