├── .circleci └── config.yml ├── .gitattributes ├── .github └── FUNDING.yml ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── docker-compose.yml ├── functions.go ├── go.mod ├── go.sum ├── main.go ├── scripts ├── build │ ├── all.sh │ ├── netlify.sh │ └── www.js ├── changelog.sh └── make_release.sh ├── start.sh ├── statik └── statik.go ├── structs.go └── www ├── _header.hbs ├── all_users.hbs ├── categories.json ├── index.html ├── leaderboard.hbs ├── new.hbs ├── requests.hbs ├── response.hbs ├── stats.hbs └── style.css /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Golang CircleCI 2.0 configuration file 2 | # See https://circleci.com/docs/2.0/language-go/ 3 | version: 2.1 4 | orbs: 5 | docker: circleci/docker@1.0.1 6 | jobs: 7 | build: 8 | working_directory: /go/src/github.com/nektro/skarn 9 | docker: 10 | - image: circleci/golang:1.12 11 | steps: 12 | - checkout 13 | - run: go get -v -t -d ./... 14 | - run: go test -v ./... 15 | - run: ./scripts/build/all.sh 16 | - store_artifacts: 17 | path: ./bin/ 18 | destination: /artifacts/ 19 | - run: ./scripts/make_release.sh 20 | - setup_remote_docker 21 | - docker/check 22 | - docker/build: 23 | image: $CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME 24 | - docker/push: 25 | image: $CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME 26 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: nektro 4 | # patreon: 5 | # open_collective: 6 | # ko_fi: 7 | # tidelift: 8 | # community_bridge: 9 | # liberapay: 10 | # issuehunt: 11 | # otechie: 12 | custom: https://www.paypal.me/nektro 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /bin/ 2 | /skarn* 3 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:alpine as golang 2 | WORKDIR /go/src/skarn 3 | COPY . . 4 | RUN apk add --no-cache git libc-dev musl-dev build-base gcc ca-certificates \ 5 | && export VCS_REF=$(git describe --tags) \ 6 | && echo $VCS_REF \ 7 | && go get -u github.com/rakyll/statik \ 8 | && $GOPATH/bin/statik -src="./www/" \ 9 | && go get -u . \ 10 | && CGO_ENABLED=1 go build -ldflags "-s -w -X main.Version=$VCS_REF" . 11 | 12 | FROM alpine 13 | COPY --from=golang /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ 14 | COPY --from=golang /go/src/skarn/skarn /app/skarn 15 | 16 | VOLUME /data 17 | ENTRYPOINT ["/app/skarn", "--port", "80", "--config", "/data/config.json"] 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2020 Meghan Denny 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Skarn 2 | ![loc](https://sloc.xyz/github/nektro/skarn) 3 | [![license](https://img.shields.io/github/license/nektro/skarn.svg)](https://github.com/nektro/skarn/blob/master/LICENSE) 4 | [![discord](https://img.shields.io/discord/551971034593755159.svg)](https://discord.gg/P6Y4zQC) 5 | [![paypal](https://img.shields.io/badge/donate-paypal-009cdf)](https://paypal.me/nektro) 6 | [![circleci](https://circleci.com/gh/nektro/skarn.svg?style=svg)](https://circleci.com/gh/nektro/skarn) 7 | [![release](https://img.shields.io/github/v/release/nektro/skarn)](https://github.com/nektro/skarn/releases/latest) 8 | [![goreportcard](https://goreportcard.com/badge/github.com/nektro/skarn)](https://goreportcard.com/report/github.com/nektro/skarn) 9 | [![codefactor](https://www.codefactor.io/repository/github/nektro/skarn/badge)](https://www.codefactor.io/repository/github/nektro/skarn) 10 | 11 | Media Request & Inventory Management System 12 | 13 | ## Getting Started 14 | These instructions will get you a copy of the project up and running on your machine. 15 | 16 | ### Configuration 17 | This guide assumes you want to configure Skarn to a Discord server and auto-add members that have a specific role. 18 | 19 | - Go to https://discordapp.com/developers/applications/ 20 | - Create an application and save down the Client ID and Client Secret. 21 | - Add a bot to the application and save down the Bot Token. 22 | - Add the bot to the server you wish to auth this instance throuh. 23 | - Below are the command line flags you may use to configure your Skarn instance. 24 | 25 | | Name | Type | Default | Description | 26 | |------|------|---------|-------------| 27 | | `--port` | `int` | `8001` | Port for web server to bind to. | 28 | | `--members` | `[]string` | none. | List of role snowflakes that may view this instance | 29 | | `--admins` | `[]string` | none. | List of role snowflakes that may manage this instance | 30 | | `--theme` | `[]string` | none. | List of theme IDs | 31 | | `--announce-webhook-url` | `string` | none. | Discord webhook URL for announcements | 32 | 33 | ### Themes 34 | Skarn supports custom themes through use of the `--theme` flag to identify a folder or list of folders to overwrite any of the handlebars template files. The location to place themes is at `~/.config/skarn/themes/{THEME_ID}/` 35 | 36 | ### Announcements 37 | Using the `--announce-webhook-url` flag you can create an announcements channel that will display status updates to requests. See https://support.discordapp.com/hc/en-us/articles/228383668-Intro-to-Webhooks for more info on how to setup Discord Webhooks and get the URL. 38 | 39 | ## Development 40 | 41 | ### Prerequisites 42 | - The Go Language 1.12+ (https://golang.org/dl/) 43 | - Docker (https://www.docker.com/products/docker-desktop) 44 | - Docker Compose (https://docs.docker.com/compose/install/) 45 | 46 | ### Installing 47 | Run 48 | ``` 49 | $ git clone https://github.com/nektro/skarn 50 | $ cd ./skarn/ 51 | $ go get -v . 52 | $ docker-compose up 53 | ``` 54 | 55 | ## Deployment 56 | Pre-compiled binaries can be obtained from https://github.com/nektro/skarn/releases/latest. 57 | 58 | Or you can build from source: 59 | ``` 60 | $ ./scripts/build/all.sh 61 | ``` 62 | 63 | ## Contributing 64 | [![issues](https://img.shields.io/github/issues/nektro/skarn.svg)](https://github.com/nektro/skarn/issues) 65 | [![pulls](https://img.shields.io/github/issues-pr/nektro/skarn.svg)](https://github.com/nektro/skarn/pulls) 66 | 67 | We take issues all the time right here on GitHub. We use labels extensively to show the progress through the fixing process. Question issues are okay but make sure to close the issue when it's been answered! 68 | 69 | When making a pull request, please have it be associated with an issue and make a comment on the issue saying that you're working on it so everyone else knows what's going on :D 70 | 71 | ## Contact 72 | - hello@nektro.net 73 | - Meghan#2032 on https://discord.gg/P6Y4zQC 74 | - https://twitter.com/nektro 75 | 76 | ## License 77 | Apache 2.0 78 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | services: 3 | app: 4 | image: golang:1.12.17 5 | volumes: 6 | - .:/app/ 7 | working_dir: /app/ 8 | command: go run . --port 8000 --config './data/config.json' 9 | ports: 10 | - "80:8000" 11 | -------------------------------------------------------------------------------- /functions.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "database/sql" 5 | "encoding/json" 6 | "io/ioutil" 7 | "net/http" 8 | "net/url" 9 | "strconv" 10 | "strings" 11 | 12 | "github.com/gorilla/sessions" 13 | "github.com/nektro/go-util/arrays/stringsu" 14 | "github.com/nektro/go-util/util" 15 | etc "github.com/nektro/go.etc" 16 | 17 | . "github.com/nektro/go-util/alias" 18 | ) 19 | 20 | // 21 | // 22 | 23 | // QueryDoSelect simplifies commonly built sql statements 24 | func QueryDoSelect(table, col, val string) *sql.Rows { 25 | return db.Build().Se("*").Fr(table).Wh(col, val).Exe() 26 | } 27 | 28 | // QuerySelectFunc simplifies commonly built sql statements 29 | func QuerySelectFunc(table, f, fcol, col, val string) *sql.Rows { 30 | return db.Build().Se(F("%s(%s)", f, fcol)).Fr(table).Wh(col, val).Exe() 31 | } 32 | 33 | // QueryDoUpdate simplifies commonly built sql statements 34 | func QueryDoUpdate(table, ucol, uval, col, val string) *sql.Rows { 35 | return db.Build().Up(table, ucol, uval).Wh(col, val).Exe() 36 | } 37 | 38 | // QueryDoSelectAll simplifies commonly built sql statements 39 | func QueryDoSelectAll(table string) *sql.Rows { 40 | return db.Build().Se("*").Fr(table).Exe() 41 | } 42 | 43 | // QueryDelete simplifies commonly built sql statements 44 | func QueryDelete(table, col, val string) *sql.Rows { 45 | return db.Build().Del(table).Wh(col, val).Exe() 46 | } 47 | 48 | // 49 | // 50 | 51 | func isLoggedIn(r *http.Request) bool { 52 | return isLoggedInS(etc.GetSession(r)) 53 | } 54 | 55 | func isLoggedInS(sess *sessions.Session) bool { 56 | _, ok := sess.Values["user"] 57 | return ok 58 | } 59 | 60 | func saveOAuth2Info(w http.ResponseWriter, r *http.Request, provider string, id string, name string, oa2resp map[string]interface{}) { 61 | util.Log("[user-login]", provider, id, name) 62 | sess := etc.GetSession(r) 63 | sess.Values["user"] = id 64 | sess.Save(r, w) 65 | queryUserBySnowflake(id) 66 | QueryDoUpdate("users", "username", name, "snowflake", id) 67 | } 68 | 69 | func queryUserBySnowflake(snowflake string) *User { 70 | rows := QueryDoSelect("users", "snowflake", snowflake) 71 | if rows.Next() { 72 | ru := scanUser(rows) 73 | rows.Close() 74 | return &ru 75 | } 76 | // else 77 | id := db.QueryNextID("users") 78 | db.Build().Ins("users", id, snowflake, T(), 0, util.Btoi(id == 1), "", "", "").Exe() 79 | return queryUserBySnowflake(snowflake) 80 | } 81 | 82 | func scanUser(rows *sql.Rows) User { 83 | var u User 84 | rows.Scan(&u.ID, &u.Snowflake, &u.JoinedOn, &u.IsMember, &u.IsAdmin, &u.Username, &u.Nickname, &u.Avatar) 85 | if len(u.Nickname) > 0 { 86 | u.RealName = u.Nickname 87 | } else { 88 | u.RealName = u.Username 89 | } 90 | return u 91 | } 92 | 93 | func pageInit(r *http.Request, w http.ResponseWriter, method string, requireLogin bool, requireMember bool, requireAdmin bool) (*sessions.Session, *User, error) { 94 | if r.Method != method { 95 | writeResponse(r, w, "Forbidden Method", F("%s is not allowed on this endpoint.", r.Method), "", "") 96 | return nil, nil, E("bad http method") 97 | } 98 | if method == http.MethodPost { 99 | r.ParseForm() 100 | } 101 | if !requireLogin { 102 | return nil, nil, nil 103 | } 104 | 105 | s := etc.GetSession(r) 106 | if !isLoggedInS(s) { 107 | writeResponse(r, w, "Authentication Required", "You must log in to access this site.", "/login", "Please Log In") 108 | return s, nil, E("not logged in") 109 | } 110 | 111 | if !requireMember { 112 | return s, nil, nil 113 | } 114 | u := queryUserBySnowflake(s.Values["user"].(string)) 115 | if requireMember && !u.IsMember { 116 | writeResponse(r, w, "Access Forbidden", "You must be a member to view this page.", "", "") 117 | return s, u, E("not a member") 118 | } 119 | if requireAdmin && !u.IsAdmin { 120 | writeResponse(r, w, "Access Forbidden", "You must be an admin to view this page.", "", "") 121 | return s, u, E("not an admin") 122 | } 123 | 124 | return s, u, nil 125 | } 126 | 127 | func doDiscordAPIRequest(endpoint string) ([]byte, int) { 128 | par := url.Values{} 129 | req, _ := http.NewRequest(http.MethodGet, "https://discordapp.com/api/v6"+endpoint, strings.NewReader(par.Encode())) 130 | req.Header.Set("User-Agent", "nektro/skarn") 131 | req.Header.Set("Authorization", "Bot "+config.Clients[0].Extra1) 132 | return doHttpRequest(req) 133 | } 134 | 135 | func doHttpRequest(req *http.Request) ([]byte, int) { 136 | resp, _ := http.DefaultClient.Do(req) 137 | body, _ := ioutil.ReadAll(resp.Body) 138 | resp.Body.Close() 139 | return body, resp.StatusCode 140 | } 141 | 142 | func containsAny(haystack []string, needle []string) bool { 143 | for _, item := range needle { 144 | if stringsu.Contains(haystack, item) { 145 | return true 146 | } 147 | } 148 | return false 149 | } 150 | 151 | func writeResponse(r *http.Request, w http.ResponseWriter, title string, message string, url string, link string) { 152 | etc.WriteHandlebarsFile(r, w, "/response.hbs", map[string]interface{}{ 153 | "base": "/", 154 | "title": title, 155 | "message": message, 156 | "url": url, 157 | "link": link, 158 | }) 159 | } 160 | 161 | func assertPostFormValuesExist(r *http.Request, args ...string) error { 162 | for _, item := range args { 163 | v := r.PostForm.Get(item) 164 | if len(v) == 0 { 165 | return E(F("form[%s] empty", item)) 166 | } 167 | } 168 | return nil 169 | } 170 | 171 | func assertURLValidity(toTest string) error { 172 | _, err := url.Parse(toTest) 173 | return err 174 | } 175 | 176 | func scanRowsRequests(rows *sql.Rows) []Request { 177 | result := []Request{} 178 | for rows.Next() { 179 | var rq Request 180 | rows.Scan(&rq.ID, &rq.Owner, &rq.Category, &rq.AddedOn, &rq.Title, &rq.QualityRaw, &rq.Link, &rq.Description, &rq.Points, &rq.Filler, &rq.FilledOn, &rq.Response) 181 | rq.Quality = strings.Split(rq.QualityRaw, ",") 182 | rq.Filled = rq.Filler > -1 183 | result = append(result, rq) 184 | } 185 | rows.Close() 186 | return result 187 | } 188 | 189 | func scanRowsUsers(rows *sql.Rows) []User { 190 | result := []User{} 191 | for rows.Next() { 192 | u := scanUser(rows) 193 | result = append(result, u) 194 | } 195 | rows.Close() 196 | return result 197 | } 198 | 199 | func scanInt(row *sql.Rows) int { 200 | var s int 201 | if row.Next() { 202 | row.Scan(&s) 203 | } 204 | row.Close() 205 | return s 206 | } 207 | 208 | func scanRowsUsersComplete(rows *sql.Rows) []UserComplete { 209 | result := []UserComplete{} 210 | users := scanRowsUsers(rows) 211 | for _, u := range users { 212 | uid := strconv.Itoa(u.ID) 213 | var uc UserComplete 214 | uc.U = u 215 | uc.Fills = scanInt(QuerySelectFunc("requests", "count", "points", "filler", uid)) 216 | uc.PointsF = scanInt(QuerySelectFunc("requests", "sum", "points", "filler", uid)) 217 | uc.Requests = scanInt(QuerySelectFunc("requests", "count", "points", "owner", uid)) 218 | uc.PointsR = scanInt(QuerySelectFunc("requests", "sum", "points", "owner", uid)) 219 | result = append(result, uc) 220 | } 221 | return result 222 | } 223 | 224 | func writePage(r *http.Request, w http.ResponseWriter, user *User, path string, page string, title string, data map[string]interface{}) { 225 | etc.WriteHandlebarsFile(r, w, "/_header.hbs", map[string]interface{}{ 226 | "version": Version, 227 | "base": "/", 228 | "user": user, 229 | "page": page, 230 | "title": title, 231 | }) 232 | etc.WriteHandlebarsFile(r, w, path, map[string]interface{}{ 233 | "version": Version, 234 | "base": "/", 235 | "user": user, 236 | "page": page, 237 | "title": title, 238 | "data": data, 239 | }) 240 | } 241 | 242 | func isInt(s string) bool { 243 | _, err := strconv.ParseInt(s, 10, 32) 244 | return err == nil 245 | } 246 | 247 | func queryRequestById(id string) (*Request, *User, error) { 248 | if !isInt(id) { 249 | return nil, nil, E("non-ID ID") 250 | } 251 | reqs := scanRowsRequests(QueryDoSelect("requests", "id", id)) 252 | if len(reqs) == 0 { 253 | return nil, nil, E("unable to find specified request") 254 | } 255 | req := reqs[0] 256 | own := scanRowsUsers(QueryDoSelect("users", "id", strconv.Itoa(req.Owner)))[0] 257 | return &req, &own, nil 258 | } 259 | 260 | func makeAnnouncement(message string) { 261 | if len(config.AnnounceURL) == 0 { 262 | return 263 | } 264 | urlO, _ := url.Parse(config.AnnounceURL) 265 | if urlO.Host != "discordapp.com" { 266 | return 267 | } 268 | if !strings.HasPrefix(urlO.Path, "/api/webhooks/") { 269 | return 270 | } 271 | 272 | parameters := map[string]string{"content": message} 273 | content, _ := json.Marshal(parameters) 274 | req, _ := http.NewRequest(http.MethodPost, config.AnnounceURL, strings.NewReader(string(content))) 275 | req.Header.Set("User-Agent", "nektro/skarn") 276 | req.Header.Set("Content-Type", "application/json") 277 | http.DefaultClient.Do(req) 278 | } 279 | 280 | type reqStat struct { 281 | AddedOn string `json:"added_on"` 282 | FilledOn string `json:"filled_on"` 283 | } 284 | 285 | func requestsOverTime() interface{} { 286 | reqsRaw := scanRowsRequests(QueryDoSelectAll("requests")) 287 | reqsNew := []reqStat{} 288 | for _, item := range reqsRaw { 289 | reqsNew = append(reqsNew, reqStat{AddedOn: item.AddedOn, FilledOn: item.FilledOn}) 290 | } 291 | return reqsNew 292 | } 293 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/nektro/skarn 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/aymerick/raymond v2.0.2+incompatible 7 | github.com/deckarep/golang-set v1.7.1 // indirect 8 | github.com/gorilla/mux v1.7.4 // indirect 9 | github.com/gorilla/sessions v1.2.0 10 | github.com/mattn/go-sqlite3 v2.0.3+incompatible // indirect 11 | github.com/mitchellh/go-homedir v1.1.0 // indirect 12 | github.com/nektro/go-util v0.0.0-20200515093218-75e527c1e1ca 13 | github.com/nektro/go.dbstorage v0.0.0-20200515093335-8e2c19fc1929 14 | github.com/nektro/go.discord v0.0.0-20190906060420-58630ff220dd 15 | github.com/nektro/go.etc v0.0.0-20200605221012-5880324e03dc 16 | github.com/nektro/go.oauth2 v0.0.0-20200413024519-33aeafe6ee91 17 | github.com/rakyll/statik v0.1.7 18 | github.com/spf13/pflag v1.0.5 // indirect 19 | github.com/valyala/fastjson v1.5.1 20 | golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9 // indirect 21 | ) 22 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/aymerick/raymond v1.1.0 h1:phuNN2s67eI/HtO8CrvqFcdR2JP+BtkGJZ9n692Hr2Y= 2 | github.com/aymerick/raymond v2.0.2+incompatible h1:VEp3GpgdAnv9B2GFyTvqgcKvY+mfKMjPOA3SbKLtnU0= 3 | github.com/aymerick/raymond v2.0.2+incompatible/go.mod h1:osfaiScAUVup+UC9Nfq76eWqDhXlp+4UYaA8uhTBO6g= 4 | github.com/deckarep/golang-set v1.7.1 h1:SCQV0S6gTtp6itiFrTqI+pfmJ4LN85S1YzhDf9rTHJQ= 5 | github.com/deckarep/golang-set v1.7.1/go.mod h1:93vsz/8Wt4joVM7c2AVqh+YRMiUSc14yDtF28KmMOgQ= 6 | github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc= 7 | github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= 8 | github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= 9 | github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= 10 | github.com/gorilla/sessions v1.2.0 h1:S7P+1Hm5V/AT9cjEcUD5uDaQSX0OE577aCXgoaKpYbQ= 11 | github.com/gorilla/sessions v1.2.0/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= 12 | github.com/mattn/go-sqlite3 v1.13.0 h1:LnJI81JidiW9r7pS/hXe6cFeO5EXNq7KbfvoJLRI69c= 13 | github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= 14 | github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= 15 | github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= 16 | github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= 17 | github.com/nektro/go-util v0.0.0-20200515093218-75e527c1e1ca h1:eD6+0iugGYMg/oxoiUY+HT+VRwf7bKan1Q1nxzzwVxs= 18 | github.com/nektro/go-util v0.0.0-20200515093218-75e527c1e1ca/go.mod h1:EhkJcpK0SX9LtkqvOHWG9Fpe7LE3kxTM0dMKUp08VnM= 19 | github.com/nektro/go.dbstorage v0.0.0-20200515093335-8e2c19fc1929 h1:ocJRVTfqJRym3G48Ho+1PGkoQ3xda/moDEFFjUpbCtg= 20 | github.com/nektro/go.dbstorage v0.0.0-20200515093335-8e2c19fc1929/go.mod h1:8PkaJBrkNn1TsHpOjDLDxOsKXv7QviBBjncs0WgPyO0= 21 | github.com/nektro/go.discord v0.0.0-20190906060420-58630ff220dd h1:e8RgnXPoDTc+Q340LAuZ+OdOe7XPYOXTF5k5CI5daqM= 22 | github.com/nektro/go.discord v0.0.0-20190906060420-58630ff220dd/go.mod h1:5l5KIfJE6AHZkxaYglzzqaR/P4tSIv+UzzR1mrXWQX8= 23 | github.com/nektro/go.etc v0.0.0-20200605221012-5880324e03dc h1:Oo2Oa2xKXI2igKgIVt0Ry+OL7EJpcgTpC/wqYhtO4Do= 24 | github.com/nektro/go.etc v0.0.0-20200605221012-5880324e03dc/go.mod h1:lZDMgzeJ6eYj8GNcQXfVs2s1KERw00pE2IMVs9XlO+w= 25 | github.com/nektro/go.oauth2 v0.0.0-20200413024519-33aeafe6ee91 h1:RguHpv3kTNGR87GpXT+V86xZVBsWyOTKLl1Fukr5R68= 26 | github.com/nektro/go.oauth2 v0.0.0-20200413024519-33aeafe6ee91/go.mod h1:ywuQRMEuUHKL59OHssh4c0taBA2APYnun7humThPn9o= 27 | github.com/rakyll/statik v0.1.7 h1:OF3QCZUuyPxuGEP7B4ypUa7sB/iHtqOTDYZXGM8KOdQ= 28 | github.com/rakyll/statik v0.1.7/go.mod h1:AlZONWzMtEnMs7W4e/1LURLiI49pIMmp6V9Unghqrcc= 29 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 30 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 31 | github.com/valyala/fastjson v1.5.1 h1:SXaQZVSwLjZOVhDEhjiCcDtnX0Feu7Z7A1+C5atpoHM= 32 | github.com/valyala/fastjson v1.5.1/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY= 33 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 34 | golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9 h1:vEg9joUBmeBcK9iSJftGNf3coIG4HqZElCPehJsfAYM= 35 | golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 36 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 37 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 38 | golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI= 39 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 40 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 41 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io/ioutil" 7 | "net/http" 8 | "net/url" 9 | "os" 10 | "strconv" 11 | "strings" 12 | "time" 13 | 14 | "github.com/aymerick/raymond" 15 | "github.com/nektro/go-util/arrays/stringsu" 16 | "github.com/nektro/go-util/util" 17 | "github.com/nektro/go-util/vflag" 18 | dbstorage "github.com/nektro/go.dbstorage" 19 | discord "github.com/nektro/go.discord" 20 | etc "github.com/nektro/go.etc" 21 | "github.com/nektro/go.etc/htp" 22 | "github.com/valyala/fastjson" 23 | 24 | . "github.com/nektro/go-util/alias" 25 | 26 | _ "github.com/nektro/skarn/statik" 27 | ) 28 | 29 | var ( 30 | config = new(Config) 31 | categoryNames = []string{"lit", "mov", "mus", "exe", "xxx", "etc"} 32 | categoryValues map[string]CategoryMapValue 33 | Version = "vMASTER" 34 | db dbstorage.Database 35 | ) 36 | 37 | // file:///home/meghan/.config/skarn/config.json 38 | 39 | func main() { 40 | etc.AppID = "skarn" 41 | Version = etc.FixBareVersion(Version) 42 | util.Log("Initializing Skarn Request System...") 43 | 44 | vflag.IntVar(&config.Port, "port", 8000, "") 45 | vflag.StringArrayVar(&config.Members, "members", []string{}, "") 46 | vflag.StringArrayVar(&config.Members, "admins", []string{}, "") 47 | vflag.StringVar(&config.AnnounceURL, "announce-webhook-url", "", "") 48 | etc.PreInit() 49 | 50 | etc.Init("skarn", &config, "./verify", saveOAuth2Info) 51 | 52 | // 53 | 54 | catf, err := etc.MFS.Open("/categories.json") 55 | util.DieOnError(err, "Unable to read 'categories.json' from static resources!") 56 | catb, _ := ioutil.ReadAll(catf) 57 | json.Unmarshal(catb, &categoryValues) 58 | 59 | // 60 | 61 | db = etc.Database 62 | db.CreateTableStruct("users", User{}) 63 | db.CreateTableStruct("requests", Request{}) 64 | 65 | // 66 | 67 | util.RunOnClose(func() { 68 | util.Log("Gracefully shutting down...") 69 | 70 | util.Log("Saving database to disk") 71 | db.Close() 72 | 73 | os.Exit(0) 74 | }) 75 | 76 | // 77 | 78 | raymond.RegisterHelper("icon", func(cat string) string { 79 | return categoryValues[cat].Icon 80 | }) 81 | 82 | raymond.RegisterHelper("domain", func(link string) string { 83 | u, e := url.Parse(link) 84 | if e != nil { 85 | return "WWW" 86 | } 87 | return u.Host 88 | }) 89 | 90 | raymond.RegisterHelper("name", func(userID int) string { 91 | usrs := scanRowsUsers(QueryDoSelect("users", "id", strconv.FormatInt(int64(userID), 10))) 92 | if len(usrs) == 0 { 93 | return "" 94 | } 95 | return usrs[0].RealName 96 | }) 97 | 98 | raymond.RegisterHelper("quality", func(cat string, item string) string { 99 | i, _ := strconv.ParseInt(item, 10, 32) 100 | return categoryValues[cat].Quality[i] 101 | }) 102 | 103 | raymond.RegisterHelper("length", func(array []string) int { 104 | return len(array) 105 | }) 106 | 107 | // 108 | 109 | util.DieOnError(util.Assert(len(config.Clients) == 1, "'config.json' must only have 1 client")) 110 | util.DieOnError(util.Assert(config.Clients[0].For == "discord", "client in 'config.json' must be for discord")) 111 | 112 | htp.Register("/verify", "GET", func(w http.ResponseWriter, r *http.Request) { 113 | s, u, err := pageInit(r, w, http.MethodGet, true, false, false) 114 | if err != nil { 115 | return 116 | } 117 | 118 | tm, ok := s.Values["verify_time"] 119 | if ok { 120 | a := time.Now().Unix() - tm.(int64) 121 | b := int64(time.Second * 60 * 1) 122 | if a < b { 123 | if !u.IsMember { 124 | writeResponse(r, w, "Access Denied", "Must be a member. Please try again later.", "", "") 125 | return // only query once every 1 mins 126 | } 127 | w.Header().Add("location", "./requests?status=open") 128 | w.WriteHeader(http.StatusFound) 129 | return 130 | } 131 | } 132 | 133 | snowflake := s.Values["user"].(string) 134 | res, rcd := doDiscordAPIRequest(F("/guilds/%s/members/%s", config.Clients[0].Extra2, snowflake)) 135 | if rcd >= 400 { 136 | writeResponse(r, w, "Discord Error", fastjson.GetString(res, "message"), "", "") 137 | return // discord error 138 | } 139 | 140 | var dat discord.GuildMember 141 | json.Unmarshal(res, &dat) 142 | 143 | QueryDoUpdate("users", "nickname", dat.Nickname, "snowflake", snowflake) 144 | QueryDoUpdate("users", "avatar", dat.User.Avatar, "snowflake", snowflake) 145 | 146 | allowed := false 147 | if containsAny(dat.Roles, config.Members) { 148 | QueryDoUpdate("users", "is_member", "1", "snowflake", snowflake) 149 | allowed = true 150 | } 151 | if containsAny(dat.Roles, config.Admins) { 152 | QueryDoUpdate("users", "is_admin", "1", "snowflake", snowflake) 153 | allowed = true 154 | } 155 | if !allowed { 156 | QueryDoUpdate("users", "is_member", "0", "snowflake", snowflake) 157 | QueryDoUpdate("users", "is_admin", "0", "snowflake", snowflake) 158 | writeResponse(r, w, "Acess Denied", "No valid Discord Roles found.", "", "") 159 | return 160 | } 161 | 162 | s.Values["verify_time"] = time.Now().Unix() 163 | s.Save(r, w) 164 | 165 | w.Header().Add("location", "./requests?status=open") 166 | w.WriteHeader(http.StatusFound) 167 | }) 168 | 169 | htp.Register("/requests", "GET", func(w http.ResponseWriter, r *http.Request) { 170 | _, u, err := pageInit(r, w, http.MethodGet, true, true, false) 171 | if err != nil { 172 | return 173 | } 174 | q := db.Build().Se("*").Fr("requests") 175 | // 176 | switch r.URL.Query().Get("status") { 177 | case "open": 178 | q.Wh("filler", "-1") 179 | case "closed": 180 | q.Wr("filler", ">", "0") 181 | } 182 | // 183 | own := r.URL.Query().Get("owner") 184 | if own != "" { 185 | _, err := strconv.Atoi(own) 186 | if err == nil { 187 | q.Wh("owner", own) 188 | } 189 | } 190 | // 191 | fill := r.URL.Query().Get("filler") 192 | if fill != "" { 193 | _, err := strconv.Atoi(fill) 194 | if err == nil { 195 | q.Wh("filler", fill) 196 | } 197 | } 198 | // 199 | s := q.Exe() 200 | writePage(r, w, u, "/requests.hbs", "reqs", "Requests", map[string]interface{}{ 201 | "requests": scanRowsRequests(s), 202 | }) 203 | }) 204 | 205 | htp.Register("/new", "GET", func(w http.ResponseWriter, r *http.Request) { 206 | _, u, err := pageInit(r, w, http.MethodGet, true, true, false) 207 | if err != nil { 208 | return 209 | } 210 | writePage(r, w, u, "/new.hbs", "new", "New Request", map[string]interface{}{ 211 | "categories": categoryValues, 212 | }) 213 | }) 214 | 215 | htp.Register("/edit", "GET", func(w http.ResponseWriter, r *http.Request) { 216 | _, u, err := pageInit(r, w, http.MethodGet, true, true, false) 217 | if err != nil { 218 | return 219 | } 220 | id := r.URL.Query().Get("id") 221 | req, _, err := queryRequestById(id) 222 | if err != nil { 223 | writeResponse(r, w, "Unable to find request", "", "./../../requests?status=open", "Go back to /requests") 224 | return 225 | } 226 | if req.Owner != u.ID { 227 | writeResponse(r, w, "Must own request to edit", "", "./../../requests?status=open", "Go back to /requests") 228 | return 229 | } 230 | writePage(r, w, u, "/new.hbs", "edit", "Edit Request", map[string]interface{}{ 231 | "categories": categoryValues, 232 | "req": map[string]string{ 233 | "id": id, 234 | "category": req.Category, 235 | "title": req.Title, 236 | "quality": strings.Join(req.Quality, ","), 237 | "link": req.Link, 238 | "description": req.Description, 239 | }, 240 | }) 241 | }) 242 | 243 | htp.Register("/leaderboard", "GET", func(w http.ResponseWriter, r *http.Request) { 244 | _, u, err := pageInit(r, w, http.MethodGet, true, true, false) 245 | if err != nil { 246 | return 247 | } 248 | writePage(r, w, u, "/leaderboard.hbs", "users", "Leaderboard", map[string]interface{}{ 249 | "users": scanRowsUsersComplete(QueryDoSelect("users", "is_member", "1")), 250 | }) 251 | }) 252 | 253 | htp.Register("/stats", "GET", func(w http.ResponseWriter, r *http.Request) { 254 | _, u, err := pageInit(r, w, http.MethodGet, true, true, false) 255 | if err != nil { 256 | return 257 | } 258 | writePage(r, w, u, "/stats.hbs", "stats", "Statistics", map[string]interface{}{ 259 | // 260 | }) 261 | }) 262 | 263 | htp.Register("/admin/users", "GET", func(w http.ResponseWriter, r *http.Request) { 264 | _, u, err := pageInit(r, w, http.MethodGet, true, true, true) 265 | if err != nil { 266 | return 267 | } 268 | writePage(r, w, u, "/all_users.hbs", "a/u", "All Users", map[string]interface{}{ 269 | "users": scanRowsUsers(QueryDoSelectAll("users")), 270 | }) 271 | }) 272 | 273 | // 274 | 275 | htp.Register("/api/request/create", "POST", func(w http.ResponseWriter, r *http.Request) { 276 | _, u, err := pageInit(r, w, http.MethodPost, true, true, false) 277 | if err != nil { 278 | return 279 | } 280 | if assertPostFormValuesExist(r, "category") != nil { 281 | writeResponse(r, w, "Missing POST values", "", "./../../new", "Go back to /new") 282 | return 283 | } 284 | cat := r.PostForm["category"][0] 285 | if !stringsu.Contains(categoryNames, cat) { 286 | writeResponse(r, w, "Invalid Category", "", "./../../new", "Go back to /new") 287 | return 288 | } 289 | if assertPostFormValuesExist(r, "quality_"+cat, "title", "link") != nil { 290 | writeResponse(r, w, "Missing POST values", "", "./../../new", "Go back to /new") 291 | return 292 | } 293 | q := r.PostForm.Get("quality_" + cat) 294 | t := r.PostForm.Get("title") 295 | l := r.PostForm.Get("link") 296 | d := r.PostForm.Get("description") 297 | lerr := assertURLValidity(l) 298 | if lerr != nil { 299 | writeResponse(r, w, "Link is not a valid URL", "", "./../../new", "Go back to /new") 300 | return 301 | } 302 | i := db.QueryNextID("requests") 303 | o := u.ID 304 | t = strings.ReplaceAll(t, "@", "@\u200D") 305 | t = strings.ReplaceAll(t, ":", ":\u200D") 306 | 307 | // success 308 | db.Build().Ins("requests", i, o, cat, T(), t, q, l, d, 1, -1, "", "").Exe() 309 | makeAnnouncement(F("**[NEW]** <@%s> created a request for **%s**.", u.Snowflake, t)) 310 | writeResponse(r, w, "Success!", F("Added your request for %s", t), "./../../requests", "Back to home") 311 | }) 312 | 313 | htp.Register("/api/request/update", "POST", func(w http.ResponseWriter, r *http.Request) { 314 | _, u, err := pageInit(r, w, http.MethodPost, true, true, false) 315 | if err != nil { 316 | return 317 | } 318 | if assertPostFormValuesExist(r, "id", "category") != nil { 319 | writeResponse(r, w, "Missing POST values", "", "./../../new", "Go back to /new") 320 | return 321 | } 322 | id := r.PostForm.Get("id") 323 | req, _, err := queryRequestById(id) 324 | if err != nil { 325 | writeResponse(r, w, "Request not found", "", "./../../new", "Go back to /new") 326 | return 327 | } 328 | if req.Owner != u.ID { 329 | writeResponse(r, w, "Must own request to edit", "", "./../../edit?id="+id, "Go back to /edit") 330 | return 331 | } 332 | cat := r.PostForm.Get("category") 333 | if !stringsu.Contains(categoryNames, cat) { 334 | writeResponse(r, w, "Invalid Category", "", "./../../edit?id="+id, "Go back to /edit") 335 | return 336 | } 337 | if assertPostFormValuesExist(r, "quality_"+cat, "title", "link", "description") != nil { 338 | writeResponse(r, w, "Missing POST Values", "", "./../../edit?id="+id, "Go back to /edit") 339 | return 340 | } 341 | q := r.PostForm.Get("quality_" + cat) 342 | t := r.PostForm.Get("title") 343 | l := r.PostForm.Get("link") 344 | d := r.PostForm.Get("description") 345 | // 346 | t = strings.ReplaceAll(t, "@", "@\u200D") 347 | t = strings.ReplaceAll(t, ":", ":\u200D") 348 | if assertURLValidity(l) != nil { 349 | writeResponse(r, w, "Link is not a valid URL", "", "./../../edit?id="+id, "Go back to /edit") 350 | return 351 | } 352 | // success 353 | db.Build().Up("requests", "title", t).Wh("id", id).Exe() 354 | db.Build().Up("requests", "link", l).Wh("id", id).Exe() 355 | db.Build().Up("requests", "quality", q).Wh("id", id).Exe() 356 | db.Build().Up("requests", "description", d).Wh("id", id).Exe() 357 | makeAnnouncement(F("**[UPDATE]** <@%s> updated their request for **%s**.", u.Snowflake, t)) 358 | writeResponse(r, w, "Success!", F("Updated your request for %s", t), "./../../requests?status=open", "Back to home") 359 | }) 360 | 361 | htp.Register("/api/request/fill", "POST", func(w http.ResponseWriter, r *http.Request) { 362 | _, u, err := pageInit(r, w, http.MethodPost, true, true, false) 363 | if err != nil { 364 | return 365 | } 366 | if assertPostFormValuesExist(r, "id", "message") != nil { 367 | writeResponse(r, w, "Missing POST values", "", "./../../requests", "Go back to /requests") 368 | return 369 | } 370 | rid := r.PostForm["id"][0] 371 | msg := r.PostForm["message"][0] 372 | // 373 | req, own, err := queryRequestById(rid) 374 | if err != nil { 375 | writeResponse(r, w, "Unable to find request", "", "./../../requests", "Go back to /requests") 376 | return 377 | } 378 | if req.Filled { 379 | writeResponse(r, w, "Cannot fill already filled request", "", "./../../requests", "Go back to /requests") 380 | return 381 | } 382 | // 383 | QueryDoUpdate("requests", "filler", strconv.Itoa(u.ID), "id", rid) 384 | QueryDoUpdate("requests", "filled_on", T(), "id", rid) 385 | QueryDoUpdate("requests", "response", msg, "id", rid) 386 | makeAnnouncement(F("**[FILL]** <@%s>'s request for **%s** was just filled by <@%s>.", own.Snowflake, req.Title, u.Snowflake)) 387 | fmt.Fprintln(w, "good") 388 | }) 389 | 390 | htp.Register("/api/request/unfill", "POST", func(w http.ResponseWriter, r *http.Request) { 391 | _, u, err := pageInit(r, w, http.MethodPost, true, true, false) 392 | if err != nil { 393 | return 394 | } 395 | if assertPostFormValuesExist(r, "id") != nil { 396 | writeResponse(r, w, "Missing POST values", "", "./../../requests", "Go back to /requests") 397 | return 398 | } 399 | rid := r.PostForm["id"][0] 400 | req, own, err := queryRequestById(rid) 401 | if err != nil { 402 | writeResponse(r, w, "Unable to find request", "", "./../../requests", "Go back to /requests") 403 | return 404 | } 405 | if u.ID != own.ID && !u.IsAdmin { 406 | writeResponse(r, w, "Must own request to unfill", "", "./../../requests", "Go back to /requests") 407 | return 408 | } 409 | // 410 | QueryDoUpdate("requests", "filler", "-1", "id", rid) 411 | QueryDoUpdate("requests", "filled_on", "", "id", rid) 412 | QueryDoUpdate("requests", "response", "", "id", rid) 413 | makeAnnouncement(F("**[UNFILL]** <@%s>'s just un-filled their request for **%s**.", own.Snowflake, req.Title)) 414 | fmt.Fprintln(w, "good") 415 | }) 416 | 417 | htp.Register("/api/request/delete", "POST", func(w http.ResponseWriter, r *http.Request) { 418 | _, u, err := pageInit(r, w, http.MethodPost, true, true, false) 419 | if err != nil { 420 | return 421 | } 422 | if assertPostFormValuesExist(r, "id") != nil { 423 | writeResponse(r, w, "Missing POST values", "", "./../../requests", "Go back to /requests") 424 | return 425 | } 426 | rid := r.PostForm["id"][0] 427 | req, own, err := queryRequestById(rid) 428 | if err != nil { 429 | writeResponse(r, w, "Unable to find request", "", "./../../requests", "Go back to /requests") 430 | return 431 | } 432 | if u.ID != own.ID && !u.IsAdmin { 433 | writeResponse(r, w, "Must own request to delete", "", "./../../requests", "Go back to /requests") 434 | return 435 | } 436 | // 437 | QueryDelete("requests", "id", rid) 438 | makeAnnouncement(F("**[DELETE]** <@%s>'s request for **%s** was just deleted.", own.Snowflake, req.Title)) 439 | fmt.Fprintln(w, "good") 440 | }) 441 | 442 | htp.Register("/api/stats", "GET", func(w http.ResponseWriter, r *http.Request) { 443 | _, _, err := pageInit(r, w, http.MethodGet, true, true, false) 444 | if err != nil { 445 | return 446 | } 447 | bys, _ := json.Marshal(map[string]interface{}{ 448 | "requests_over_time": requestsOverTime(), 449 | }) 450 | w.Header().Add("content-type", "application/json") 451 | fmt.Fprintln(w, string(bys)) 452 | }) 453 | 454 | // 455 | 456 | etc.StartServer(config.Port) 457 | } 458 | -------------------------------------------------------------------------------- /scripts/build/all.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | init() { 4 | go get -v -u github.com/rakyll/statik 5 | $GOPATH/bin/statik -src="./www/" 6 | } 7 | build_template() { 8 | export CGO_ENABLED=1 9 | export GOOS=$1 10 | export GOARCH=$2 11 | export GOARM=7 12 | ext=$3 13 | date=$(date +'%Y.%m.%d') 14 | version=${CIRCLE_BUILD_NUM-$date} 15 | tag=v$version-$(git log --format=%h -1) 16 | echo $tag-$GOOS-$GOARCH 17 | go build -ldflags="-s -w -X main.Version=$tag" -o ./bin/skarn-$tag-$GOOS-$GOARCH$ext 18 | } 19 | 20 | init 21 | # build_template darwin 386 22 | # build_template darwin amd64 23 | # build_template dragonfly amd64 24 | # build_template freebsd 386 25 | # build_template freebsd amd64 26 | # build_template freebsd arm 27 | # build_template linux 386 28 | build_template linux amd64 29 | # build_template linux arm 30 | # build_template linux arm64 31 | # build_template linux ppc64 32 | # build_template linux ppc64le 33 | # build_template linux mips 34 | # build_template linux mipsle 35 | # build_template linux mips64 36 | # build_template linux mips64le 37 | # build_template linux s390x 38 | # build_template nacl 386 39 | # build_template nacl amd64p32 40 | # build_template nacl arm 41 | # build_template netbsd 386 42 | # build_template netbsd amd64 43 | # build_template netbsd arm 44 | # build_template openbsd 386 45 | # build_template openbsd amd64 46 | # build_template openbsd arm 47 | # build_template plan9 386 48 | # build_template plan9 amd64 49 | # build_template plan9 arm 50 | # build_template solaris amd64 51 | # build_template windows 386 .exe 52 | # build_template windows amd64 .exe 53 | -------------------------------------------------------------------------------- /scripts/build/netlify.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | # exit when any command fails 4 | set -e 5 | 6 | DIR=$(dirname $0) 7 | 8 | echo "<> Downloading source and updating dependecies" 9 | go get -v -t -d ./... 10 | echo 11 | 12 | echo "<> Running go test" 13 | go test -v ./... 14 | echo 15 | 16 | echo "<> Generating build artifacts" 17 | source $DIR/all.sh 18 | echo 19 | 20 | echo "<> Generating index.html" 21 | node $DIR/www.js 22 | -------------------------------------------------------------------------------- /scripts/build/www.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const fs = require("fs"); 4 | 5 | fs.readdir("./bin/", function(err, files) { 6 | // 7 | const data = ` 8 | 9 | 10 | 11 | 12 | 13 | Skarn Artifacts 14 | 17 | 18 | 19 |

