40 |
41 |
--------------------------------------------------------------------------------
/commons/seed/seed.go:
--------------------------------------------------------------------------------
1 | package seed
2 |
3 | import (
4 | "embed"
5 | "encoding/csv"
6 | "io"
7 | "math/rand"
8 | "mouji/features/pageviews"
9 | "mouji/features/projects"
10 | "mouji/features/users"
11 | )
12 |
13 | func SeedUsers(resources embed.FS) {
14 | rows := readCSV(resources, "commons/seed/users.csv")
15 | for i, row := range rows {
16 | if i == 0 {
17 | continue
18 | }
19 |
20 | email := row[0]
21 | passwordHash, _ := users.HashPassword(row[1])
22 | isAdmin := row[2] == "true"
23 |
24 | users.InsertUser(email, passwordHash, isAdmin)
25 | }
26 | }
27 |
28 | func SeedProjects(resources embed.FS) {
29 | rows := readCSV(resources, "commons/seed/projects.csv")
30 | for i, row := range rows {
31 | if i == 0 {
32 | continue
33 | }
34 |
35 | name := row[0]
36 | baseURL := row[1]
37 |
38 | projects.InsertProject(name, baseURL)
39 | }
40 | }
41 |
42 | func SeedPageViews(resources embed.FS) {
43 | projects := projects.GetAllProjects()
44 | projectNameToIDMap := make(map[string]string)
45 |
46 | for _, project := range projects {
47 | projectNameToIDMap[project.Name] = project.ProjectID
48 | }
49 |
50 | rows := readCSV(resources, "commons/seed/pageviews.csv")
51 | for i, row := range rows {
52 | if i == 0 {
53 | continue
54 | }
55 |
56 | randomViewCount := rand.Intn(50)
57 | for i := 0; i <= randomViewCount; i++ {
58 | pageviews.InsertPageView(pageviews.PageViewRecord{
59 | ProjectID: projectNameToIDMap[row[0]],
60 | Path: row[1],
61 | Title: row[2],
62 | Referrer: row[3],
63 | })
64 | }
65 | }
66 | }
67 |
68 | func readCSV(resources embed.FS, path string) [][]string {
69 | file, err := embed.FS.Open(resources, path)
70 |
71 | defer file.Close()
72 |
73 | if err != nil {
74 | panic(err)
75 | }
76 |
77 | csvReader := csv.NewReader(file)
78 |
79 | var rows [][]string
80 | for {
81 | row, err := csvReader.Read()
82 |
83 | if err == io.EOF {
84 | break
85 | }
86 |
87 | if err != nil {
88 | panic(err)
89 | }
90 |
91 | rows = append(rows, row)
92 | }
93 |
94 | return rows
95 | }
96 |
--------------------------------------------------------------------------------
/features/pageviews/collect.go:
--------------------------------------------------------------------------------
1 | package pageviews
2 |
3 | import (
4 | "crypto/sha256"
5 | "fmt"
6 | "net/http"
7 | "net/url"
8 | "strings"
9 | "time"
10 | )
11 |
12 | func HandleCollect(w http.ResponseWriter, r *http.Request) {
13 | var record PageViewRecord
14 |
15 | projectID := r.URL.Query().Get("project_id")
16 | path := r.URL.Query().Get("path")
17 | title := r.URL.Query().Get("title")
18 | referrer := r.URL.Query().Get("referrer")
19 | userAgent := r.Header.Get("User-Agent")
20 | ipAddress := r.RemoteAddr
21 |
22 | visitorHash := generateVisitorHash(projectID, ipAddress, userAgent)
23 |
24 | normalizedPath, err := normalizePath(path)
25 | if err != nil {
26 | http.Error(w, err.Error(), http.StatusBadRequest)
27 | return
28 | }
29 |
30 | record = PageViewRecord{
31 | ProjectID: projectID,
32 | Path: normalizedPath,
33 | Title: title,
34 | Referrer: referrer,
35 | VisitorHash: visitorHash,
36 | UserAgent: userAgent,
37 | }
38 |
39 | err = InsertPageView(record)
40 | if err != nil {
41 | http.Error(w, err.Error(), http.StatusInternalServerError)
42 | return
43 | }
44 | }
45 |
46 | func normalizePath(rawURL string) (string, error) {
47 | parsedURL, err := url.Parse(rawURL)
48 | defaultPath := "/"
49 |
50 | if err != nil {
51 | return defaultPath, err
52 | }
53 |
54 | var normalizedPath string
55 |
56 | if strings.TrimSpace(parsedURL.Path) == "" {
57 | normalizedPath = defaultPath
58 | } else {
59 | normalizedPath = parsedURL.Path
60 | }
61 |
62 | return normalizedPath, nil
63 | }
64 |
65 | // Generates a transient visitor hash that rotates daily
66 | // hash(daily_salt + website_domain + ip_address + user_agent)
67 | // https://news.ycombinator.com/item?id=24696768
68 | func generateVisitorHash(projectID string, ipAddress string, userAgent string) string {
69 |
70 | dailySalt := time.Now().Format("2006-01-02")
71 |
72 | // https://gobyexample.com/sha256-hashes
73 | hash := sha256.New()
74 | hash.Write([]byte(dailySalt + projectID + ipAddress + userAgent))
75 | visitorHash := fmt.Sprintf("%x", hash.Sum(nil))
76 |
77 | return visitorHash
78 | }
79 |
--------------------------------------------------------------------------------
/features/users/users_model.go:
--------------------------------------------------------------------------------
1 | package users
2 |
3 | import (
4 | "database/sql"
5 | "errors"
6 | "fmt"
7 | "log/slog"
8 | "mouji/commons/sqlite"
9 | )
10 |
11 | type UserRecord struct {
12 | UserID string
13 | Email string
14 | Password string
15 | }
16 |
17 | func HasUsers() bool {
18 | query := "SELECT user_id FROM users LIMIT 1"
19 | var userID string
20 |
21 | row := sqlite.DB.QueryRow(query)
22 | err := row.Scan(&userID)
23 | if errors.Is(err, sql.ErrNoRows) {
24 | return false
25 | }
26 | if err != nil {
27 | err = fmt.Errorf("error retrieving users: %w", err)
28 | panic(err)
29 | }
30 |
31 | return true
32 | }
33 |
34 | func GetUserByEmail(email string) (UserRecord, error) {
35 | var user UserRecord
36 |
37 | query := "SELECT user_id, email, password_hash FROM users where email = ?"
38 |
39 | row := sqlite.DB.QueryRow(query, email)
40 | err := row.Scan(&user.UserID, &user.Email, &user.Password)
41 | if err != nil {
42 | err = fmt.Errorf("error retrieving user: %w", err)
43 | slog.Error(err.Error())
44 | return user, err
45 | }
46 |
47 | return user, nil
48 | }
49 |
50 | func GetUserByID(userID string) (UserRecord, error) {
51 | var user UserRecord
52 |
53 | query := "SELECT user_id, email, password_hash FROM users where user_id = ?"
54 |
55 | row := sqlite.DB.QueryRow(query, userID)
56 | err := row.Scan(&user.UserID, &user.Email, &user.Password)
57 | if err != nil {
58 | err = fmt.Errorf("error retrieving user: %w", err)
59 | slog.Error(err.Error())
60 | return user, err
61 | }
62 |
63 | return user, nil
64 | }
65 |
66 | func InsertUser(email string, passwordHash string, isAdmin bool) (UserRecord, error) {
67 | var user UserRecord
68 |
69 | query := "INSERT INTO users (email, password_hash, is_admin) VALUES (?, ?, ?) RETURNING user_id, email, password_hash"
70 |
71 | row := sqlite.DB.QueryRow(query, email, passwordHash, isAdmin)
72 | err := row.Scan(&user.UserID, &user.Email, &user.Password)
73 |
74 | if err != nil {
75 | err = fmt.Errorf("error inserting user: %w", err)
76 | slog.Error(err.Error())
77 | return user, err
78 | }
79 |
80 | return user, nil
81 | }
82 |
83 | func UpdatePassword(userID, passwordHash string) error {
84 | query := "UPDATE users SET password_hash = ? WHERE user_id = ?"
85 |
86 | _, err := sqlite.DB.Exec(query, passwordHash, userID)
87 | if err != nil {
88 | err = fmt.Errorf("error updating password: %w", err)
89 | slog.Error(err.Error())
90 | return err
91 | }
92 |
93 | return nil
94 | }
95 |
--------------------------------------------------------------------------------
/features/login/login.go:
--------------------------------------------------------------------------------
1 | package login
2 |
3 | import (
4 | "database/sql"
5 | "errors"
6 | "fmt"
7 | "mouji/commons/components"
8 | "mouji/commons/session"
9 | "mouji/commons/templates"
10 | "mouji/features/users"
11 | "net/http"
12 | )
13 |
14 | func HandleLoginPage(w http.ResponseWriter, r *http.Request) {
15 | email := ""
16 | emailError := ""
17 | passwordError := ""
18 |
19 | renderLoginForm(w, email, emailError, passwordError)
20 | }
21 |
22 | func HandleLoginSubmit(w http.ResponseWriter, r *http.Request) {
23 | err := r.ParseForm()
24 | if err != nil {
25 | err = fmt.Errorf("error parsing form: %w", err)
26 | http.Error(w, err.Error(), http.StatusBadRequest)
27 | return
28 | }
29 |
30 | email := r.Form.Get("email")
31 | password := r.Form.Get("password")
32 | emailError := ""
33 | passwordError := ""
34 |
35 | user, err := users.GetUserByEmail(email)
36 |
37 | if err != nil {
38 | if errors.Is(err, sql.ErrNoRows) {
39 | emailError = "Email address does not exist"
40 | } else {
41 | http.Error(w, err.Error(), http.StatusInternalServerError)
42 | return
43 | }
44 | }
45 |
46 | if !users.IsValidPassword(password, user.Password) {
47 | passwordError = "Password is incorrect"
48 | }
49 |
50 | if emailError != "" || passwordError != "" {
51 | renderLoginForm(w, email, emailError, passwordError)
52 | return
53 | }
54 |
55 | sess, err := session.NewSession(user.UserID)
56 | if err != nil {
57 | http.Error(w, err.Error(), http.StatusInternalServerError)
58 | return
59 | }
60 | session.SetSessionCookie(w, sess)
61 |
62 | http.Redirect(w, r, "/", http.StatusSeeOther)
63 | }
64 |
65 | func renderLoginForm(w http.ResponseWriter, email string, emailError string, passwordError string) {
66 | type templateData struct {
67 | Navbar components.Navbar
68 | EmailInput components.Input
69 | PasswordInput components.Input
70 | SubmitButton components.Button
71 | }
72 |
73 | tmplData := templateData{
74 | Navbar: components.NewNavbar(false),
75 | EmailInput: components.Input{
76 | ID: "email",
77 | Label: "Email",
78 | Type: "email",
79 | Placeholder: "Enter your email address",
80 | Error: emailError,
81 | Value: email,
82 | },
83 | PasswordInput: components.Input{
84 | ID: "password",
85 | Label: "Password",
86 | Type: "password",
87 | Placeholder: "Enter your password",
88 | Error: passwordError,
89 | },
90 | SubmitButton: components.Button{
91 | Text: "Login",
92 | Icon: "arrow-right",
93 | IsSubmit: true,
94 | IsPrimary: true,
95 | },
96 | }
97 |
98 | templates.Render(w, "login.html", tmplData)
99 | }
100 |
--------------------------------------------------------------------------------
/assets/index.js:
--------------------------------------------------------------------------------
1 | document.addEventListener('DOMContentLoaded', () => {
2 | initBarChart();
3 | initDropdown();
4 | });
5 |
6 | function initBarChart() {
7 | const tooltip = document.querySelector('.tooltip');
8 | const tooltipLabel = document.querySelector('.tooltip > .label');
9 | const tooltipValue = document.querySelector('.tooltip > .value');
10 | const bars = document.querySelectorAll('.bar');
11 |
12 | bars.forEach(bar => {
13 | bar.addEventListener('mousemove', (e) => {
14 | tooltipLabel.textContent = bar.getAttribute('data-label');
15 | tooltipValue.textContent = `${bar.getAttribute('data-value')} views`;
16 | tooltip.style.display = 'flex';
17 |
18 | const barRect = bar.getBoundingClientRect();
19 | const tooltipRect = tooltip.getBoundingClientRect();
20 |
21 | const tooltipHeight = tooltipRect.height;
22 | const tooltipWidth = tooltipRect.width;
23 |
24 | const topY = barRect.top + window.scrollY; // https://stackoverflow.com/q/41576287
25 | let tooltipLeft = barRect.x + (barRect.width / 2) - (tooltipWidth / 2);
26 | if (tooltipLeft + tooltipWidth > window.innerWidth) { // https://o7planning.org/12397/javascript-window
27 | tooltipLeft = barRect.right - tooltipWidth;
28 | } else if (tooltipLeft < 0) {
29 | tooltipLeft = barRect.left;
30 | }
31 | tooltip.style.left = `${tooltipLeft}px`;
32 | tooltip.style.top = `${topY - tooltipHeight - 5}px`;
33 | });
34 |
35 | bar.addEventListener('mouseleave', () => {
36 | tooltip.style.display = 'none';
37 | });
38 | });
39 | }
40 |
41 | function initDropdown() {
42 | const dropdowns = document.querySelectorAll('.dropdown-container');
43 | dropdowns.forEach(el => {
44 | el.addEventListener('click', (e) => {
45 | if (e.target.closest('.dropdown-button')) {
46 | e.preventDefault(); // Prevent form submission
47 | el.classList.add('open');
48 | } else if (e.target.closest('span.dropdown-option')) {
49 | e.preventDefault(); // Prevent form submission
50 | el.querySelector("#dropdown-hidden-input").value = e.target.dataset.value;
51 | el.querySelector(".dropdown-selected-option").textContent = e.target.dataset.name;
52 | el.classList.remove('open');
53 | }
54 | });
55 | });
56 | }
57 |
58 | document.addEventListener('click', (e) => {
59 | if (e.target.closest('.dropdown-container')) {
60 | return;
61 | }
62 |
63 | const dropdowns = document.querySelectorAll('.dropdown-container.open');
64 | dropdowns.forEach(el => el.classList.remove('open'));
65 | });
--------------------------------------------------------------------------------
/commons/seed/pageviews.csv:
--------------------------------------------------------------------------------
1 | project_name,path,title,referrer
2 | Blog,/posts/fastapi-structured-json-logging/,Structured JSON Logging using FastAPI,https://www.google.com
3 | Blog,/posts/rust-module-system/,Clear explanation of Rust’s module system,https://www.google.com
4 | Blog,/posts/thoughts-on-the-future-of-software-development/,Thoughts on the Future of Software Development,https://www.google.com
5 | Blog,/posts/rust-error-handling/,"Beginner's guide to Error Handling in Rust",https://www.google.com
6 | Blog,/posts/nginx-caching-proxy/,Make your backend more reliable using Nginx caching proxy,https://www.google.com
7 | Blog,/posts/rust-wasm-yew-single-page-application/,Single Page Applications using Rust,https://www.google.com
8 | Blog,/posts/exploring-singapore-onemap-api/,Exploring Singapore’s OneMap API,https://www.google.com
9 | Blog,/posts/system-wide-text-summarization-using-ollama-and-applescript/,System-wide text summarization using Ollama and AppleScript,https://www.google.com
10 | Blog,/posts/why-use-azure-openai-when-you-have-openai/,Why use Azure OpenAI when you have OpenAI?,https://www.google.com
11 | Blog,/posts/rust-for-javascript-developers-pattern-matching-and-enums/,Rust for JavaScript Developers - Pattern Matching and Enums,https://www.github.com
12 | Blog,/tags/Rust-Beginners/,"Shesh's blog",https://www.github.com
13 | Blog,/posts/automatic-pageview-tracking-using-react-router/,Automatic PageView Tracking using React Router,https://www.github.com
14 | Blog,/posts/running-express-over-https-in-localhost/,Running Express over HTTPS in localhost,https://www.github.com
15 | Blog,/posts/taurus-writing-jmeter-load-tests-as-code/,Taurus: Writing JMeter Load Tests As Code,https://www.github.com
16 | Blog,/posts/analyzing-slow-python-code-using-cprofile/,Analyzing Slow Python Code using cProfile,https://www.github.com
17 | Blog,/posts/blocking-usage-of-the-any-type-in-typescript-codebases/,Blocking usage of the any type in TypeScript codebases,https://www.google.com
18 | Blog,/posts/rust-for-javascript-developers-functions-and-control-flow/,Rust for JavaScript Developers - Functions and Control Flow,https://www.google.com
19 | Blog,/posts/measuring-response-times-of-express-route-handlers/,Measuring response times of Express route handlers,https://www.google.com
20 | Blog,/posts/minimal-viable-search-using-postgres/,Minimal Viable Search using Postgres,https://www.google.com
21 | Blog,/posts/packaging-node-js-code-into-cross-platform-executables/,Packaging Node.js code into cross platform executables,https://www.google.com
22 | Blog,/posts/publishing-npx-command-to-npm/,Publishing an npx command to npm,https://www.google.com
23 | Blog,/posts/rust-for-javascript-developers-variables-and-data-types/,Rust for JavaScript Developers - Variables and Data Types,https://www.google.com
24 | Blog,/posts/using-optimizely-with-react/,Using Optimizely with React,https://www.google.com
25 | Blog,/posts/visual-explanation-of-saml-authentication/,Visual explanation of SAML authentication,https://www.google.com
--------------------------------------------------------------------------------
/commons/session/session.go:
--------------------------------------------------------------------------------
1 | package session
2 |
3 | import (
4 | "database/sql"
5 | "errors"
6 | "fmt"
7 | "log/slog"
8 | "mouji/commons/sqlite"
9 | "net/http"
10 | "time"
11 | )
12 |
13 | var sessionLength = time.Hour * 24 * 7 // 7 days
14 | var expiresAtFormat = "2006-01-02T15:04:05-07:00"
15 |
16 | type SessionRecord struct {
17 | SessionID string
18 | UserID string
19 | ExpiresAt time.Time
20 | }
21 |
22 | func NewSession(userID string) (SessionRecord, error) {
23 | expiresAt := time.Now().Add(sessionLength)
24 |
25 | var session SessionRecord
26 | var expiresAtString string
27 |
28 | query := "INSERT INTO sessions (session_id, user_id, expires_at) VALUES (LOWER(HEX(RANDOMBLOB (16))), ?, ?) RETURNING session_id, user_id, expires_at"
29 |
30 | row := sqlite.DB.QueryRow(query, userID, expiresAt.Format(expiresAtFormat))
31 | err := row.Scan(&session.SessionID, &session.UserID, &expiresAtString)
32 |
33 | if err != nil {
34 | err = fmt.Errorf("error retrieving sessions: %w", err)
35 | slog.Error(err.Error())
36 | return session, err
37 | }
38 |
39 | session.ExpiresAt, err = time.Parse(expiresAtFormat, expiresAtString)
40 |
41 | if err != nil {
42 | err = fmt.Errorf("error parsing session expiry: %w", err)
43 | slog.Error(err.Error())
44 | return session, err
45 | }
46 |
47 | return session, nil
48 | }
49 |
50 | func SetSessionCookie(w http.ResponseWriter, session SessionRecord) {
51 | cookies := http.Cookie{Name: "session_token", Value: session.SessionID, Expires: session.ExpiresAt, Path: "/"}
52 | http.SetCookie(w, &cookies)
53 | }
54 |
55 | func IsValidSession(sessionID string) bool {
56 | query := "SELECT expires_at FROM sessions WHERE session_id = ?"
57 | var expiresAtString string
58 |
59 | row := sqlite.DB.QueryRow(query, sessionID)
60 | err := row.Scan(&expiresAtString)
61 |
62 | if errors.Is(err, sql.ErrNoRows) {
63 | return false
64 | }
65 |
66 | if err != nil {
67 | slog.Error("error retrieving sessions", "error", err)
68 | return false
69 | }
70 |
71 | expiresAt, err := time.Parse(expiresAtFormat, expiresAtString)
72 |
73 | if err != nil {
74 | slog.Error("error parsing session expiry", "error", err)
75 | return false
76 | }
77 |
78 | if expiresAt.Before(time.Now()) {
79 | return false
80 | }
81 |
82 | return true
83 | }
84 |
85 | func GetUserID(sessionID string) (string, error) {
86 | query := "SELECT user_id FROM sessions WHERE session_id = ?"
87 | var userID string
88 |
89 | row := sqlite.DB.QueryRow(query, sessionID)
90 | err := row.Scan(&userID)
91 |
92 | if err != nil {
93 | err = fmt.Errorf("error retrieving user_id: %w", err)
94 | slog.Error(err.Error())
95 | return "", err
96 | }
97 |
98 | return userID, nil
99 | }
100 |
101 | func DeleteExpiredSessions() {
102 | query := "DELETE FROM sessions WHERE expires_at < ?"
103 | _, err := sqlite.DB.Exec(query, time.Now().Format(expiresAtFormat))
104 |
105 | if err != nil {
106 | slog.Error("error deleting expired sessions", "error", err)
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "embed"
5 | "log/slog"
6 | "mouji/commons/auth"
7 | "mouji/commons/session"
8 | "mouji/commons/sqlite"
9 | "mouji/commons/templates"
10 | "mouji/features/home"
11 | "mouji/features/login"
12 | "mouji/features/pageviews"
13 | "mouji/features/projects"
14 | "mouji/features/settings"
15 | "mouji/features/users"
16 | "net/http"
17 | "os"
18 | "strings"
19 | "time"
20 | )
21 |
22 | //go:embed all:commons all:features
23 | var resources embed.FS
24 |
25 | //go:embed assets/*
26 | var assets embed.FS
27 |
28 | //go:embed migrations/*.sql
29 | var migrations embed.FS
30 |
31 | func main() {
32 | defer func() {
33 | if r := recover(); r != nil {
34 | slog.Error("killing server", "error", r)
35 | os.Exit(1)
36 | }
37 | }()
38 |
39 | sqlite.NewDB()
40 | defer sqlite.DB.Close()
41 |
42 | sqlite.Migrate(migrations)
43 |
44 | templates.NewTemplates(resources)
45 |
46 | go runBackgroundTasks()
47 |
48 | port := os.Getenv("PORT")
49 | if port == "" {
50 | port = "8080"
51 | }
52 | port = ":" + port
53 |
54 | slog.Info("starting server", "port", port)
55 | err := http.ListenAndServe(port, newRouter())
56 | if err != nil {
57 | panic(err)
58 | }
59 | }
60 |
61 | func newRouter() *http.ServeMux {
62 | mux := http.NewServeMux()
63 |
64 | // public
65 | mux.HandleFunc("GET /assets/", handleStaticAssets)
66 | mux.HandleFunc("GET /collect", pageviews.HandleCollect)
67 | mux.HandleFunc("GET /login", login.HandleLoginPage)
68 | mux.HandleFunc("POST /login", login.HandleLoginSubmit)
69 |
70 | // private
71 | addPrivateRoute(mux, "GET /", home.HandleHomePage)
72 | addPrivateRoute(mux, "GET /settings", settings.HandleSettingsPage)
73 | addPrivateRoute(mux, "GET /settings/server_url", settings.HandleServerURLPage)
74 | addPrivateRoute(mux, "POST /settings/server_url", settings.HandleServerURLSubmit)
75 | addPrivateRoute(mux, "GET /users/new", users.HandleNewUserPage)
76 | addPrivateRoute(mux, "POST /users/new", users.HandleNewUserSubmit)
77 | addPrivateRoute(mux, "GET /users/me/password", users.HandleChangePasswordPage)
78 | addPrivateRoute(mux, "POST /users/me/password", users.HandleChangePasswordSubmit)
79 | addPrivateRoute(mux, "GET /projects/new", projects.HandleNewProjectPage)
80 | addPrivateRoute(mux, "GET /projects/{project_id}", projects.HandleEditProjectPage)
81 | addPrivateRoute(mux, "POST /projects/", projects.HandleProjectDetailSubmit)
82 | addPrivateRoute(mux, "POST /projects/{project_id}", projects.HandleProjectDetailSubmit)
83 |
84 | return mux
85 | }
86 |
87 | func handleStaticAssets(w http.ResponseWriter, r *http.Request) {
88 | if strings.HasSuffix(r.URL.Path, ".woff2") {
89 | w.Header().Set("Cache-Control", "public, max-age=31536000") // 1 year
90 | }
91 |
92 | http.FileServer(http.FS(assets)).ServeHTTP(w, r)
93 | }
94 |
95 | func addPrivateRoute(mux *http.ServeMux, pattern string, handlerFunc func(w http.ResponseWriter, r *http.Request)) {
96 | handler := http.HandlerFunc(handlerFunc)
97 | mux.HandleFunc(pattern, auth.EnsureAuthenticated(handler))
98 | }
99 |
100 | func runBackgroundTasks() {
101 | for range time.Tick(24 * time.Hour) {
102 | session.DeleteExpiredSessions()
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/features/projects/projects_model.go:
--------------------------------------------------------------------------------
1 | package projects
2 |
3 | import (
4 | "database/sql"
5 | "errors"
6 | "fmt"
7 | "log/slog"
8 | "mouji/commons/sqlite"
9 | )
10 |
11 | type ProjectRecord struct {
12 | ProjectID string
13 | Name string
14 | BaseURL string
15 | }
16 |
17 | func HasProjects() bool {
18 | query := "SELECT project_id FROM projects LIMIT 1"
19 | var projectID string
20 |
21 | row := sqlite.DB.QueryRow(query)
22 | err := row.Scan(&projectID)
23 | if errors.Is(err, sql.ErrNoRows) {
24 | return false
25 | }
26 | if err != nil {
27 | err = fmt.Errorf("error retrieving projects: %w", err)
28 | panic(err)
29 | }
30 |
31 | return true
32 | }
33 |
34 | func GetAllProjects() []ProjectRecord {
35 | var projects []ProjectRecord
36 | query := "SELECT project_id, name, base_url FROM projects ORDER BY created_at DESC"
37 |
38 | rows, err := sqlite.DB.Query(query)
39 | defer rows.Close()
40 |
41 | if err != nil {
42 | err = fmt.Errorf("error retrieving projects: %w", err)
43 | panic(err)
44 | }
45 |
46 | for rows.Next() {
47 | var project ProjectRecord
48 | err = rows.Scan(&project.ProjectID, &project.Name, &project.BaseURL)
49 | if err != nil {
50 | err = fmt.Errorf("error retrieving projects: %w", err)
51 | panic(err)
52 | }
53 | projects = append(projects, project)
54 | }
55 |
56 | return projects
57 | }
58 |
59 | func getProjectByID(projectID string) (ProjectRecord, error) {
60 | var project ProjectRecord
61 |
62 | query := "SELECT project_id, name, base_url FROM projects where project_id = ?"
63 |
64 | row := sqlite.DB.QueryRow(query, projectID)
65 | err := row.Scan(&project.ProjectID, &project.Name, &project.BaseURL)
66 | if err != nil {
67 | err = fmt.Errorf("error retrieving project: %w", err)
68 | slog.Error(err.Error())
69 | return project, err
70 | }
71 |
72 | return project, nil
73 | }
74 |
75 | func InsertProject(projectName string, serverBaseURL string) (ProjectRecord, error) {
76 | var project ProjectRecord
77 |
78 | query := `
79 | INSERT INTO projects (
80 | project_id,
81 | name,
82 | base_url
83 | )
84 | VALUES(
85 | LOWER(HEX(RANDOMBLOB (16))),
86 | ?,
87 | ?
88 | )
89 | RETURNING
90 | project_id,
91 | name,
92 | base_url`
93 |
94 | row := sqlite.DB.QueryRow(query, projectName, serverBaseURL)
95 | err := row.Scan(&project.ProjectID, &project.Name, &project.BaseURL)
96 | if err != nil {
97 | err = fmt.Errorf("error inserting project: %w", err)
98 | slog.Error(err.Error())
99 | return project, err
100 | }
101 |
102 | return project, nil
103 | }
104 |
105 | func updateProject(projectID string, projectName string, serverBaseURL string) (ProjectRecord, error) {
106 | var project ProjectRecord
107 |
108 | query := `
109 | UPDATE projects
110 | SET
111 | name = ?,
112 | base_url = ?,
113 | updated_at = CURRENT_TIMESTAMP
114 | WHERE
115 | project_id = ?
116 | RETURNING
117 | project_id,
118 | name,
119 | base_url
120 | `
121 |
122 | row := sqlite.DB.QueryRow(query, projectName, serverBaseURL, projectID)
123 | err := row.Scan(&project.ProjectID, &project.Name, &project.BaseURL)
124 | if err != nil {
125 | err = fmt.Errorf("error updating project: %w", err)
126 | slog.Error(err.Error())
127 | return project, err
128 | }
129 |
130 | return project, nil
131 | }
132 |
--------------------------------------------------------------------------------
/commons/components/button.html:
--------------------------------------------------------------------------------
1 | {{define "button"}}
2 |
30 | {{end}}
--------------------------------------------------------------------------------
/features/users/password_change.go:
--------------------------------------------------------------------------------
1 | package users
2 |
3 | import (
4 | "database/sql"
5 | "errors"
6 | "fmt"
7 | "mouji/commons/components"
8 | "mouji/commons/session"
9 | "mouji/commons/templates"
10 | "net/http"
11 | )
12 |
13 | func HandleChangePasswordPage(w http.ResponseWriter, r *http.Request) {
14 | oldPassword := ""
15 | newPassword := ""
16 | oldPasswordError := ""
17 | newPasswordError := ""
18 | renderChangePasswordPage(w, oldPassword, newPassword, oldPasswordError, newPasswordError)
19 | }
20 |
21 | func HandleChangePasswordSubmit(w http.ResponseWriter, r *http.Request) {
22 | err := r.ParseForm()
23 | if err != nil {
24 | err = fmt.Errorf("error parsing form: %w", err)
25 | http.Error(w, err.Error(), http.StatusBadRequest)
26 | return
27 | }
28 |
29 | cookie, err := r.Cookie("session_token")
30 | oldPassword := r.Form.Get("old_password")
31 | newPassword := r.Form.Get("new_password")
32 |
33 | oldPasswordError := ""
34 | newPasswordError := ""
35 |
36 | if err != nil && errors.Is(err, http.ErrNoCookie) {
37 | http.Redirect(w, r, "/login", http.StatusSeeOther)
38 | return
39 | }
40 |
41 | sessionID := cookie.Value
42 | userID, err := session.GetUserID(sessionID)
43 |
44 | if err != nil && errors.Is(err, sql.ErrNoRows) {
45 | http.Redirect(w, r, "/login", http.StatusSeeOther)
46 | return
47 | }
48 |
49 | user, err := GetUserByID(userID)
50 |
51 | if err != nil && errors.Is(err, sql.ErrNoRows) {
52 | http.Redirect(w, r, "/login", http.StatusSeeOther)
53 | return
54 | }
55 |
56 | if !IsValidPassword(oldPassword, user.Password) {
57 | oldPasswordError = "Old password is incorrect"
58 | renderChangePasswordPage(w, oldPassword, newPassword, oldPasswordError, newPasswordError)
59 | return
60 | }
61 |
62 | if oldPassword == newPassword {
63 | newPasswordError = "New password should be different from old password"
64 | renderChangePasswordPage(w, oldPassword, newPassword, oldPasswordError, newPasswordError)
65 | return
66 | }
67 |
68 | passwordHash, err := HashPassword(newPassword)
69 | if err != nil {
70 | err = fmt.Errorf("error hashing password: %w", err)
71 | http.Error(w, err.Error(), http.StatusInternalServerError)
72 | return
73 | }
74 |
75 | err = UpdatePassword(userID, passwordHash)
76 | if err != nil {
77 | err = fmt.Errorf("error updating password: %w", err)
78 | http.Error(w, err.Error(), http.StatusInternalServerError)
79 | return
80 | }
81 |
82 | http.Redirect(w, r, "/settings", http.StatusSeeOther)
83 | }
84 |
85 | func renderChangePasswordPage(w http.ResponseWriter, oldPassword, newPassword, oldPasswordError, newPasswordError string) {
86 | type templateData struct {
87 | Navbar components.Navbar
88 | OldPasswordInput components.Input
89 | NewPasswordInput components.Input
90 | SubmitButton components.Button
91 | }
92 |
93 | tmplData := templateData{
94 | Navbar: components.NewNavbar(false),
95 | OldPasswordInput: components.Input{
96 | ID: "old_password",
97 | Label: "Old Password",
98 | Type: "password",
99 | Placeholder: "Enter your old password",
100 | Error: oldPasswordError,
101 | Value: oldPassword,
102 | },
103 | NewPasswordInput: components.Input{
104 | ID: "new_password",
105 | Label: "New Password",
106 | Type: "password",
107 | Placeholder: "Enter your new password",
108 | Error: newPasswordError,
109 | Value: newPassword,
110 | },
111 | SubmitButton: components.Button{
112 | Text: "Update",
113 | IsSubmit: true,
114 | IsPrimary: true,
115 | },
116 | }
117 |
118 | templates.Render(w, "password_change.html", tmplData)
119 | }
120 |
--------------------------------------------------------------------------------
/features/users/users.go:
--------------------------------------------------------------------------------
1 | package users
2 |
3 | import (
4 | "fmt"
5 | "mouji/commons/components"
6 | "mouji/commons/session"
7 | "mouji/commons/templates"
8 | "net/http"
9 | "net/mail"
10 | "strings"
11 | )
12 |
13 | func HandleNewUserPage(w http.ResponseWriter, r *http.Request) {
14 | isOnboarding := r.URL.Query().Get("is_onboarding") == "true"
15 |
16 | email := ""
17 | emailError := ""
18 | passwordError := ""
19 |
20 | renderNewUserPage(w, isOnboarding, email, emailError, passwordError)
21 | }
22 |
23 | func HandleNewUserSubmit(w http.ResponseWriter, r *http.Request) {
24 | isOnboarding := r.URL.Query().Get("is_onboarding") == "true"
25 | hasUsers := HasUsers()
26 |
27 | err := r.ParseForm()
28 | if err != nil {
29 | err = fmt.Errorf("error parsing form: %w", err)
30 | http.Error(w, err.Error(), http.StatusBadRequest)
31 | return
32 | }
33 |
34 | email := r.Form.Get("email")
35 | password := r.Form.Get("password")
36 | emailError := ""
37 | passwordError := ""
38 |
39 | if !isValidEmail(email) {
40 | emailError = "Please enter a valid email address"
41 | }
42 |
43 | if !isValidPassword(password) {
44 | passwordError = "Password should not be empty"
45 | }
46 |
47 | if emailError != "" || passwordError != "" {
48 | renderNewUserPage(w, isOnboarding, email, emailError, passwordError)
49 | return
50 | }
51 |
52 | passwordHash, err := HashPassword(password)
53 | if err != nil {
54 | err = fmt.Errorf("error hashing password: %w", err)
55 | http.Error(w, err.Error(), http.StatusInternalServerError)
56 | return
57 | }
58 |
59 | // If there are no users, then the first user becomes an admin
60 | isAdmin := !hasUsers
61 |
62 | user, err := InsertUser(email, passwordHash, isAdmin)
63 |
64 | if err != nil {
65 | http.Error(w, err.Error(), http.StatusInternalServerError)
66 | return
67 | }
68 |
69 | if !hasUsers {
70 | sess, err := session.NewSession(user.UserID)
71 | if err != nil {
72 | http.Error(w, err.Error(), http.StatusInternalServerError)
73 | return
74 | }
75 | session.SetSessionCookie(w, sess)
76 |
77 | http.Redirect(w, r, "/", http.StatusSeeOther)
78 | return
79 | }
80 |
81 | http.Redirect(w, r, "/settings", http.StatusSeeOther)
82 | }
83 |
84 | func renderNewUserPage(w http.ResponseWriter, isOnboarding bool, email string, emailError string, passwordError string) {
85 | type templateData struct {
86 | Navbar components.Navbar
87 | IsOnboarding bool
88 | EmailInput components.Input
89 | PasswordInput components.Input
90 | SubmitButton components.Button
91 | }
92 |
93 | submitButtonText := "Continue"
94 | submitButtonIcon := "arrow-right"
95 | if isOnboarding {
96 | submitButtonText = "Create"
97 | submitButtonIcon = ""
98 | }
99 |
100 | tmplData := templateData{
101 | Navbar: components.NewNavbar(false),
102 | IsOnboarding: isOnboarding,
103 | EmailInput: components.Input{
104 | ID: "email",
105 | Label: "Email",
106 | Type: "email",
107 | Placeholder: "Enter your email address",
108 | Error: emailError,
109 | Value: email,
110 | },
111 | PasswordInput: components.Input{
112 | ID: "password",
113 | Label: "Password",
114 | Type: "password",
115 | Placeholder: "Enter your password",
116 | Error: passwordError,
117 | },
118 | SubmitButton: components.Button{
119 | Text: submitButtonText,
120 | Icon: submitButtonIcon,
121 | IsSubmit: true,
122 | IsPrimary: true,
123 | },
124 | }
125 |
126 | templates.Render(w, "user_detail.html", tmplData)
127 | }
128 |
129 | func isValidEmail(email string) bool {
130 | _, err := mail.ParseAddress(email)
131 | return err == nil
132 | }
133 |
134 | func isValidPassword(password string) bool {
135 | return len(strings.TrimSpace(password)) > 0
136 | }
137 |
--------------------------------------------------------------------------------
/features/settings/settings.go:
--------------------------------------------------------------------------------
1 | package settings
2 |
3 | import (
4 | "fmt"
5 | "mouji/commons/components"
6 | "mouji/commons/config"
7 | "mouji/commons/templates"
8 | "mouji/features/projects"
9 | "net/http"
10 | "net/url"
11 | )
12 |
13 | func HandleSettingsPage(w http.ResponseWriter, r *http.Request) {
14 | allProjects := projects.GetAllProjects()
15 |
16 | renderSettingsPage(w, allProjects)
17 | }
18 |
19 | func HandleServerURLPage(w http.ResponseWriter, r *http.Request) {
20 | isOnboarding := r.URL.Query().Get("is_onboarding") == "true"
21 |
22 | serverURL, err := config.GetConfig("server_url")
23 | if err != nil {
24 | http.Error(w, err.Error(), http.StatusInternalServerError)
25 | return
26 | }
27 |
28 | serverURLError := ""
29 |
30 | renderServerURLPage(w, isOnboarding, serverURL, serverURLError)
31 | }
32 |
33 | func HandleServerURLSubmit(w http.ResponseWriter, r *http.Request) {
34 | isOnboarding := r.URL.Query().Get("is_onboarding") == "true"
35 |
36 | err := r.ParseForm()
37 | if err != nil {
38 | err = fmt.Errorf("error parsing form: %w", err)
39 | http.Error(w, err.Error(), http.StatusBadRequest)
40 | return
41 | }
42 |
43 | serverURL := r.Form.Get("server_url")
44 | serverURLError := ""
45 |
46 | if !isValidURL(serverURL) {
47 | serverURLError = "Please enter a valid URL"
48 | renderServerURLPage(w, isOnboarding, serverURL, serverURLError)
49 | return
50 | }
51 |
52 | err = config.SetConfig("server_url", serverURL)
53 | if err != nil {
54 | http.Error(w, err.Error(), http.StatusInternalServerError)
55 | return
56 | }
57 |
58 | if isOnboarding {
59 | http.Redirect(w, r, "/", http.StatusSeeOther)
60 | return
61 | }
62 |
63 | http.Redirect(w, r, "/settings", http.StatusSeeOther)
64 | }
65 |
66 | func renderSettingsPage(w http.ResponseWriter, allProjects []projects.ProjectRecord) {
67 | type templateData struct {
68 | Navbar components.Navbar
69 | Projects []projects.ProjectRecord
70 | NewProjectButton components.Button
71 | ChangePasswordButton components.Button
72 | ServerURLButton components.Button
73 | }
74 |
75 | tmplData := templateData{
76 | Navbar: components.NewNavbar(false),
77 | Projects: allProjects,
78 | NewProjectButton: components.Button{
79 | Text: "New Project",
80 | Icon: "plus",
81 | Link: "/projects/new",
82 | },
83 | ChangePasswordButton: components.Button{
84 | Text: "Change Password",
85 | Icon: "key",
86 | Link: "/users/me/password",
87 | },
88 | ServerURLButton: components.Button{
89 | Text: "Change Server URL",
90 | Icon: "server-stack",
91 | Link: "/settings/server_url",
92 | },
93 | }
94 |
95 | templates.Render(w, "settings.html", tmplData)
96 | }
97 |
98 | func renderServerURLPage(w http.ResponseWriter, isOnboarding bool, serverURL string, serverURLError string) {
99 | type templateData struct {
100 | Navbar components.Navbar
101 | IsOnboarding bool
102 | ServerURLInput components.Input
103 | SubmitButton components.Button
104 | }
105 |
106 | tmplData := templateData{
107 | Navbar: components.NewNavbar(false),
108 | IsOnboarding: isOnboarding,
109 | ServerURLInput: components.Input{
110 | ID: "server_url",
111 | Label: "Server URL",
112 | Type: "url",
113 | Placeholder: "Example: https://www.myserver.com",
114 | Error: serverURLError,
115 | Value: serverURL,
116 | Hint: "Enter the Base URL of the server to correctly generate your tracking snippet",
117 | },
118 | SubmitButton: components.Button{
119 | Text: "Update",
120 | IsSubmit: true,
121 | IsPrimary: true,
122 | },
123 | }
124 |
125 | templates.Render(w, "server_url.html", tmplData)
126 | }
127 |
128 | func isValidURL(serverURL string) bool {
129 | _, err := url.ParseRequestURI(serverURL)
130 | return err == nil
131 | }
132 |
--------------------------------------------------------------------------------
/commons/sqlite/migrate.go:
--------------------------------------------------------------------------------
1 | package sqlite
2 |
3 | import (
4 | "embed"
5 | "fmt"
6 | "io/fs"
7 | "log/slog"
8 | "sort"
9 | "strconv"
10 | "strings"
11 | )
12 |
13 | type migration struct {
14 | version int
15 | name string
16 | content string
17 | isApplied bool
18 | }
19 |
20 | func Migrate(resources embed.FS) {
21 | createMigrationsTable()
22 |
23 | migrations := getAllMigrations(resources)
24 |
25 | migrations = getUnAppliedMigrations(migrations)
26 |
27 | if len(migrations) > 0 {
28 | slog.Info("applying database migrations")
29 | }
30 |
31 | sort.Slice(migrations, func(i, j int) bool {
32 | return migrations[i].version < migrations[j].version
33 | })
34 |
35 | applyMigrations(migrations)
36 | }
37 |
38 | func createMigrationsTable() {
39 | query := "CREATE TABLE IF NOT EXISTS migrations (version INT)"
40 |
41 | _, err := DB.Exec(query)
42 |
43 | if err != nil {
44 | err = fmt.Errorf("error creating migrations table: %w", err)
45 | panic(err)
46 | }
47 | }
48 |
49 | func getAllMigrations(resources embed.FS) []migration {
50 | var migrations []migration
51 |
52 | fs.WalkDir(resources, ".", func(path string, d fs.DirEntry, err error) error {
53 | if strings.Contains(d.Name(), ".sql") {
54 | migrations = append(migrations, getMigration(resources, path, d.Name()))
55 | }
56 | return nil
57 | })
58 |
59 | return migrations
60 | }
61 |
62 | func getMigration(resources embed.FS, path string, name string) migration {
63 | content, err := fs.ReadFile(resources, path)
64 |
65 | if err != nil {
66 | err = fmt.Errorf("error reading migration file: %w", err)
67 | panic(err)
68 | }
69 |
70 | version, err := strconv.Atoi(strings.Split(name, "_")[0])
71 |
72 | if err != nil {
73 | err = fmt.Errorf("error parsing migration file version: %w", err)
74 | panic(err)
75 | }
76 |
77 | return migration{
78 | name: name,
79 | version: version,
80 | content: string(content),
81 | isApplied: false,
82 | }
83 | }
84 |
85 | func getUnAppliedMigrations(migrations []migration) []migration {
86 | query := "SELECT version FROM migrations ORDER BY version ASC"
87 |
88 | rows, err := DB.Query(query)
89 | defer rows.Close()
90 |
91 | if err != nil {
92 | err = fmt.Errorf("error retrieving migrations: %w", err)
93 | panic(err)
94 | }
95 |
96 | for rows.Next() {
97 | var version int
98 | err = rows.Scan(&version)
99 |
100 | if err != nil {
101 | err = fmt.Errorf("error scanning migration record: %w", err)
102 | panic(err)
103 | }
104 |
105 | for i := range migrations {
106 | if migrations[i].version == version {
107 | migrations[i].isApplied = true
108 | }
109 | }
110 | }
111 |
112 | var unAppliedMigrations []migration
113 | for i := range migrations {
114 | if !migrations[i].isApplied {
115 | unAppliedMigrations = append(unAppliedMigrations, migrations[i])
116 | }
117 | }
118 |
119 | return unAppliedMigrations
120 | }
121 |
122 | func applyMigrations(migrations []migration) {
123 | tx, err := DB.Begin()
124 |
125 | if err != nil {
126 | err = fmt.Errorf("error beginning migration tx: %w", err)
127 | panic(err)
128 | }
129 |
130 | for _, m := range migrations {
131 | slog.Info("applying migration", "name", m.name)
132 | _, err = tx.Exec(m.content)
133 |
134 | if err != nil {
135 | err = fmt.Errorf("error applying migration %d: %w", m.version, err)
136 | slog.Error(err.Error())
137 |
138 | err = tx.Rollback()
139 | if err != nil {
140 | err = fmt.Errorf("error rolling back migration: %w", err)
141 | panic(err)
142 | }
143 |
144 | return
145 | }
146 |
147 | query := "INSERT INTO migrations VALUES(?)"
148 | _, err = tx.Exec(query, m.version)
149 |
150 | if err != nil {
151 | err = fmt.Errorf("error updating migrations table %d: %w", m.version, err)
152 | slog.Error(err.Error())
153 |
154 | err = tx.Rollback()
155 | if err != nil {
156 | err = fmt.Errorf("error rolling back migration: %w", err)
157 | panic(err)
158 | }
159 |
160 | return
161 | }
162 | }
163 |
164 | err = tx.Commit()
165 |
166 | if err != nil {
167 | err = fmt.Errorf("error commiting migrations: %w", err)
168 | slog.Error(err.Error())
169 |
170 | err = tx.Rollback()
171 | if err != nil {
172 | err = fmt.Errorf("error rolling back migration: %w", err)
173 | panic(err)
174 | }
175 |
176 | return
177 | }
178 | }
179 |
--------------------------------------------------------------------------------
/features/pageviews/pageviews_model.go:
--------------------------------------------------------------------------------
1 | package pageviews
2 |
3 | import (
4 | "database/sql"
5 | "fmt"
6 | "log/slog"
7 | "mouji/commons/components"
8 | "mouji/commons/sqlite"
9 | "slices"
10 | )
11 |
12 | type PageViewRecord struct {
13 | ProjectID string
14 | Path string
15 | Title string
16 | Referrer string
17 | VisitorHash string
18 | UserAgent string
19 | }
20 |
21 | type PaginatedPageViewRecord struct {
22 | Title string
23 | Path string
24 | Views int
25 | TotalRecords int
26 | }
27 |
28 | type PageViewCountRecord struct {
29 | Interval string
30 | Count int
31 | TotalCount int
32 | }
33 |
34 | func InsertPageView(record PageViewRecord) error {
35 | query := "INSERT INTO pageviews (project_id, path, title, referrer, visitor_hash, user_agent) VALUES (?, ?, ?, ?, ?, ?);"
36 |
37 | _, err := sqlite.DB.Exec(query, record.ProjectID, record.Path, record.Title, record.Referrer, record.VisitorHash, record.UserAgent)
38 | if err != nil {
39 | err = fmt.Errorf("error inserting pageview: %w", err)
40 | slog.Error(err.Error())
41 | return err
42 | }
43 |
44 | return nil
45 | }
46 |
47 | func GetPaginatedPageViews(projectID string, daterange components.DataRangeType, limit int, offset int) ([]PaginatedPageViewRecord, error) {
48 | var records []PaginatedPageViewRecord
49 |
50 | query := `
51 | SELECT
52 | title,
53 | path,
54 | COUNT(*) AS views,
55 | COUNT(*) OVER() AS total_rows
56 | FROM
57 | pageviews
58 | WHERE
59 | project_id = ?
60 | AND
61 | received_at >= DATETIME('now', ?)
62 | GROUP BY
63 | path
64 | ORDER BY
65 | views DESC
66 | LIMIT
67 | ?
68 | OFFSET
69 | ?
70 | `
71 |
72 | rows, err := sqlite.DB.Query(query, projectID, getDateRangeFilter(daterange), limit, offset)
73 | if err != nil {
74 | err = fmt.Errorf("error retrieving pageviews: %w", err)
75 | slog.Error(err.Error())
76 | return records, err
77 | }
78 | defer rows.Close()
79 |
80 | for rows.Next() {
81 | var record PaginatedPageViewRecord
82 | err = rows.Scan(&record.Title, &record.Path, &record.Views, &record.TotalRecords)
83 | if err != nil {
84 | return records, err
85 | }
86 | records = append(records, record)
87 | }
88 |
89 | return records, nil
90 | }
91 |
92 | func GetPageViewCountsByInterval(projectID string, daterange components.DataRangeType) ([]PageViewCountRecord, error) {
93 | var records []PageViewCountRecord
94 | var rows *sql.Rows
95 | var err error
96 |
97 | if daterange == "24h" {
98 | query := `
99 | SELECT
100 | -- https://stackoverflow.com/a/33116186
101 | STRFTIME('%d ', received_at) || SUBSTR('--JanFebMarAprMayJunJulAugSepOctNovDec', STRFTIME('%m', received_at) * 3, 3) || ', ' ||
102 | CASE
103 | WHEN STRFTIME('%H', received_at) = '00' THEN '12 - 01 AM'
104 | WHEN STRFTIME('%H', received_at) = '12' THEN '12 - 01 PM'
105 | ELSE
106 | STRFTIME('%I', received_at) || ' - ' || STRFTIME('%I', DATETIME(received_at, '+1 hour')) ||
107 | CASE
108 | WHEN STRFTIME('%p', received_at) = 'AM' AND STRFTIME('%H', received_at) = '11' THEN ' PM'
109 | WHEN STRFTIME('%p', received_at) = 'PM' AND STRFTIME('%H', received_at) = '23' THEN ' AM'
110 | ELSE STRFTIME(' %p', received_at)
111 | END
112 | END AS interval,
113 | COUNT(*) AS count,
114 | SUM(COUNT(*)) OVER() AS total_count
115 | FROM
116 | pageviews
117 | WHERE
118 | project_id = ?
119 | AND
120 | received_at >= DATETIME('now', '-24 hours')
121 | GROUP BY
122 | STRFTIME('%Y-%m-%d %H', received_at)
123 | ORDER BY
124 | STRFTIME('%Y-%m-%d %H', received_at);
125 | `
126 | rows, err = sqlite.DB.Query(query, projectID)
127 | } else if daterange == "1w" || daterange == "1m" || daterange == "3m" {
128 | query := `
129 | SELECT
130 | STRFTIME('%d ', received_at) || SUBSTR('--JanFebMarAprMayJunJulAugSepOctNovDec', STRFTIME('%m', received_at) * 3, 3) AS interval,
131 | COUNT(*) AS count,
132 | SUM(COUNT(*)) OVER() AS total_count
133 | FROM
134 | pageviews
135 | WHERE
136 | project_id = ?
137 | AND
138 | received_at >= DATETIME('now', ?)
139 | GROUP BY
140 | interval
141 | ORDER BY
142 | received_at
143 | `
144 | rows, err = sqlite.DB.Query(query, projectID, getDateRangeFilter(daterange))
145 | } else {
146 | query := `
147 | SELECT
148 | STRFTIME('%Y ', received_at) || SUBSTR('--JanFebMarAprMayJunJulAugSepOctNovDec', STRFTIME('%m', received_at) * 3, 3) AS interval,
149 | COUNT(*) AS count,
150 | SUM(COUNT(*)) OVER() AS total_count
151 | FROM
152 | pageviews
153 | WHERE
154 | project_id = ?
155 | AND
156 | received_at >= DATETIME('now', '-1 years')
157 | GROUP BY
158 | interval
159 | ORDER BY
160 | received_at
161 | `
162 | rows, err = sqlite.DB.Query(query, projectID, getDateRangeFilter(daterange))
163 | }
164 | if err != nil {
165 | err = fmt.Errorf("error retrieving pageview counts: %w", err)
166 | slog.Error(err.Error())
167 | return records, err
168 | }
169 | defer rows.Close()
170 |
171 | for rows.Next() {
172 | var record PageViewCountRecord
173 | err = rows.Scan(&record.Interval, &record.Count, &record.TotalCount)
174 | if err != nil {
175 | return records, err
176 | }
177 | records = append(records, record)
178 | }
179 |
180 | return records, nil
181 | }
182 |
183 | func getDateRangeFilter(daterange components.DataRangeType) string {
184 | if !slices.Contains(components.DateRangeValues, daterange) {
185 | daterange = components.DateRangeValues[0]
186 | }
187 |
188 | switch daterange {
189 | case "24h":
190 | return "-24 hours"
191 | case "1w":
192 | return "-6 days"
193 | case "1m":
194 | return "-1 months"
195 | case "3m":
196 | return "-3 months"
197 | case "1y":
198 | return "-1 years"
199 | }
200 |
201 | return "-24 hours"
202 | }
203 |
--------------------------------------------------------------------------------
/features/home/home.go:
--------------------------------------------------------------------------------
1 | package home
2 |
3 | import (
4 | "fmt"
5 | "mouji/commons/components"
6 | "mouji/commons/config"
7 | "mouji/commons/templates"
8 | "mouji/features/pageviews"
9 | "mouji/features/projects"
10 | "mouji/features/users"
11 | "net/http"
12 | "strconv"
13 | )
14 |
15 | type urlState struct {
16 | selectedProjectID string
17 | selectedDateRange components.DataRangeType
18 | currentPageViewTableOffset string
19 | }
20 |
21 | type pageViewsTable struct {
22 | Records []pageviews.PaginatedPageViewRecord
23 | ShouldShowPagination bool
24 | Pagination components.Pagination
25 | }
26 |
27 | type pageViewsChart struct {
28 | TotalCount int
29 | BarChart components.BarChart
30 | }
31 |
32 | func HandleHomePage(w http.ResponseWriter, r *http.Request) {
33 | hasUsers := users.HasUsers()
34 | if !hasUsers {
35 | http.Redirect(w, r, "/users/new?is_onboarding=true", http.StatusSeeOther)
36 | return
37 | }
38 |
39 | server_url, err := config.GetConfig("server_url")
40 | if err != nil {
41 | http.Error(w, err.Error(), http.StatusInternalServerError)
42 | return
43 | }
44 | if server_url == "" {
45 | http.Redirect(w, r, "/settings/server_url?is_onboarding=true", http.StatusSeeOther)
46 | return
47 | }
48 |
49 | projects := projects.GetAllProjects()
50 | if len(projects) == 0 {
51 | http.Redirect(w, r, "/projects/new?is_onboarding=true", http.StatusSeeOther)
52 | return
53 | }
54 |
55 | var state urlState
56 | state.selectedProjectID = r.URL.Query().Get("project_id")
57 | state.selectedDateRange = components.DataRangeType(r.URL.Query().Get("daterange"))
58 | state.currentPageViewTableOffset = r.URL.Query().Get("current_pageview_table_offset")
59 |
60 | if state.selectedProjectID == "" {
61 | newURL := fmt.Sprintf("/?project_id=%s&daterange=%s¤t_pageview_table_offset=%d", projects[0].ProjectID, components.DateRangeValues[0], 0)
62 | http.Redirect(w, r, newURL, http.StatusSeeOther)
63 | return
64 | }
65 |
66 | renderHomePage(w, state, projects)
67 | }
68 |
69 | func renderHomePage(w http.ResponseWriter, state urlState, projects []projects.ProjectRecord) {
70 | type templateData struct {
71 | Navbar components.Navbar
72 | PageViewsChart pageViewsChart
73 | PageViewsTable pageViewsTable
74 | }
75 |
76 | navbar := getNavbar(state, projects)
77 |
78 | pageViewsCount, err := pageviews.GetPageViewCountsByInterval(state.selectedProjectID, state.selectedDateRange)
79 | if err != nil {
80 | http.Error(w, err.Error(), http.StatusInternalServerError)
81 | return
82 | }
83 |
84 | totalCount := 0
85 | barChartInputDataPoints := []components.BarChartInputDataPoint{}
86 | for _, record := range pageViewsCount {
87 | barChartInputDataPoint := components.BarChartInputDataPoint{
88 | Label: record.Interval,
89 | Data: record.Count,
90 | }
91 | barChartInputDataPoints = append(barChartInputDataPoints, barChartInputDataPoint)
92 | totalCount = record.TotalCount
93 | }
94 | barChart := components.NewBarChart(barChartInputDataPoints)
95 | chart := pageViewsChart{
96 | TotalCount: totalCount,
97 | BarChart: barChart,
98 | }
99 |
100 | table, err := getPageViewsTable(state)
101 | if err != nil {
102 | http.Error(w, err.Error(), http.StatusInternalServerError)
103 | return
104 | }
105 |
106 | tmplData := templateData{
107 | Navbar: navbar,
108 | PageViewsChart: chart,
109 | PageViewsTable: table,
110 | }
111 |
112 | templates.Render(w, "home.html", tmplData)
113 | }
114 |
115 | func getNavbar(state urlState, projects []projects.ProjectRecord) components.Navbar {
116 | navbar := components.NewNavbar(true)
117 | var allOptions []components.DropdownOption
118 | var selectedOption components.DropdownOption
119 | for _, project := range projects {
120 | var option components.DropdownOption
121 | option.Name = project.Name
122 | option.Link = fmt.Sprintf("/?project_id=%s&daterange=%s", project.ProjectID, state.selectedDateRange)
123 | option.Value = ""
124 | allOptions = append(allOptions, option)
125 | if project.ProjectID == state.selectedProjectID {
126 | selectedOption = option
127 | }
128 | }
129 | if state.selectedProjectID == "" {
130 | selectedOption = allOptions[0]
131 | }
132 | navbar.ProjectsDropdown.SelectedOption = selectedOption
133 | navbar.ProjectsDropdown.AllOptions = allOptions
134 | navbar.ProjectsDropdown.InputName = ""
135 |
136 | navbar.DateRange = getDateRange(state)
137 |
138 | return navbar
139 | }
140 |
141 | func getDateRange(state urlState) components.DateRange {
142 | var daterange components.DateRange
143 |
144 | for _, value := range components.DateRangeValues {
145 | var option components.DateRangeOption
146 | option.Name = value
147 | option.Link = fmt.Sprintf("/?project_id=%s&daterange=%s", state.selectedProjectID, value)
148 | if value == state.selectedDateRange {
149 | option.IsSelected = true
150 | }
151 | daterange.Options = append(daterange.Options, option)
152 | }
153 |
154 | return daterange
155 | }
156 |
157 | func getPageViewsTable(state urlState) (pageViewsTable, error) {
158 | var records []pageviews.PaginatedPageViewRecord
159 | limit := 10
160 |
161 | pageViewTableOffset, err := strconv.Atoi(state.currentPageViewTableOffset)
162 | if err != nil {
163 | pageViewTableOffset = 0
164 | }
165 |
166 | table := pageViewsTable{
167 | Records: records,
168 | ShouldShowPagination: false,
169 | Pagination: components.Pagination{
170 | PageStartRecord: pageViewTableOffset + 1,
171 | PageEndRecord: 0,
172 | TotalRecords: 0,
173 | PrevLink: "",
174 | NextLink: "",
175 | },
176 | }
177 |
178 | records, err = pageviews.GetPaginatedPageViews(state.selectedProjectID, state.selectedDateRange, limit, pageViewTableOffset)
179 | if err != nil {
180 | return table, err
181 | }
182 |
183 | if len(records) > 0 {
184 | table.Records = records
185 | table.Pagination.TotalRecords = records[0].TotalRecords
186 | table.Pagination.PageStartRecord = pageViewTableOffset + 1
187 | table.Pagination.PageEndRecord = pageViewTableOffset + len(records)
188 | table.ShouldShowPagination = records[0].TotalRecords > limit
189 | }
190 |
191 | if table.ShouldShowPagination && pageViewTableOffset != 0 {
192 | table.Pagination.PrevLink = fmt.Sprintf("/?project_id=%s&daterange=%s¤t_pageview_table_offset=%d", state.selectedProjectID, state.selectedDateRange, pageViewTableOffset-limit)
193 | }
194 |
195 | if table.ShouldShowPagination && pageViewTableOffset+limit < table.Pagination.TotalRecords {
196 | table.Pagination.NextLink = fmt.Sprintf("/?project_id=%s&daterange=%s¤t_pageview_table_offset=%d", state.selectedProjectID, state.selectedDateRange, pageViewTableOffset+limit)
197 | }
198 |
199 | return table, nil
200 | }
201 |
--------------------------------------------------------------------------------
/features/projects/projects.go:
--------------------------------------------------------------------------------
1 | package projects
2 |
3 | import (
4 | "fmt"
5 | "mouji/commons/components"
6 | "mouji/commons/config"
7 | "mouji/commons/templates"
8 | "net/http"
9 | "net/url"
10 | "strings"
11 | )
12 |
13 | func HandleNewProjectPage(w http.ResponseWriter, r *http.Request) {
14 | isOnboarding := r.URL.Query().Get("is_onboarding") == "true"
15 | isNewProject := true
16 |
17 | projectID := ""
18 | projectName := ""
19 | siteBaseURL := ""
20 | projectNameError := ""
21 | siteBaseURLError := ""
22 |
23 | serverURL, err := config.GetConfig("server_url")
24 | if err != nil {
25 | http.Error(w, err.Error(), http.StatusInternalServerError)
26 | return
27 | }
28 |
29 | renderProjectDetailPage(w, isOnboarding, isNewProject, projectID, projectName, siteBaseURL, serverURL, projectNameError, siteBaseURLError)
30 | }
31 |
32 | func HandleEditProjectPage(w http.ResponseWriter, r *http.Request) {
33 | isOnboarding := false
34 | isNewProject := false
35 |
36 | projectID := r.PathValue("project_id")
37 | project, err := getProjectByID(projectID)
38 | if err != nil {
39 | http.Error(w, err.Error(), http.StatusInternalServerError)
40 | return
41 | }
42 |
43 | serverURL, err := config.GetConfig("server_url")
44 | if err != nil {
45 | http.Error(w, err.Error(), http.StatusInternalServerError)
46 | return
47 | }
48 |
49 | projectNameError := ""
50 | siteBaseURLError := ""
51 |
52 | renderProjectDetailPage(w, isOnboarding, isNewProject, project.ProjectID, project.Name, project.BaseURL, serverURL, projectNameError, siteBaseURLError)
53 | }
54 |
55 | func HandleProjectDetailSubmit(w http.ResponseWriter, r *http.Request) {
56 | isOnboarding := r.URL.Query().Get("is_onboarding") == "true"
57 | projectID := r.PathValue("project_id")
58 | isNewProject := projectID == "new"
59 |
60 | err := r.ParseForm()
61 | if err != nil {
62 | err = fmt.Errorf("error parsing form: %w", err)
63 | http.Error(w, err.Error(), http.StatusBadRequest)
64 | return
65 | }
66 |
67 | projectName := r.Form.Get("name")
68 | siteBaseURL := r.Form.Get("base_url")
69 | projectNameError := ""
70 | siteBaseURLError := ""
71 |
72 | serverURL, err := config.GetConfig("server_url")
73 | if err != nil {
74 | http.Error(w, err.Error(), http.StatusInternalServerError)
75 | return
76 | }
77 |
78 | if !isValidProjectName(projectName) {
79 | projectNameError = "Project name should not be empty"
80 | }
81 |
82 | if !isValidURL(siteBaseURL) {
83 | siteBaseURLError = "Please enter a valid URL"
84 | }
85 |
86 | if projectNameError != "" || siteBaseURLError != "" {
87 | renderProjectDetailPage(w, isOnboarding, isNewProject, projectID, projectName, siteBaseURL, serverURL, projectNameError, siteBaseURLError)
88 | return
89 | }
90 |
91 | var project ProjectRecord
92 | if isNewProject {
93 | project, err = InsertProject(projectName, siteBaseURL)
94 | } else {
95 | project, err = updateProject(projectID, projectName, siteBaseURL)
96 | }
97 |
98 | if err != nil {
99 | http.Error(w, err.Error(), http.StatusInternalServerError)
100 | return
101 | }
102 |
103 | if isOnboarding {
104 | http.Redirect(w, r, "/", http.StatusSeeOther)
105 | return
106 | }
107 |
108 | projectDetailURL := fmt.Sprintf("/projects/%s", project.ProjectID)
109 | http.Redirect(w, r, projectDetailURL, http.StatusSeeOther)
110 | }
111 |
112 | func renderProjectDetailPage(w http.ResponseWriter, isOnboarding bool, isNewProject bool, projectID string, projectName string, siteBaseURL string, serverURL string, projectNameError string, siteBaseURLError string) {
113 | type templateData struct {
114 | Navbar components.Navbar
115 | IsOnboarding bool
116 | IsNewProject bool
117 | ProjectID string
118 | ProjectNameInput components.Input
119 | SiteURLInput components.Input
120 | TrackingSnippetInput components.TextArea
121 | SubmitButton components.Button
122 | }
123 |
124 | trackingSnippet := ""
125 | submitButtonText := "Create"
126 | if !isNewProject {
127 | submitButtonText = "Update"
128 | trackingSnippet = getTrackingSnippet(serverURL, projectID)
129 | }
130 |
131 | tmplData := templateData{
132 | Navbar: components.NewNavbar(false),
133 | IsOnboarding: isOnboarding,
134 | IsNewProject: isNewProject,
135 | ProjectID: projectID,
136 | ProjectNameInput: components.Input{
137 | ID: "name",
138 | Label: "Name",
139 | Type: "text",
140 | Placeholder: "Enter your project name",
141 | Error: projectNameError,
142 | Value: projectName,
143 | },
144 | SiteURLInput: components.Input{
145 | ID: "base_url",
146 | Label: "Site URL",
147 | Type: "url",
148 | Placeholder: "Example: https://www.blogpost.com",
149 | Error: siteBaseURLError,
150 | Value: siteBaseURL,
151 | Hint: "Enter the base URL of the site associated with this project",
152 | },
153 | TrackingSnippetInput: components.TextArea{
154 | ID: "tracking_snippet",
155 | Label: "Tracking Snippet",
156 | Content: trackingSnippet,
157 | Hint: "Copy paste this tracking snippet in your site's HTML file at the end of head tag",
158 | IsDisabled: true,
159 | },
160 | SubmitButton: components.Button{
161 | Text: submitButtonText,
162 | IsSubmit: true,
163 | IsPrimary: true,
164 | },
165 | }
166 |
167 | templates.Render(w, "project_detail.html", tmplData)
168 | }
169 |
170 | func isValidProjectName(projectName string) bool {
171 | return len(strings.TrimSpace(projectName)) > 0
172 | }
173 |
174 | func isValidURL(siteBaseURL string) bool {
175 | _, err := url.ParseRequestURI(siteBaseURL)
176 | return err == nil
177 | }
178 |
179 | func getTrackingSnippet(serverURL string, projectID string) string {
180 | var snippet = `
181 |
182 |
214 | `
215 | snippet = strings.TrimSpace(snippet)
216 | return fmt.Sprintf(snippet, serverURL, projectID)
217 | }
218 |
--------------------------------------------------------------------------------
/assets/index.css:
--------------------------------------------------------------------------------
1 | /*
2 | * References:
3 | * "The 80% of UI Design - Typography" https://www.youtube.com/watch?v=9-oefwZ6Z74
4 | * "Modular scale" https://design-system.economist.com/foundations/typography/modular-scale#type-scale
5 | * "Line-height" https://design-system.economist.com/foundations/typography/line-height#multipliers
6 | * "Responsive And Fluid Typography With vh And vw Units" https://www.smashingmagazine.com/2016/05/fluid-typography/
7 | */
8 |
9 | :root {
10 | /* https://tailwindcss.com/docs/customizing-colors */
11 | --neutral-900: #171717;
12 | --neutral-400: #a3a3a3;
13 | --gray-900: #111827;
14 | --gray-700: #374151;
15 | --zinc-200: #E4E4E7;
16 | --zinc-100: #f4f4f5;
17 | --red-600: #DC2626;
18 |
19 | /* typography */
20 | --font-scale: 1.125; /* Major Second */
21 | --font-family: "Lato", sans-serif;
22 | --h1: bold 2.027rem/1.2 var(--font-family); /* 1rem * pow(var(--font-scale), 6) */
23 | --h2: bold 1.802rem/1.2 var(--font-family); /* 1rem * pow(var(--font-scale), 5) */
24 | --h3: bold 1.602rem/1.2 var(--font-family); /* 1rem * pow(var(--font-scale), 4) */
25 | --h4: bold 1.424rem/1.2 var(--font-family); /* 1rem * pow(var(--font-scale), 3) */
26 | --h5: bold 1.266rem/1.2 var(--font-family); /* 1rem * pow(var(--font-scale), 2) */
27 | --h6: bold 1.125rem/1.2 var(--font-family); /* 1rem * pow(var(--font-scale), 1) */
28 | --p1: normal 1rem/1.4 var(--font-family);
29 | --sm: normal 0.889rem/1.4 var(--font-family); /* 1rem / var(--font-scale) */
30 |
31 | /* spacing */
32 | /* https://medium.com/dwarves-design/the-principle-of-spacing-in-ui-design-part-1-3354d0d65e51 */
33 | --spacing-xs: 6px;
34 | --spacing-sm: 12px;
35 | --spacing-md: 24px;
36 | --spacing-lg: 48px;
37 |
38 | /* elevation */
39 | --shadow-0: inset 0 1px 2px rgba(0, 0, 0, .39), 0 -1px 1px #FFF, 0 1px 0 #FFF; /* https://gist.github.com/nrrrdcore/3309046 */
40 | --shadow-1: rgba(0, 0, 0, 0.01) 0px 1px 3px 0px, rgba(0, 0, 0, 0.10) 0px 1px 3px 0px;
41 | --shadow-2: rgba(0, 0, 0, 0.10) 0px 1px 3px 0px, rgba(0, 0, 0, 0.10) 0px 1px 3px 0px;
42 | }
43 |
44 | html {
45 | font-size: 16px; /* 1rem */
46 | box-sizing: border-box;
47 | }
48 |
49 | * {
50 | font: var(--p1);
51 | color: var(--neutral-900);
52 | }
53 |
54 | /* https://css-tricks.com/box-sizing/#aa-universal-box-sizing-with-inheritance */
55 | *,
56 | *:before,
57 | *:after {
58 | box-sizing: inherit;
59 | }
60 |
61 | body {
62 | max-width: 900px;
63 | margin: 24px auto;
64 | padding-bottom: 24px;
65 | }
66 |
67 | @media screen and (max-width: 948px) {
68 | body {
69 | margin-top: var(--spacing-md);
70 | -webkit-text-size-adjust: 100%; /* https://stackoverflow.com/a/2711132 */
71 | margin-bottom: max(24px, env(safe-area-inset-bottom)); /* https://webkit.org/blog/7929/designing-websites-for-iphone-x */
72 | margin-left: max(24px, env(safe-area-inset-left));
73 | margin-right: max(24px, env(safe-area-inset-right));
74 | }
75 | }
76 |
77 | .h-space-12 {
78 | display: inline;
79 | margin-left: var(--spacing-sm);
80 | }
81 |
82 | .v-space-6 {
83 | margin-top: var(--spacing-xs);
84 | }
85 |
86 | .v-space-12 {
87 | margin-top: var(--spacing-sm);
88 | }
89 |
90 | .v-space-24 {
91 | margin-top: var(--spacing-md);
92 | }
93 |
94 | svg.icon {
95 | width: 34px;
96 | height: 34px;
97 | padding: 9px;
98 |
99 | path {
100 | stroke: var(--neutral-900);
101 | stroke-width: 1.5;
102 | }
103 | }
104 |
105 | table {
106 | margin-top: var(--spacing-sm);
107 | width: 100%;
108 | border-collapse: collapse;
109 | border-radius: 6px;
110 | border-style: hidden;
111 | box-shadow: 0 0 0 1px var(--zinc-200);
112 | }
113 |
114 | tr {
115 | display: flex;
116 | justify-content: space-between;
117 | padding: 12px;
118 | border-bottom: 1px solid var(--zinc-200);
119 | }
120 |
121 | tr:last-child {
122 | border-bottom: none;
123 | }
124 |
125 | td {
126 | text-align: left;
127 | vertical-align: text-top;
128 |
129 | &.text {
130 | padding-right: 8px;
131 |
132 | .path {
133 | font: var(--sm);
134 | margin-top: 4px;
135 | color: var(--neutral-400);
136 | }
137 | }
138 |
139 | &.metrics {
140 | display: flex;
141 | align-items: center;
142 | justify-content: end;
143 |
144 | .value {
145 | margin-right: -4px;
146 | }
147 |
148 | svg {
149 | padding-right: 0;
150 | padding-left: 0;
151 | margin-right: -9px;
152 |
153 | path {
154 | stroke: var(--neutral-400);
155 | stroke-width: 1.5;
156 | }
157 | }
158 | }
159 | }
160 |
161 | .navbar {
162 | height: 36px;
163 | display: flex;
164 | align-items: center;
165 | justify-content: space-between;
166 |
167 | .logo {
168 | font: var(--h1);
169 | text-decoration: none;
170 | }
171 |
172 | .actions {
173 | display: flex;
174 | }
175 | }
176 |
177 | @media screen and (max-width: 750px) {
178 | .navbar {
179 | margin-top: 24px;
180 | flex-direction: column;
181 | align-items: flex-start;
182 |
183 | &:has(.actions) {
184 | height: 196px;
185 | }
186 |
187 | .actions {
188 | flex-direction: column;
189 | align-items: flex-start;
190 | justify-content: space-between;
191 | height: 132px;
192 | margin-top: 24px;
193 | }
194 | }
195 | }
196 |
197 | .section {
198 | margin-top: 48px;
199 |
200 | .title-bar {
201 | display: flex;
202 | align-items: center;
203 | justify-content: space-between;
204 | }
205 |
206 | .title {
207 | font: var(--h5);
208 | }
209 |
210 | .subtitle {
211 | margin-top: 4px;
212 | color: var(--neutral-400);
213 | }
214 |
215 | .empty {
216 | margin-top: var(--spacing-sm);
217 | }
218 | }
219 |
220 | @media screen and (max-width: 750px) {
221 | .section {
222 | margin-top: var(--spacing-lg);
223 | }
224 | }
225 |
226 | .input-container {
227 | margin-top: var(--spacing-md);
228 |
229 | input,
230 | textarea {
231 | height: 44px;
232 | border-radius: 6px;
233 | border: 1px solid transparent;
234 | margin-left: -1px; /* To fix the transparent border */
235 | border-top: none;
236 | border-bottom: 1px solid var(--zinc-200);
237 | padding: 8px;
238 | margin-top: var(--spacing-xs);
239 | min-width: 320px;
240 | box-shadow: var(--shadow-0);
241 |
242 | &.error {
243 | border: 1px solid var(--red-600);
244 | color: var(--neutral-900);
245 | box-shadow: none;
246 | }
247 | }
248 |
249 | textarea {
250 | width: 100%;
251 | height: 300px;
252 | font: var(--sm);
253 | font-family: monospace;
254 | resize: none;
255 | tab-size: 4;
256 | field-sizing: content; /* https://developer.mozilla.org/en-US/docs/Web/CSS/field-sizing#browser_compatibility */
257 | }
258 |
259 | .error {
260 | color: var(--red-600);
261 | font: var(--sm);
262 | }
263 | }
264 |
265 | .hint {
266 | color: var(--neutral-400);
267 | font: var(--sm);
268 | }
269 |
270 | button.button-container,
271 | button.dropdown-container {
272 | display: flex;
273 | position: relative;
274 | padding: 0;
275 | border: 0;
276 | background: none;
277 | }
278 |
279 | .button,
280 | .pagination,
281 | .dropdown-button,
282 | .daterange {
283 | display: flex;
284 | height: 36px;
285 | align-items: center;
286 | justify-content: space-between;
287 | padding: 0 12px;
288 | border-radius: 6px;
289 | border: 1px solid var(--zinc-200);
290 | overflow: hidden;
291 | transition-property: background-color, box-shadow;
292 | transition-duration: 500ms;
293 | text-decoration: none;
294 | box-shadow: var(--shadow-1);
295 |
296 | &:has(svg) {
297 | padding-right: 0;
298 | }
299 |
300 | &:active {
301 | box-shadow: none;
302 | }
303 |
304 | &.primary {
305 | background-color: var(--neutral-900);
306 | color: white;
307 |
308 | svg.icon {
309 | path {
310 | stroke: white;
311 | }
312 | }
313 |
314 | &:hover {
315 | background-color: var(--zinc-400);
316 | }
317 | }
318 |
319 | a {
320 | height: 34px;
321 | line-height: 1;
322 | }
323 | }
324 |
325 | .button:hover,
326 | .dropdown-button:hover,
327 | .dropdown-option:hover {
328 | background-color: var(--zinc-100);
329 | cursor: pointer;
330 |
331 | &.primary {
332 | background-color: var(--gray-700);
333 | }
334 | }
335 |
336 | .dropdown-container {
337 | &.open {
338 | .dropdown-menu {
339 | display: block;
340 | }
341 |
342 | .dropdown-button {
343 | border-radius: 6px 6px 0 0;
344 | }
345 | }
346 | }
347 |
348 | .dropdown-button {
349 | min-width: 160px;
350 | }
351 |
352 | .dropdown-menu {
353 | list-style: none;
354 | margin: 0;
355 | padding: 0;
356 | top: 36px;
357 | position: absolute;
358 | width: 100%;
359 | box-shadow: var(--shadow-2);
360 | display: none;
361 | background-color: white;
362 | z-index: 1;
363 | max-height: 198px; /* 5.5 items * 36px of option height */
364 | overflow: scroll;
365 | }
366 |
367 | .dropdown-option {
368 | text-decoration: none;
369 | padding-left: 12px;
370 | height: 36px;
371 | display: flex;
372 | align-items: center;
373 | border: 1px solid var(--zinc-200);
374 | border-top: none;
375 | white-space: nowrap;
376 | overflow: hidden;
377 | background: white;
378 | }
379 |
380 | .pagination-container {
381 | display: flex;
382 | flex-direction: row-reverse;
383 | margin-top: var(--spacing-sm);
384 | }
385 |
386 | .pagination {
387 | overflow: hidden;
388 |
389 | a {
390 | transition-property: background-color;
391 | transition-duration: 500ms;
392 | }
393 |
394 | a:hover {
395 | background-color: var(--zinc-100);
396 | cursor: pointer;
397 | }
398 |
399 | a:first-of-type {
400 | margin-left: 8px;
401 | }
402 |
403 | a.disabled {
404 | cursor: not-allowed;
405 |
406 | svg.icon {
407 | path {
408 | stroke: var(--neutral-400);
409 | }
410 | }
411 | }
412 | }
413 |
414 | .daterange {
415 | padding: 0;
416 | cursor: pointer;
417 | background-color: var(--zinc-100);
418 | border-color: var(--zinc-100);
419 |
420 | a {
421 | transition-property: background-color;
422 | transition-duration: 500ms;
423 | text-decoration: none;
424 | height: 28px;
425 | padding: 6px 12px;
426 | margin: 4px;
427 | }
428 |
429 | a:hover {
430 | background-color: var(--zinc-200);
431 | border-radius: 4px;
432 | }
433 |
434 | a.selected {
435 | background-color: white;
436 | border-radius: 4px;
437 | box-shadow: var(--shadow-1);
438 | }
439 | }
440 |
441 | .pageviews-chart-container {
442 | margin-top: var(--spacing-lg);
443 | border-radius: 6px;
444 | border: 1px solid var(--zinc-200);
445 | padding: 12px;
446 |
447 | .title {
448 | font: var(--sm);
449 | color: var(--neutral-400)
450 | }
451 |
452 | .count {
453 | margin-top: 4px;
454 | font: var(--h3);
455 | }
456 | }
457 |
458 | .barchart {
459 | .bar-background {
460 | fill: var(--zinc-200);
461 | fill-opacity: 0.2;
462 | }
463 |
464 | .bar-foreground {
465 | fill: var(--gray-900);
466 |
467 | .bar:hover {
468 | fill: url(#bar-selected);
469 | }
470 | }
471 |
472 | .tooltip {
473 | position: absolute;
474 | display: none;
475 | flex-direction: column;
476 | align-items: center;
477 | padding: 8px;
478 | border-radius: 6px;
479 | box-shadow: var(--shadow-1);
480 | background: var(--neutral-900);
481 |
482 | .label {
483 | font: var(--sm);
484 | color: var(--neutral-400);
485 | }
486 |
487 | .value {
488 | margin-top: 8px;
489 | color: white;
490 | }
491 | }
492 | }
493 |
494 | /* Lato Regular */
495 | /* https://medium.com/going-fullstack/self-hosting-web-font-files-6a46bfc36ffd */
496 | @font-face {
497 | font-display: block;
498 | font-family: 'Lato';
499 | font-style: normal;
500 | font-weight: 400;
501 | src: url('/assets/lato-v24-latin-regular.woff2') format('woff2');
502 | }
503 |
504 | /* Lato Bold */
505 | @font-face {
506 | font-display: block;
507 | font-family: 'Lato';
508 | font-style: normal;
509 | font-weight: 700;
510 | src: url('/assets/lato-v24-latin-700.woff2') format('woff2');
511 | }
--------------------------------------------------------------------------------
/license.md:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------