Skarn Artifacts

20 | 23 | 24 | 25 | `; 26 | 27 | // 28 | fs.writeFile("./bin/index.html", data, function(err) {}); 29 | }); 30 | -------------------------------------------------------------------------------- /scripts/changelog.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | read-log() { 6 | git log --format=format:"%h%n%H%n%an%n%s%n%d%n" 7 | } 8 | 9 | hash_abrev='' 10 | hash='' 11 | author='' 12 | title='' 13 | 14 | c=0 15 | t=0 16 | read-log | 17 | while IFS= read -r lineVAR; do 18 | if [[ "$c" == '0' ]]; then 19 | hash_abrev="$lineVAR" 20 | fi 21 | if [[ "$c" == '1' ]]; then 22 | hash="$lineVAR" 23 | fi 24 | if [[ "$c" == '2' ]]; then 25 | author="$lineVAR" 26 | fi 27 | if [[ "$c" == '3' ]]; then 28 | title="$lineVAR" 29 | fi 30 | if [[ "$c" == '4' ]]; then 31 | if [ ! -z "$lineVAR" ]; then 32 | t=$(($t+1)) 33 | fi 34 | if [[ "$t" == '2' ]]; then 35 | break 36 | fi 37 | echo "
  • $hash_abrev $title ($author)
  • " 38 | fi 39 | c=$(($c+1)) 40 | # 41 | if [[ "$c" == '6' ]]; then 42 | c=0 43 | fi 44 | done 45 | -------------------------------------------------------------------------------- /scripts/make_release.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | init() { 4 | date=$(date +'%Y.%m.%d') 5 | version=${CIRCLE_BUILD_NUM-$date} 6 | tag=v$version-$(git log --format=%h -1) 7 | go get -v -u github.com/tcnksm/ghr 8 | $GOPATH/bin/ghr \ 9 | -t ${GITHUB_TOKEN} \ 10 | -u ${CIRCLE_PROJECT_USERNAME} \ 11 | -r ${CIRCLE_PROJECT_REPONAME} \ 12 | -b "$(./scripts/changelog.sh)" \ 13 | "$tag" \ 14 | "./bin/" 15 | } 16 | 17 | init 18 | -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | set -x 5 | 6 | go test 7 | go build 8 | ./skarn \ 9 | -------------------------------------------------------------------------------- /statik/statik.go: -------------------------------------------------------------------------------- 1 | // Code generated by statik. DO NOT EDIT. 2 | 3 | // Package statik contains static assets. 4 | package statik 5 | -------------------------------------------------------------------------------- /structs.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | oauth2 "github.com/nektro/go.oauth2" 5 | ) 6 | 7 | type Config struct { 8 | Port int `json:"port"` 9 | Clients []oauth2.AppConf `json:"clients"` 10 | Providers []oauth2.Provider `json:"providers"` 11 | Themes []string `json:"themes"` 12 | Members []string `json:"members"` 13 | Admins []string `json:"admins"` 14 | AnnounceURL string `json:"announce_webhook_url"` 15 | } 16 | 17 | type User struct { 18 | ID int `json:"id"` 19 | Snowflake string `json:"snowflake" sqlite:"text"` 20 | JoinedOn string `json:"joined_on" sqlite:"text"` 21 | IsMember bool `json:"is_member" sqlite:"tinyint(1)"` 22 | IsAdmin bool `json:"is_admin" sqlite:"tinyint(1)"` 23 | Username string `json:"username" sqlite:"text"` 24 | Nickname string `json:"nickname" sqlite:"text"` 25 | Avatar string `json:"avatar" sqlite:"text"` 26 | RealName string `json:"name"` 27 | } 28 | 29 | type UserComplete struct { 30 | U User `json:"user"` 31 | Fills int `json:"fills"` 32 | PointsF int `json:"points"` 33 | Requests int `json:"requests"` 34 | PointsR int `json:"points_r"` 35 | } 36 | 37 | type Request struct { 38 | ID int `json:"id"` 39 | Owner int `json:"owner" sqlite:"int"` 40 | Category string `json:"category" sqlite:"text"` 41 | AddedOn string `json:"added_on" sqlite:"text"` 42 | Title string `json:"title" sqlite:"text"` 43 | QualityRaw string `json:"quality" sqlite:"text"` 44 | Quality []string `json:"quality_real"` 45 | Link string `json:"link" sqlite:"text"` 46 | Description string `json:"description" sqlite:"text"` 47 | Points int `json:"points" sqlite:"int"` 48 | Filled bool `json:"filled"` 49 | Filler int `json:"filler" sqlite:"int"` 50 | FilledOn string `json:"filled_on" sqlite:"text"` 51 | Response string `json:"response" sqlite:"text"` 52 | } 53 | 54 | type CategoryMapValue struct { 55 | Name string `json:"name"` 56 | Icon string `json:"icon"` 57 | Quality []string `json:"quality"` 58 | } 59 | -------------------------------------------------------------------------------- /www/_header.hbs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | {{title}} 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 26 | 27 | 28 | 35 |
    36 |

    Media Requests

    37 | 46 | -------------------------------------------------------------------------------- /www/all_users.hbs: -------------------------------------------------------------------------------- 1 |
    2 |

    All Users

    3 |

    Here is the list of every user.

    4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | {{#each data.users}} 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | {{/each}} 30 | 31 |
    IDSnowflakeJoinedOnMember?Admin?UsernameNicknameAvatar
    {{ID}}{{Snowflake}}{{JoinedOn}}{{Username}}{{Nickname}}
    32 |
    33 |
    34 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /www/categories.json: -------------------------------------------------------------------------------- 1 | { 2 | "lit": { 3 | "name": "Book", 4 | "icon": "book", 5 | "quality": ["Any",".pdf",".epub",".mobi",".cbr","Other"] 6 | }, 7 | "mov": { 8 | "name": "Video", 9 | "icon": "film", 10 | "quality": [ 11 | "Any", 12 | "480p","720p","1080p","1440p","2160p","4320p", 13 | "x264","x265","vp8","vp9","AV1", 14 | "REMUX","ISO","VHSRip","DVDRip","BDRip", 15 | "Other" 16 | ] 17 | }, 18 | "mus": { 19 | "name": "Music", 20 | "icon": "music", 21 | "quality": ["Any",".flac",".mp3","Other"] 22 | }, 23 | "exe": { 24 | "name": "Program", 25 | "icon": "code", 26 | "quality": ["Any","Windows","macOS","Linux","Android","ROM","Other"] 27 | }, 28 | "xxx": { 29 | "name": "NSFW", 30 | "icon": "venus-mars", 31 | "quality": ["Any","Other"] 32 | }, 33 | "etc": { 34 | "name": "Unknown", 35 | "icon": "question", 36 | "quality": ["Any","Other"] 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /www/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Welcome to Skarn 8 | 9 | 10 | 11 | 12 | 13 | 16 | 17 | 18 | 21 |
    22 |

    Welcome to Skarn

    23 |

    The media request system.

    24 | Explore the Requests 25 |
    26 | 27 | 28 | -------------------------------------------------------------------------------- /www/leaderboard.hbs: -------------------------------------------------------------------------------- 1 |
    2 |

    Leaderboard

    3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | {{#each data.users}} 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | {{/each}} 23 | 24 |
    IDNameFillsRequests
    {{U.ID}}{{U.RealName}}{{Fills}}{{Requests}}
    25 |
    26 | 27 | 33 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /www/new.hbs: -------------------------------------------------------------------------------- 1 |
    2 | {{#equal page "new"}} 3 |

    New Request

    4 |

    Here you can create a new request.

    5 |
    6 | {{/equal}} 7 | {{#equal page "edit"}} 8 |

    Edit Request

    9 |

    Here you can update an existing request.

    10 | 11 | {{/equal}} 12 |
    13 | 14 | 19 |
    20 |
    21 | 22 | 23 |
    24 |
    25 | 26 | 27 |
    28 | {{#each data.categories}} 29 | 42 | {{/each}} 43 |
    44 | 45 | 46 |
    47 | 48 | 49 |
    50 |
    51 | 52 |

    53 | 56 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /www/requests.hbs: -------------------------------------------------------------------------------- 1 |
    2 | All Requests 3 | All (Open) 4 | All (Filled) 5 | Mine (Open) 6 | Mine (Filled) 7 | Filled by Me 8 |

    {{title}}

    9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | {{#each data.requests}} 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | {{/each}} 41 | 42 |
    TitleQualityReferenceRequesterFillerAdded OnFilled OnFillEditUnfillDelete
    {{Title}}
    {{Description}}

    {{Response}}
    {{#each Quality}}
    {{quality Category this}}
    {{/each}}
    {{domain Link}} {{name Owner}}{{name Filler}}{{AddedOn}}{{FilledOn}}{{#unless Filled}}{{/unless}}{{#equal Owner user.ID}}{{/equal}}{{#equal Owner user.ID}}{{#if Filled}}{{/if}}{{/equal}}{{#equal Owner user.ID}}{{/equal}}
    43 |
    44 | 45 | 55 | 155 | 156 | 157 | -------------------------------------------------------------------------------- /www/response.hbs: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | {{title}} 8 | 9 | 10 | 11 | 12 | 13 | 18 |
    19 |
    20 |

    {{title}}

    21 |

    {{message}}

    22 |

    {{{link}}}

    23 |
    24 | 25 | 26 | -------------------------------------------------------------------------------- /www/stats.hbs: -------------------------------------------------------------------------------- 1 |
    2 |

    Statistics

    3 |

    View reports on requests and fills.

    4 | 5 |
    6 | 7 |

    8 | 9 | 13 | 14 | 15 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /www/style.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nektro/skarn/bf81a91780aa33f9e4f992e7da9a0defba480313/www/style.css --------------------------------------------------------------------------------