├── .gitignore ├── appvariables.toml ├── docker-compose.yml ├── Dockerfile ├── .github └── workflows │ ├── production-workflow.yml │ └── development-workflow.yml ├── go.mod ├── internal ├── domain │ ├── errors.go │ ├── model.go │ └── Session.go ├── data │ ├── UpdateManager.go │ ├── persistence │ │ ├── PersistenceManager.go │ │ └── SqliteManager.go │ ├── model │ │ └── sqlite_db_model.sql │ └── DataModel.go ├── botmodule │ ├── Restorer.go │ ├── Actions.go │ ├── CommandMenu.go │ └── Communicator.go ├── utils │ ├── utils_test.go │ └── Utils.go ├── inputprocess │ └── parsing.go └── sessionmanager │ └── RunningSession.go ├── cmd ├── GoforPomodoroBot │ └── main.go └── GoforPomodoroCheck │ └── main.go ├── go.sum ├── README.md └── LICENSE.txt /.gitignore: -------------------------------------------------------------------------------- 1 | appsettings.toml 2 | .idea/ 3 | Pomodorogram.iml 4 | GoforPomodoro 5 | main 6 | *.db 7 | -------------------------------------------------------------------------------- /appvariables.toml: -------------------------------------------------------------------------------- 1 | # This privacy policy is just an example 2 | 3 | # The regulation of GDPR does not apply to purely personal activities 4 | 5 | PrivacyPolicyEnabled = false 6 | 7 | PrivacySettingsVersion = 1 8 | 9 | PrivacyPolicy1 = """""" 10 | 11 | OpenSource1 = """Did you know that this bot is opensource? It is licensed \ 12 | under AGPL 3.0. The official source code for this bot is available at 13 | \n\n 14 | https://github.com/IThoughtUGNU/GoforPomodoro 15 | \n\n 16 | You can read what the license consists at 17 | \n\n 18 | https://www.gnu.org/licenses/#AGPL 19 | """ -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | services: 3 | goforpomodoro: 4 | image: goforpomodoro 5 | build: 6 | context: . 7 | args: 8 | INTERNAL_SERVER_PORT: ${INTERNAL_SERVER_PORT} 9 | container_name: goforpomodorobot${CONTAINER_NAME_SUFFIX} 10 | volumes: 11 | - ${BOT_DATA_DIR}data/go4pom_data.db:/app/data/go4pom_data.db 12 | - ${BOT_DATA_DIR}appsettings.toml:/app/appsettings.toml 13 | - ${BOT_DATA_DIR}appvariables.toml:/app/appvariables.toml 14 | networks: 15 | goforpomodorobot: 16 | ipv4_address: ${CONTAINER_IP} 17 | restart: always 18 | 19 | networks: 20 | goforpomodorobot: 21 | driver: bridge 22 | ipam: 23 | config: 24 | - subnet: ${SUBNET} 25 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # syntax=docker/dockerfile:1 2 | FROM golang:1.19-alpine as build-stage 3 | WORKDIR /build 4 | COPY ./ ./ 5 | RUN --mount=type=cache,target=/go/pkg CGO_ENABLED=0 go build -o GoforPomodoroCheck cmd/GoforPomodoroCheck/main.go 6 | RUN --mount=type=cache,target=/go/pkg CGO_ENABLED=0 go build -o GoforPomodoroBot cmd/GoforPomodoroBot/main.go 7 | 8 | FROM ubuntu:latest 9 | ARG INTERNAL_SERVER_PORT 10 | WORKDIR /app 11 | COPY --from=build-stage /build/GoforPomodoroCheck ./ 12 | COPY --from=build-stage /build/GoforPomodoroBot ./ 13 | RUN --mount=type=cache,target=/var/cache/apt apt update && apt install -y ca-certificates 14 | ENTRYPOINT [ "bash", "-c", "if ./GoforPomodoroCheck ; then ./GoforPomodoroBot ; fi" ] 15 | EXPOSE $INTERNAL_SERVER_PORT 16 | -------------------------------------------------------------------------------- /.github/workflows/production-workflow.yml: -------------------------------------------------------------------------------- 1 | name: GoforPomodoro 2 | on: 3 | push: 4 | branches: 5 | - 'release' 6 | workflow_dispatch: 7 | jobs: 8 | build-and-deploy: 9 | runs-on: self-hosted 10 | environment: production 11 | steps: 12 | - name: Check out repository code 13 | uses: actions/checkout@v3 14 | - name: Copy appvariables.toml in data folder 15 | run: | 16 | cd ${{ github.workspace }} 17 | cp appvariables.toml ${{ secrets.BOT_DATA_DIR }} 18 | - name: Build & Deploy 19 | run: | 20 | cd ${{ github.workspace }} 21 | DOCKER_BUILDKIT=1 COMPOSE_PROJECT_NAME=production BOT_DATA_DIR=${{ secrets.BOT_DATA_DIR }} INTERNAL_SERVER_PORT=${{ secrets.INTERNAL_SERVER_PORT }} CONTAINER_IP=${{ secrets.CONTAINER_IP }} SUBNET='${{ secrets.SUBNET }}' docker-compose up -d --build 22 | -------------------------------------------------------------------------------- /.github/workflows/development-workflow.yml: -------------------------------------------------------------------------------- 1 | name: GoforPomodoro 2 | on: 3 | push: 4 | branches: 5 | - 'main' 6 | workflow_dispatch: 7 | jobs: 8 | build-and-deploy: 9 | runs-on: self-hosted 10 | environment: development 11 | steps: 12 | - name: Check out repository code 13 | uses: actions/checkout@v3 14 | - name: Copy appvariables.toml in data folder 15 | run: | 16 | cd ${{ github.workspace }} 17 | cp appvariables.toml ${{ secrets.BOT_DATA_DIR }} 18 | - name: Build & Deploy 19 | run: | 20 | cd ${{ github.workspace }} 21 | DOCKER_BUILDKIT=1 COMPOSE_PROJECT_NAME=development BOT_DATA_DIR=${{ secrets.BOT_DATA_DIR }} INTERNAL_SERVER_PORT=${{ secrets.INTERNAL_SERVER_PORT }} CONTAINER_IP=${{ secrets.CONTAINER_IP }} SUBNET='${{ secrets.SUBNET }}' CONTAINER_NAME_SUFFIX='-dev' docker-compose up -d --build 22 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module GoforPomodoro 2 | 3 | go 1.19 4 | 5 | require ( 6 | github.com/BurntSushi/toml v1.2.0 7 | github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 8 | ) 9 | 10 | require ( 11 | github.com/google/uuid v1.3.0 // indirect 12 | github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect 13 | github.com/mattn/go-isatty v0.0.16 // indirect 14 | github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 // indirect 15 | golang.org/x/mod v0.3.0 // indirect 16 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab // indirect 17 | golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78 // indirect 18 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect 19 | lukechampine.com/uint128 v1.1.1 // indirect 20 | modernc.org/cc/v3 v3.38.1 // indirect 21 | modernc.org/ccgo/v3 v3.16.9 // indirect 22 | modernc.org/libc v1.19.0 // indirect 23 | modernc.org/mathutil v1.5.0 // indirect 24 | modernc.org/memory v1.4.0 // indirect 25 | modernc.org/opt v0.1.3 // indirect 26 | modernc.org/sqlite v1.19.1 // indirect 27 | modernc.org/strutil v1.1.3 // indirect 28 | modernc.org/token v1.0.1 // indirect 29 | ) 30 | -------------------------------------------------------------------------------- /internal/domain/errors.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package domain 17 | 18 | type AlreadySubscribed struct{} 19 | 20 | func (_ AlreadySubscribed) Error() string { 21 | return "you were already subscribed" 22 | } 23 | 24 | type AlreadyUnsubscribed struct{} 25 | 26 | func (_ AlreadyUnsubscribed) Error() string { 27 | return "you were already unsubscribed" 28 | } 29 | 30 | type SubscriptionError struct{} 31 | 32 | func (_ SubscriptionError) Error() string { 33 | return "cannot subscribe" 34 | } 35 | 36 | type OperationError struct{} 37 | 38 | func (_ OperationError) Error() string { 39 | return "error with this operation right now" 40 | } 41 | -------------------------------------------------------------------------------- /internal/data/UpdateManager.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package data 17 | 18 | /* 19 | import ( 20 | "GoforPomodoro/internal/domain" 21 | "log" 22 | "time" 23 | ) 24 | 25 | type DispatchUpdate struct { 26 | ChatId domain.ChatID 27 | } 28 | 29 | type UpdateManager struct { 30 | AppState *domain.AppState 31 | 32 | updateChannel chan DispatchUpdate 33 | } 34 | 35 | func (m *UpdateManager) WriteChannel() chan<- DispatchUpdate { 36 | return m.updateChannel 37 | } 38 | 39 | func (m *UpdateManager) StartLoop() { 40 | mainLoop: 41 | for { 42 | select { 43 | case update, ok := <-m.updateChannel: 44 | if ok { 45 | log.Println("[UpdateManager] update received, calling...") 46 | UpdateUserSessionRunning(m.AppState, update.ChatId) 47 | } else { 48 | log.Println("updateChannel NOT ok.") 49 | break mainLoop 50 | } 51 | default: 52 | time.Sleep(500 * time.Millisecond) 53 | } 54 | } 55 | defer func() { 56 | close(m.updateChannel) 57 | m.updateChannel = nil 58 | }() 59 | } 60 | */ 61 | -------------------------------------------------------------------------------- /internal/botmodule/Restorer.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package botmodule 17 | 18 | import ( 19 | "GoforPomodoro/internal/data" 20 | "GoforPomodoro/internal/domain" 21 | tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" 22 | "log" 23 | ) 24 | 25 | func RestoreSessions( 26 | appState *domain.AppState, 27 | appVariables *domain.AppVariables, 28 | bot *tgbotapi.BotAPI, 29 | ) { 30 | if appState.PersistenceManager != nil { 31 | pairs, err := appState.PersistenceManager.GetActiveChatSettings() 32 | 33 | log.Printf("[Restorer::RestoreSessions] #sessions to restore: %v\n", len(pairs)) 34 | if err != nil { 35 | log.Printf("[Restorer::RestoreSessions] error: %v\n", err.Error()) 36 | } else { 37 | data.PreloadUsersSettings(appState, pairs) 38 | 39 | for _, pair := range pairs { 40 | chatId := pair.First 41 | settings := pair.Second 42 | 43 | log.Printf("[Restorer::RestoreSessions] Restoring session for chat id: %v", chatId) 44 | 45 | runningSession := settings.SessionRunning 46 | 47 | communicator := GetCommunicator(appState, appVariables, chatId, bot) 48 | ActionRestoreSprint(chatId, appState, runningSession, communicator) 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /internal/data/persistence/PersistenceManager.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package persistence 17 | 18 | import ( 19 | "GoforPomodoro/internal/domain" 20 | "GoforPomodoro/internal/utils" 21 | ) 22 | 23 | // Manager interface for types that want to manage persistence. 24 | // The first three methods 25 | // 26 | // GetChatSettings 27 | // StoreChatSettings 28 | // DeleteChatSettings 29 | // 30 | // are classical operations of key-value stores and alike (get/update/delete). 31 | // 32 | // Then GetActiveChatSettings is defined for a (possibly efficient) retrieval 33 | // of the chats that have/had a session running. 34 | // 35 | // Since the store is as of now thought to be key-value based, the user of this 36 | // interface is not expected to perform complex queries, but just the minimum 37 | // that is needed for correctly running the bot. 38 | type Manager interface { 39 | // GetChatSettings get the settings for the provided chat ID 40 | GetChatSettings(domain.ChatID) (*domain.Settings, error) 41 | 42 | StoreChatSettings(id domain.ChatID, settings *domain.Settings) error 43 | DeleteChatSettings(id domain.ChatID) error 44 | 45 | GetActiveChatSettings() ([]utils.Pair[domain.ChatID, *domain.Settings], error) 46 | 47 | LockDB() 48 | UnlockDB() 49 | } 50 | -------------------------------------------------------------------------------- /internal/data/model/sqlite_db_model.sql: -------------------------------------------------------------------------------- 1 | -- This file is part of GoforPomodoro. 2 | -- 3 | -- GoforPomodoro is free software: you can redistribute it and/or modify 4 | -- it under the terms of the GNU Affero General Public License as published by 5 | -- the Free Software Foundation, either version 3 of the License, or 6 | -- (at your option) any later version. 7 | -- 8 | -- GoforPomodoro is distributed in the hope that it will be useful, 9 | -- but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | -- GNU Affero General Public License for more details. 12 | -- 13 | -- You should have received a copy of the GNU Affero General Public License 14 | -- along with GoforPomodoro. If not, see . 15 | 16 | DROP TABLE IF EXISTS chat_settings; 17 | 18 | CREATE TABLE IF NOT EXISTS chat_settings( 19 | chat_id INTEGER NOT NULL PRIMARY KEY, 20 | 21 | default_sprint_duration_set INTEGER, 22 | default_pomodoro_duration_set INTEGER, 23 | default_rest_duration_set INTEGER, 24 | 25 | running_sprint_duration_set INTEGER, 26 | running_pomodoro_duration_set INTEGER, 27 | running_rest_duration_set INTEGER, 28 | 29 | running_sprint_duration INTEGER, 30 | running_pomodoro_duration INTEGER, 31 | running_rest_duration INTEGER, 32 | 33 | running_end_next_sprint_ts TIMESTAMP, 34 | running_end_next_rest_ts TIMESTAMP, 35 | 36 | running_is_cancel INTEGER, -- bool 37 | running_is_paused INTEGER, -- bool 38 | running_is_rest INTEGER, -- bool 39 | running_is_finished INTEGER, -- bool 40 | 41 | autorun INTEGER, -- bool 42 | is_group INTEGER, -- bool 43 | subscribers TEXT, -- we use this to store de-normalized arrays (encoded) 44 | 45 | active INTEGER -- bool 46 | ); 47 | 48 | CREATE INDEX ex1 ON chat_settings(active) WHERE active = 1; 49 | -------------------------------------------------------------------------------- /cmd/GoforPomodoroBot/main.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package main 17 | 18 | import ( 19 | "GoforPomodoro/internal/botmodule" 20 | "GoforPomodoro/internal/data" 21 | "GoforPomodoro/internal/data/persistence" 22 | "fmt" 23 | "log" 24 | ) 25 | 26 | func main() { 27 | appVariables, err := data.LoadAppVariables() 28 | if err != nil { 29 | log.Fatal(err) 30 | } 31 | 32 | settings, err := data.LoadAppSettings() 33 | if err != nil { 34 | log.Fatal(err) 35 | } 36 | 37 | sqliteManager := &persistence.SqliteManager{} 38 | dbErr := sqliteManager.OpenDatabase("./data/go4pom_data.db") 39 | if dbErr != nil { 40 | sqliteManager = nil // DB-less mode. 41 | log.Println("[main] Running bot with no database (there will be no persistence).") 42 | // panic(dbErr) 43 | } 44 | 45 | debugMode := settings.DebugMode 46 | 47 | appState, err := data.LoadAppState(sqliteManager, debugMode) 48 | if err != nil { 49 | panic(err) 50 | } 51 | 52 | fmt.Printf("Hello from Go for Pomodoro!\n\n(debug mode set to: %v)\n\n", debugMode) 53 | 54 | // serverActionChannel := make(chan domain.DispatchServerAction) 55 | 56 | // Listen for /shutdown 57 | if settings.ListenAddressPrivate != "" && settings.ListenPortPrivate != 0 { 58 | go botmodule.ListenPrivateHTTP( 59 | appState, 60 | settings.ListenAddressPrivate, 61 | settings.ListenPortPrivate, 62 | ) 63 | } 64 | 65 | // Start the actual bot 66 | botmodule.CommandMenuLoop(settings, appVariables, appState) 67 | } 68 | -------------------------------------------------------------------------------- /internal/utils/utils_test.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package utils 17 | 18 | import ( 19 | "testing" 20 | ) 21 | 22 | func TestIsCapitalizedLetter(t *testing.T) { 23 | 24 | for _, c := range "ABCDEFGHIJKLMNOPQRSTUVWXYZ" { 25 | if !IsCapitalizedLetter(c) { 26 | t.Fatalf("%c is a capitalized letter (returned false).", c) 27 | } 28 | } 29 | for _, c := range "0123456789abcdefghijklmnopqrstuvwxyz;" { 30 | if IsCapitalizedLetter(c) { 31 | t.Fatalf("%c is NOT a capitalized letter (returned true).", c) 32 | } 33 | } 34 | 35 | for _, c := range "ABCDEFGHIJKLMNOPQRSTUVWXYZ" { 36 | if !IsCapitalizedLetterStr(string(c)) { 37 | t.Fatalf("%c is a capitalized letter (returned false).", c) 38 | } 39 | } 40 | for _, c := range "0123456789abcdefghijklmnopqrstuvwxyz;" { 41 | if IsCapitalizedLetterStr(string(c)) { 42 | t.Fatalf("%c is NOT a capitalized letter (returned true).", c) 43 | } 44 | } 45 | } 46 | 47 | func TestAfterRemoveEl(t *testing.T) { 48 | var st_ = [...]string{"ciao", "mondo"} 49 | var st []string = st_[:] 50 | 51 | s1, err := AfterRemoveEl(st, "ciao") 52 | if err != nil { 53 | t.Fatalf("Should have not returned error.") 54 | } 55 | if len(s1) > 1 { 56 | t.Fatalf("Didn't delete element!") 57 | } 58 | 59 | s2, err := AfterRemoveEl(st, "mondo") 60 | if err != nil { 61 | t.Fatalf("Should have not returned error.") 62 | } 63 | if len(s2) > 1 { 64 | t.Fatalf("Didn't delete element!") 65 | } 66 | 67 | s3, err := AfterRemoveEl(s1, "mondo") 68 | s4, err := AfterRemoveEl(s2, "ciao") 69 | 70 | if len(s3) > 0 || len(s4) > 0 { 71 | t.Fatalf("s3/s4 not equal to empty slice") 72 | } 73 | } 74 | 75 | func TestNiceTimeFormatting(t *testing.T) { 76 | { 77 | ok := NiceTimeFormatting(10) == "10 seconds" 78 | if !ok { 79 | t.Fatalf("NiceTimeFormatting(10) != \"10 seconds\" ") 80 | } 81 | } 82 | 83 | { 84 | lhs := "2 minutes" 85 | rhs := NiceTimeFormatting(100) 86 | ok := lhs == rhs 87 | if !ok { 88 | t.Fatalf("error second check. Should be %s, instead it is %s", lhs, rhs) 89 | } 90 | } 91 | 92 | { 93 | lhs := "1 hour 55 minutes" 94 | rhs := NiceTimeFormatting(115 * 60) 95 | ok := lhs == rhs 96 | if !ok { 97 | t.Fatalf("error third check. Should be %s, instead it is %s", lhs, rhs) 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /cmd/GoforPomodoroCheck/main.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package main 17 | 18 | import ( 19 | "GoforPomodoro/internal/data" 20 | "GoforPomodoro/internal/data/persistence" 21 | "fmt" 22 | tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" 23 | "os" 24 | "runtime" 25 | ) 26 | 27 | type ErrorType int 28 | 29 | const ( 30 | NoAppSettings ErrorType = 1 << iota // 1 31 | NoDB // 2 32 | NoAPIConnection // 4 33 | ) 34 | 35 | func main() { 36 | fmt.Printf("Go for Pomodoro FOSS -- sanity check.\n") 37 | fmt.Println("--------------------------------------------------------------") 38 | var noAppSettings ErrorType 39 | var noDb ErrorType 40 | var noApiConn ErrorType 41 | 42 | okSymbol := "✅" 43 | errSymbol := "❌" 44 | 45 | fmt.Printf("(Go runtime version: %s)\n\n", runtime.Version()) 46 | 47 | settings, err := data.LoadAppSettings() 48 | 49 | var s string 50 | if err != nil || (len(settings.ApiToken) == 0) { 51 | s = errSymbol 52 | noAppSettings = NoAppSettings 53 | } else { 54 | s = okSymbol 55 | } 56 | fmt.Printf("- [%v] appsettings.toml file\n", s) 57 | if err != nil { 58 | fmt.Println(" Please create such file and provide ApiToken and BotName accordingly to\n" + 59 | " the README.") 60 | } 61 | fmt.Println() 62 | 63 | sqliteManager := &persistence.SqliteManager{} 64 | dbErr := sqliteManager.OpenDatabase("./data/go4pom_data.db") 65 | if dbErr != nil { 66 | sqliteManager = nil // DB-less mode. 67 | s = errSymbol 68 | noDb = NoDB 69 | } else { 70 | s = okSymbol 71 | } 72 | fmt.Printf("- [%v] Database connected\n", s) 73 | if dbErr != nil { 74 | fmt.Printf(" A database instance is not mandatory. The bot can also run without any\n" + 75 | " persistence. But keep in mind that doing so will make lose all data and\n" + 76 | " irremediably lose all the sessions running after the application is\n" + 77 | " shutted down.\n") 78 | } 79 | fmt.Println() 80 | 81 | bot, err := tgbotapi.NewBotAPI(settings.ApiToken) 82 | if err != nil { 83 | s = errSymbol 84 | noApiConn = NoAPIConnection 85 | } else { 86 | s = okSymbol 87 | } 88 | fmt.Printf("- [%v] Telegram API connection\n", s) 89 | if err == nil { 90 | fmt.Printf( 91 | " Authorized on account %s\n", bot.Self.UserName) 92 | } else { 93 | fmt.Println( 94 | " No account authorized. The application will not work without a valid API\n" + 95 | " key and connection.") 96 | } 97 | fmt.Println() 98 | fmt.Println("--------------------------------------------------------------") 99 | fmt.Println() 100 | 101 | os.Exit(int(noAppSettings | noDb | noApiConn)) 102 | } 103 | -------------------------------------------------------------------------------- /internal/domain/model.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package domain 17 | 18 | import ( 19 | "GoforPomodoro/internal/utils" 20 | "sync" 21 | ) 22 | 23 | type PrivacySettingsVersion int 24 | 25 | type PrivacySettingsType int 26 | 27 | const ( 28 | AcceptedEssential PrivacySettingsType = 1 << iota // 1 29 | AcceptedAll // 2 30 | ) 31 | 32 | func (privacy PrivacySettingsType) IsZero() bool { 33 | return privacy == 0 34 | } 35 | 36 | func (privacy PrivacySettingsType) HasAcceptedEssential() bool { 37 | return privacy&AcceptedEssential != 0 || 38 | privacy&AcceptedAll != 0 39 | } 40 | 41 | func (privacy PrivacySettingsType) HasAcceptedAll() bool { 42 | return privacy&AcceptedEssential != 0 || 43 | privacy&AcceptedAll != 0 44 | } 45 | 46 | type AppSettings struct { 47 | ApiToken string 48 | BotName string 49 | DebugMode bool 50 | AdminIds []ChatID 51 | ListenAddressPrivate string 52 | ListenPortPrivate int 53 | } 54 | 55 | type AppVariables struct { 56 | PrivacyPolicy1 string 57 | OpenSource1 string 58 | PrivacySettingsVersion 59 | PrivacyPolicyEnabled bool 60 | } 61 | 62 | func (v AppVariables) IsPrivacyPolicyVersionUpdated(version PrivacySettingsVersion) bool { 63 | return version == v.PrivacySettingsVersion 64 | } 65 | 66 | type ChatID int64 67 | 68 | type Settings struct { 69 | SessionDefault SessionDefaultData 70 | SessionRunning *Session 71 | Autorun bool 72 | IsGroup bool 73 | Subscribers []ChatID 74 | PrivacySettings PrivacySettingsType 75 | PrivacySettingsVersion 76 | } 77 | 78 | type PersistenceManager interface { 79 | GetChatSettings(ChatID) (*Settings, error) 80 | 81 | StoreChatSettings(id ChatID, settings *Settings) error 82 | DeleteChatSettings(id ChatID) error 83 | 84 | GetActiveChatSettings() ([]utils.Pair[ChatID, *Settings], error) 85 | 86 | LockDB() 87 | UnlockDB() 88 | } 89 | 90 | type AppState struct { 91 | DebugMode bool 92 | 93 | PersistenceManager PersistenceManager 94 | 95 | UsersSettings map[ChatID]*Settings 96 | UsersSettingsLock sync.RWMutex 97 | } 98 | 99 | func (appState *AppState) ReadSettings( 100 | chatId ChatID, 101 | ) *Settings { 102 | appState.UsersSettingsLock.RLock() 103 | defer appState.UsersSettingsLock.RUnlock() 104 | 105 | return appState.UsersSettings[chatId] 106 | } 107 | 108 | func (appState *AppState) WriteSettings( 109 | chatId ChatID, 110 | settings *Settings, 111 | ) { 112 | appState.UsersSettingsLock.Lock() 113 | defer appState.UsersSettingsLock.Unlock() 114 | 115 | appState.UsersSettings[chatId] = settings 116 | } 117 | 118 | //type DispatchServerAction struct { 119 | // Shutdown bool 120 | //} 121 | -------------------------------------------------------------------------------- /internal/botmodule/Actions.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package botmodule 17 | 18 | import ( 19 | "GoforPomodoro/internal/data" 20 | "GoforPomodoro/internal/domain" 21 | "GoforPomodoro/internal/sessionmanager" 22 | ) 23 | 24 | func ActionRestoreSprint( 25 | chatId domain.ChatID, 26 | appState *domain.AppState, 27 | session *domain.Session, 28 | communicator *Communicator, 29 | ) { 30 | go sessionmanager.SpawnSessionTimer( 31 | appState, 32 | chatId, 33 | session, 34 | communicator.RestBeginHandler, 35 | communicator.RestFinishedHandler, 36 | communicator.SessionFinishedHandler, 37 | communicator.SessionPausedHandler, 38 | ) 39 | } 40 | 41 | func ActionCancelSprint( 42 | senderId domain.ChatID, 43 | chatId domain.ChatID, 44 | appState *domain.AppState, 45 | communicator *Communicator, 46 | ) { 47 | session := data.GetUserSessionRunning(appState, chatId, senderId) 48 | 49 | var err error 50 | if !session.IsPaused() { 51 | err = sessionmanager.CancelSession(session) 52 | } else { 53 | session.Cancel() 54 | communicator.SessionFinishedHandler(chatId, session, sessionmanager.PomodoroCanceled) 55 | } 56 | 57 | communicator.SessionCanceled(err, *session) 58 | } 59 | 60 | func ActionResumeSprint( 61 | senderId domain.ChatID, 62 | chatId domain.ChatID, 63 | appState *domain.AppState, 64 | communicator *Communicator, 65 | ) { 66 | session := data.GetUserSessionRunning(appState, chatId, senderId) 67 | communicator.SessionResumed( 68 | sessionmanager.ResumeSession( 69 | appState, 70 | chatId, 71 | session, 72 | communicator.RestBeginHandler, 73 | communicator.RestFinishedHandler, 74 | communicator.SessionFinishedHandler, 75 | communicator.SessionPausedHandler, 76 | ), 77 | session, 78 | ) 79 | } 80 | 81 | func ActionStartSprint( 82 | senderId domain.ChatID, 83 | chatId domain.ChatID, 84 | appState *domain.AppState, 85 | communicator *Communicator, 86 | ) { 87 | 88 | // log.Printf("[NO-DB TEST] ActionStartSprint!!\n") 89 | session := data.GetUserSessionRunning(appState, chatId, senderId) 90 | 91 | // log.Printf("[NO-DB TEST] data.GetUserSessionRunning succeded\n") 92 | if !session.IsStopped() { 93 | communicator.SessionAlreadyRunning() 94 | // log.Printf("[NO-DB TEST] session already running: stopping\n") 95 | return 96 | } 97 | session = data.GetNewUserSessionRunning(appState, chatId, senderId) 98 | 99 | // log.Printf("[NO-DB TEST] new session running: %v\n", session) 100 | communicator.SessionStarted( 101 | session, 102 | sessionmanager.StartSession( 103 | appState, 104 | chatId, 105 | session, 106 | communicator.RestBeginHandler, 107 | communicator.RestFinishedHandler, 108 | communicator.SessionFinishedHandler, 109 | communicator.SessionPausedHandler, 110 | ), 111 | ) 112 | } 113 | -------------------------------------------------------------------------------- /internal/utils/Utils.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package utils 17 | 18 | import ( 19 | "errors" 20 | "fmt" 21 | "math" 22 | "time" 23 | ) 24 | 25 | func NiceTimeFormatting64(seconds int64) string { 26 | if seconds > 60*60 { 27 | // >1 hour 28 | minutes := int(math.Ceil(float64(seconds) / 60.0)) 29 | hours := int(math.Floor(float64(minutes) / 60.0)) 30 | 31 | minutes = minutes % 60 32 | 33 | var hoursTxt string 34 | if hours == 1 { 35 | hoursTxt = "hour" 36 | } else { 37 | hoursTxt = "hours" 38 | } 39 | 40 | return fmt.Sprintf("%d %s %d minutes", hours, hoursTxt, minutes) 41 | } else if seconds > 60 { 42 | // >1 minute 43 | 44 | minutes := int(math.Ceil(float64(seconds) / 60.0)) 45 | return fmt.Sprintf("%d minutes", minutes) 46 | } else { 47 | // <=1 minute 48 | return fmt.Sprintf("%d seconds", seconds) 49 | } 50 | } 51 | 52 | func NiceTimeFormatting(seconds int) string { 53 | return NiceTimeFormatting64(int64(seconds)) 54 | } 55 | 56 | func In[T comparable](element T, array []T) bool { 57 | found := false 58 | for _, v := range array { 59 | if element == v { 60 | found = true 61 | } 62 | } 63 | return found 64 | } 65 | 66 | func Contains[T comparable](array []T, element T) bool { 67 | return In(element, array) 68 | } 69 | 70 | // AfterRemove 71 | // Make a copy of a slice without an element; will not modify original slice. 72 | func AfterRemove[T any](s []T, index int) []T { 73 | ret := make([]T, 0) 74 | ret = append(ret, s[:index]...) 75 | return append(ret, s[index+1:]...) 76 | } 77 | 78 | func IndexOf[T comparable](element T, data []T) int { 79 | for k, v := range data { 80 | if element == v { 81 | return k 82 | } 83 | } 84 | return -1 //not found. 85 | } 86 | 87 | // AfterRemoveEl 88 | // Make a copy of a slice `s` without the element `el`. 89 | // 90 | // Does not modify the slice passed in input. 91 | // 92 | // Returns err if `el` was not in `s`. 93 | func AfterRemoveEl[T comparable](s []T, el T) ([]T, error) { 94 | index := IndexOf(el, s) 95 | 96 | if index == -1 { 97 | return s, errors.New("element was not in array") 98 | } 99 | 100 | return AfterRemove(s, index), nil 101 | } 102 | 103 | func TimePtr(t time.Time) *time.Time { 104 | return &t 105 | } 106 | 107 | type Pair[T, U any] struct { 108 | First T 109 | Second U 110 | } 111 | 112 | type EmptyOptionalError struct{} 113 | 114 | func (_ EmptyOptionalError) Error() string { 115 | return "Value is empty" 116 | } 117 | 118 | type Optional[T any] struct { 119 | value T 120 | isEmpty bool 121 | } 122 | 123 | func OptionalOf[T any](value T) (opt Optional[T]) { 124 | opt.isEmpty = false 125 | opt.value = value 126 | 127 | return 128 | } 129 | 130 | func OptionalOfNil[T any]() (opt Optional[T]) { 131 | opt.isEmpty = true 132 | 133 | return 134 | } 135 | 136 | func (opt Optional[T]) GetValue() (value T, err error) { 137 | if opt.isEmpty { 138 | err = EmptyOptionalError{} 139 | } else { 140 | value = opt.value 141 | err = nil 142 | } 143 | return 144 | } 145 | 146 | func (opt Optional[T]) IsEmpty() bool { 147 | return opt.isEmpty 148 | } 149 | 150 | func YesNo(value bool) string { 151 | if value { 152 | return "Yes" 153 | } else { 154 | return "No" 155 | } 156 | } 157 | 158 | func IsCapitalizedLetter(c rune) bool { 159 | return 'A' <= c && c <= 'Z' 160 | } 161 | 162 | func IsCapitalizedLetterStr(str string) bool { 163 | if len(str) != 1 { 164 | return false 165 | } 166 | for _, c := range str { 167 | return IsCapitalizedLetter(c) 168 | } 169 | return false 170 | } 171 | -------------------------------------------------------------------------------- /internal/inputprocess/parsing.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package inputprocess 17 | 18 | import ( 19 | "GoforPomodoro/internal/domain" 20 | "GoforPomodoro/internal/utils" 21 | "errors" 22 | "regexp" 23 | "strconv" 24 | "strings" 25 | ) 26 | 27 | const BasicPattern = `\/([1-9]\d*)(for([A-Z]|([1-9]\d*))(rest([1-9]\d*))?)?` // `\/([1-9]\d*)` 28 | 29 | const ( 30 | MinutesGroup = 1 31 | CardinalityGroup = 3 32 | RestGroup = 6 33 | ) 34 | 35 | var privacySettingsCommands = "/accept_all::/accept_essential" 36 | 37 | func IsPrivacySettingsCommand(text string) bool { 38 | commands := strings.Split(privacySettingsCommands, "::") 39 | 40 | return utils.Contains(commands, text) 41 | } 42 | 43 | func CommandFrom(appSettings *domain.AppSettings, text string) string { 44 | command := strings.Split(text, " ")[0] 45 | 46 | botName := appSettings.BotName 47 | if !strings.HasPrefix(botName, "@") { 48 | botName = "@" + botName 49 | } 50 | 51 | if strings.HasSuffix(command, botName) { 52 | command = strings.Split(command, "@")[0] 53 | } 54 | 55 | return command 56 | } 57 | 58 | func ParametersFrom(text string) []string { 59 | return strings.Split(text, " ")[1:] 60 | } 61 | 62 | func ValidateSessionParsed(sessionData domain.SessionDefaultData) (domain.SessionDefaultData, error) { 63 | // The maximum time for a session shall not exceed 48 hours 64 | var limit int64 = 48 * 60 * 60 65 | 66 | sessionTime := sessionData.CalculateSessionTimeInSeconds() 67 | 68 | if sessionTime > limit { 69 | return sessionData, errors.New("this session lasts too long") 70 | } else { 71 | return sessionData, nil 72 | } 73 | } 74 | 75 | func ParsePatternToSession(r *regexp.Regexp, text string) utils.Optional[domain.SessionDefaultData] { 76 | if r == nil { 77 | r = regexp.MustCompile(BasicPattern) 78 | } 79 | matches := r.FindAllStringSubmatch(text, -1) 80 | 81 | var sessionDefaultData domain.SessionDefaultData 82 | 83 | match := false 84 | for _, v := range matches { 85 | match = true 86 | 87 | sessionDefaultData.SprintDurationSet = 1 88 | 89 | // Mandatory parameter for this command. 90 | pomDuration, err := strconv.Atoi(v[MinutesGroup]) 91 | if err != nil { 92 | return utils.OptionalOfNil[domain.SessionDefaultData]() 93 | } 94 | sessionDefaultData.PomodoroDurationSet = domain.PomodoroDuration(pomDuration * 60) // time from minutes to seconds. 95 | 96 | // Other parameters are optional 97 | cardinality := v[CardinalityGroup] 98 | if utils.IsCapitalizedLetterStr(cardinality) { 99 | // A capitalized letter was provided 100 | sessionDefaultData.SprintDurationSet = domain.UnspecifiedSprintCardinality 101 | 102 | // Default 5 minutes of rest duration in case user did not specify. 103 | sessionDefaultData.RestDurationSet = domain.DefaultRestTime 104 | } else { 105 | // A number or else was provided 106 | sprintDuration, err := strconv.Atoi(v[CardinalityGroup]) 107 | if err == nil { 108 | sessionDefaultData.SprintDurationSet = domain.SprintDuration(sprintDuration) 109 | 110 | // Default 5 minutes of rest duration in case user did not specify. 111 | sessionDefaultData.RestDurationSet = domain.DefaultRestTime 112 | } 113 | } 114 | 115 | restDuration, err := strconv.Atoi(v[RestGroup]) 116 | if err == nil { 117 | sessionDefaultData.RestDurationSet = domain.RestDuration(restDuration * 60) 118 | } 119 | 120 | break 121 | } 122 | 123 | if !match { 124 | return utils.OptionalOfNil[domain.SessionDefaultData]() 125 | } 126 | 127 | return utils.OptionalOf(sessionDefaultData) 128 | } 129 | -------------------------------------------------------------------------------- /internal/sessionmanager/RunningSession.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package sessionmanager 17 | 18 | import ( 19 | "GoforPomodoro/internal/data" 20 | "GoforPomodoro/internal/domain" 21 | "errors" 22 | "log" 23 | "time" 24 | ) 25 | 26 | type PomodoroEndKind int 27 | 28 | const ( 29 | PomodoroFinished PomodoroEndKind = iota 30 | PomodoroCanceled 31 | ) 32 | 33 | func StartSession( 34 | appState *domain.AppState, 35 | userId domain.ChatID, 36 | currentSession *domain.Session, 37 | restBeginHandler func(id domain.ChatID, session *domain.Session), 38 | restFinishedHandler func(id domain.ChatID, session *domain.Session), 39 | endSessionHandler func(id domain.ChatID, session *domain.Session, endKind PomodoroEndKind), 40 | pauseSessionHandler func(id domain.ChatID, session *domain.Session), 41 | ) error { 42 | if currentSession.IsZero() { 43 | return errors.New("the session is effectively nil") 44 | } 45 | 46 | currentSession.Start() 47 | 48 | go SpawnSessionTimer( 49 | appState, 50 | userId, 51 | currentSession, 52 | restBeginHandler, 53 | restFinishedHandler, 54 | endSessionHandler, 55 | pauseSessionHandler, 56 | ) 57 | return nil 58 | } 59 | 60 | func SpawnSessionTimer( 61 | appState *domain.AppState, 62 | chatId domain.ChatID, 63 | currentSession *domain.Session, 64 | restBeginHandler func(id domain.ChatID, session *domain.Session), 65 | restFinishedHandler func(id domain.ChatID, session *domain.Session), 66 | endSessionHandler func(id domain.ChatID, session *domain.Session, endKind PomodoroEndKind), 67 | pauseSessionHandler func(id domain.ChatID, session *domain.Session), 68 | ) { 69 | // We update session running because it started (or resumed) 70 | data.UpdateUserSessionRunning(appState, chatId) 71 | mainLoop: 72 | for { 73 | select { 74 | case action, ok := <-currentSession.ReadingActionChannel(): 75 | if ok { 76 | // The event was internal (rest started/finished) 77 | if action.RestStarted || action.RestFinished { 78 | if action.RestStarted { 79 | currentSession.RestStarted() 80 | restBeginHandler(chatId, currentSession) 81 | } 82 | if action.RestFinished { 83 | currentSession.RestFinished() 84 | restFinishedHandler(chatId, currentSession) 85 | } 86 | // We update session running because it changed state 87 | // (rest started or finished) 88 | data.UpdateUserSessionRunning(appState, chatId) 89 | continue mainLoop 90 | } 91 | 92 | // The event was either external (paused/canceled) or internal (finished) 93 | if action.Paused || action.Canceled || action.Finished { 94 | if action.Paused { 95 | currentSession.Pause() 96 | pauseSessionHandler(chatId, currentSession) 97 | } else if action.Canceled { 98 | currentSession.Cancel() 99 | endSessionHandler(chatId, currentSession, PomodoroCanceled) 100 | } else if action.Finished { 101 | currentSession.SetFinished() 102 | endSessionHandler(chatId, currentSession, PomodoroFinished) 103 | } 104 | // We update session running because it changed state 105 | // (paused, canceled or finished) 106 | data.UpdateUserSessionRunning(appState, chatId) 107 | break mainLoop 108 | } 109 | } else { 110 | currentSession.ActionsChannel = nil 111 | log.Println("Session channel is closed. Aborting main loop...") 112 | break mainLoop 113 | } 114 | default: 115 | time.Sleep(1 * time.Second) 116 | 117 | isRest := currentSession.IsRest() 118 | 119 | if !isRest && currentSession.HasSprintEndTimePassed() { 120 | currentSession.DecreaseSprintDuration() 121 | 122 | // if currentSession.GetSprintDuration() < 0 { 123 | if currentSession.SprintDurationFinished() { 124 | currentSession.WritingActionChannel() <- domain.DispatchAction{Finished: true} 125 | continue mainLoop 126 | } 127 | 128 | // if SprintDuration still >= 0 or is UnspecifiedSprintCardinality, we have rest now 129 | currentSession.WritingActionChannel() <- domain.DispatchAction{RestStarted: true} 130 | continue mainLoop 131 | } else if isRest && currentSession.HasRestEndTimePassed() { 132 | 133 | currentSession.WritingActionChannel() <- domain.DispatchAction{RestFinished: true} 134 | continue mainLoop 135 | } 136 | } 137 | } 138 | defer currentSession.ClearChannel() 139 | } 140 | 141 | func PauseSession(currentSession *domain.Session) error { 142 | if currentSession.IsPaused() { 143 | return errors.New("sessionDefault already paused") 144 | } 145 | 146 | currentSession.WritingActionChannel() <- domain.DispatchAction{Paused: true} 147 | return nil 148 | } 149 | 150 | func CancelSession(currentSession *domain.Session) error { 151 | if currentSession.IsCanceled() { 152 | return errors.New("sessionDefault already canceled") 153 | } 154 | 155 | currentSession.WritingActionChannel() <- domain.DispatchAction{Canceled: true} 156 | return nil 157 | } 158 | 159 | func ResumeSession( 160 | appState *domain.AppState, 161 | userId domain.ChatID, 162 | currentSession *domain.Session, 163 | restBeginHandler func(id domain.ChatID, session *domain.Session), 164 | restFinishedHandler func(id domain.ChatID, session *domain.Session), 165 | endSessionHandler func(id domain.ChatID, session *domain.Session, endKind PomodoroEndKind), 166 | pauseSessionHandler func(id domain.ChatID, session *domain.Session), 167 | ) error { 168 | if currentSession.IsZero() { 169 | return errors.New("the session is effectively nil") 170 | } 171 | if !currentSession.IsStopped() { 172 | return errors.New("session already running") 173 | } 174 | if currentSession.IsCanceled() { 175 | return errors.New("session was canceled") 176 | } 177 | 178 | currentSession.Resume() 179 | 180 | go SpawnSessionTimer( 181 | appState, 182 | userId, 183 | currentSession, 184 | restBeginHandler, 185 | restFinishedHandler, 186 | endSessionHandler, 187 | pauseSessionHandler, 188 | ) 189 | return nil 190 | } 191 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/BurntSushi/toml v1.2.0 h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0= 2 | github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= 3 | github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= 4 | github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc= 5 | github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= 6 | github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 7 | github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= 8 | github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= 9 | github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 h1:Z9n2FFNUXsshfwJMBgNA0RU6/i7WVaAegv3PtuIHPMs= 10 | github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51/go.mod h1:CzGEWj7cYgsdH8dAjBGEr58BoE7ScuLd+fwFZ44+/x8= 11 | github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= 12 | github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= 13 | github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= 14 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 15 | github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0 h1:OdAsTTz6OkFY5QxjkYwrChwuRruF69c169dPK26NUlk= 16 | github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= 17 | github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= 18 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 19 | golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 20 | golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= 21 | golang.org/x/mod v0.3.0 h1:RM4zey1++hCTbCVQfnWeKs9/IEsaBLA8vTkd0WVtmH4= 22 | golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= 23 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 24 | golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= 25 | golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= 26 | golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 27 | golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 28 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 29 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 30 | golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 31 | golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 32 | golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 33 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab h1:2QkjZIsXupsJbJIdSjjUOgWK3aEtzyuh2mPt3l/CkeU= 34 | golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 35 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 36 | golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= 37 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 38 | golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= 39 | golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78 h1:M8tBwCtWD/cZV9DZpFYRUgaymAYAr+aIUTWzDaM3uPs= 40 | golang.org/x/tools v0.0.0-20201124115921-2c860bdd6e78/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= 41 | golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 42 | golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 43 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 44 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= 45 | golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 46 | lukechampine.com/uint128 v1.1.1 h1:pnxCASz787iMf+02ssImqk6OLt+Z5QHMoZyUXR4z6JU= 47 | lukechampine.com/uint128 v1.1.1/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk= 48 | modernc.org/cc/v3 v3.36.2/go.mod h1:NFUHyPn4ekoC/JHeZFfZurN6ixxawE1BnVonP/oahEI= 49 | modernc.org/cc/v3 v3.38.1 h1:Yu2IiiRpustRFUgMDZKwVn2RvyJzpfYSOw7zHeKtSi4= 50 | modernc.org/cc/v3 v3.38.1/go.mod h1:vtL+3mdHx/wcj3iEGz84rQa8vEqR6XM84v5Lcvfph20= 51 | modernc.org/ccgo/v3 v3.16.9 h1:AXquSwg7GuMk11pIdw7fmO1Y/ybgazVkMhsZWCV0mHM= 52 | modernc.org/ccgo/v3 v3.16.9/go.mod h1:zNMzC9A9xeNUepy6KuZBbugn3c0Mc9TeiJO4lgvkJDo= 53 | modernc.org/ccorpus v1.11.6/go.mod h1:2gEUTrWqdpH2pXsmTM1ZkjeSrUWDpjMu2T6m29L/ErQ= 54 | modernc.org/httpfs v1.0.6/go.mod h1:7dosgurJGp0sPaRanU53W4xZYKh14wfzX420oZADeHM= 55 | modernc.org/libc v1.17.0/go.mod h1:XsgLldpP4aWlPlsjqKRdHPqCxCjISdHfM/yeWC5GyW0= 56 | modernc.org/libc v1.19.0 h1:bXyVhGQg6KIClTr8FMVIDPl7jtbcs7aS5WP7vLDaxPs= 57 | modernc.org/libc v1.19.0/go.mod h1:ZRfIaEkgrYgZDl6pa4W39HgN5G/yDW+NRmNKZBDFrk0= 58 | modernc.org/mathutil v1.2.2/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= 59 | modernc.org/mathutil v1.4.1/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= 60 | modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= 61 | modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= 62 | modernc.org/memory v1.2.0/go.mod h1:/0wo5ibyrQiaoUoH7f9D8dnglAmILJ5/cxZlRECf+Nw= 63 | modernc.org/memory v1.4.0 h1:crykUfNSnMAXaOJnnxcSzbUGMqkLWjklJKkBK2nwZwk= 64 | modernc.org/memory v1.4.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU= 65 | modernc.org/opt v0.1.1/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= 66 | modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= 67 | modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= 68 | modernc.org/sqlite v1.19.1 h1:8xmS5oLnZtAK//vnd4aTVj8VOeTAccEFOtUnIzfSw+4= 69 | modernc.org/sqlite v1.19.1/go.mod h1:UfQ83woKMaPW/ZBruK0T7YaFCrI+IE0LeWVY6pmnVms= 70 | modernc.org/strutil v1.1.1/go.mod h1:DE+MQQ/hjKBZS2zNInV5hhcipt5rLPWkmpbGeW5mmdw= 71 | modernc.org/strutil v1.1.3 h1:fNMm+oJklMGYfU9Ylcywl0CO5O6nTfaowNsh2wpPjzY= 72 | modernc.org/strutil v1.1.3/go.mod h1:MEHNA7PdEnEwLvspRMtWTNnp2nnyvMfkimT1NKNAGbw= 73 | modernc.org/token v1.0.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= 74 | modernc.org/token v1.0.1 h1:A3qvTqOwexpfZZeyI0FeGPDlSWX5pjZu9hF4lU+EKWg= 75 | modernc.org/token v1.0.1/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Go for Pomodoro 2 | 3 | Simple README for a simple bot application written in Go. 4 | 5 | Pomodoro Technique is a technique of studying or other concentration tasks 6 | where the time is allocated during a session in more sprints, and among each 7 | pair of sprints there is a break. E.g., 4 pomodoros (4 sprints), 25 minutes 8 | for each pomodoro (task time), 5 minutes of rest, 25 minutes of task time, etc. 9 | for 4 times. 10 | 11 | The application implements a Pomodoro timer flexible to different 12 | configurations that can be used by the users as a Telegram bot. 13 | 14 | ### Official Bot 15 | 16 | #### How to find and use 17 | 18 | You can find it on [this link](https://t.me/go4pom_bot). Type `/help` to learn how 19 | the bot is used. 20 | 21 | * `/30` will run a single Pomodoro of 30 minutes. 22 | 23 | * `/25` will run a single Pomodoro of 25 minutes. 24 | 25 | * `/25for4` will run a session of 4 Pomodoros of 25 minutes. The rest time by 26 | default is set to 5 minutes. 27 | 28 | To set a different rest time, the query is modified like 29 | 30 | * `/25for4rest7` (now the rest time among sprints will be of 7 minutes). 31 | 32 | By default, setting a configuration will trigger the timer to start. You can 33 | modify this behavior by typing 34 | 35 | `/autorun off` 36 | 37 | In that case, the Pomodoro is started doing `/start_sprint` or just `/s`. 38 | 39 | You can cancel a session with `/cancel` command (will make it unrestorable) 40 | or you can temporarily `/pause` it and `/resume` it in another moment. 41 | 42 | You can reset all the configuration associated with your chat with `/reset`. 43 | (This operation is irreversible.) 44 | 45 | #### Commands' groups 46 | 47 | This bot also works in groups. In groups, you have another pair of commands 48 | that are possible useful, and they are 49 | 50 | * `/join` 51 | * `/leave` 52 | 53 | After you `/join` the bot in a group, the bot will tag you by username each 54 | update of a session (session start, break, resume, finish, etc.), so that you 55 | get notifications in the group chat even if it was otherwise silenced. 56 | 57 | Vice versa, with `/leave` you signal that you wish not to be notified anymore 58 | for the updates. You may always join later. 59 | 60 | Remind that `/reset` also works in group and will also un-join all the chat 61 | members. 62 | 63 | ## Licensing 64 | 65 | GNU AGPL 3 (Affero General Public License), since this application is not a 66 | library, and the purpose of this project and alike believes that not only 67 | open-source is the most appropriate form to publish software, but also that 68 | the users deserve to have access to the code of the software they're using. 69 | 70 | The GNU GPL-3 has **not** be used in this project as it would not be very much 71 | meaningful for the purpose. The application is mainly server-side-like, and 72 | offers a service to the users. The GNU GPL-3 enforces the distribution of the 73 | code alongside the binary but not the distribution of the code in 74 | Software-as-a-Service model. 75 | 76 | Since this application offers a SaaS, and I want it open-source also in its 77 | re-distributions, the AGPL license is the fittest license. 78 | 79 | ## Development stack 80 | 81 | - Go (1.19, need Generics to work) 82 | - [go-telegram-bot-api](https://github.com/go-telegram-bot-api/telegram-bot-api) 83 | - SQLite ([driver](https://modernc.org/sqlite)) 84 | - not very much else 85 | 86 | ### Why SQLite? 87 | 88 | SQLite is a simple and very powerful DBMS, often under-estimated among 89 | developers. 90 | 91 | Free and open-source, easy to configure and use, very good performances and 92 | efficiency. 93 | 94 | I am aware that possibly it isn't the most efficient DB for an application 95 | like this. For this reason, although not exclusively, the DB side is very much 96 | abstracted in the program. The components that touch the DB (in `data` package) 97 | do not use SQL or SQLite directly; instead, they refer to an abstract 98 | key-value-store. Such key-value-store as of now has SQLite as backend, but 99 | it would be really easy to implement another backend (e.g., using Redis 100 | instead) under the same interface and providing it in the place of 101 | `persistence.Manager` interface (dependency injection pattern is used here not 102 | to force a particular DB onto the application). 103 | 104 | This software is Free and Open-Source and as such, you're free to implement 105 | your own a different DB underneath and eventually to make a pull request for 106 | its integration. Any contributions to this project would be appreciated. 107 | 108 | ### Why Go? 109 | 110 | A lot of Telegram bots are often written in either JS or Python. Go is no less 111 | safe than these languages, but allows for a very more robust concurrency model 112 | and better performance. Since a bot can have a lot of users at the same 113 | time, these advantages are well appreciated. At the same time, Go doesn't 114 | constitute an obstacle to what the project's purpose is, and I hope that 115 | readability is also a good side of this choice and the code itself. 116 | 117 | ## How to run the bot 118 | 119 | ### Getting a token 120 | The application needs a proper authentication with Telegram to work. It's 121 | assumed that who wants to run this bot has a valid Telegram account and at 122 | least a bot key available to use. 123 | 124 | If you have a Telegram account, you can create a bot using @BotFather, I 125 | recommend the [official guide](https://core.telegram.org/bots#6-botfather). 126 | 127 | ### Setting the token for the application 128 | 129 | Create a file named `appsettings.toml` in the directory the application will 130 | be run. (It can also be the project directory), and type inside 131 | 132 | ```toml 133 | ApiToken = "" 134 | 135 | DebugMode = false # optional parameter 136 | 137 | AdminIds = [] # optional parameter 138 | 139 | ListenAddressPrivate = "127.0.0.1" # optional parameter 140 | ListenPortPrivate = 8080 # optional parameter 141 | 142 | ``` 143 | 144 | * `ApiToken` should contain the token from Telegram/BotFather. 145 | **_Mandatory parameter_.** 146 | 147 | * `DebugMode` is a boolean attribute; when `true`, it logs more information of 148 | what is happening with the bot. _Optional parameter_. 149 | 150 | * `AdminIds` is an array of `int64`. Should contain the IDs of the admins of 151 | the bot. Allows for commands like `/shutdown` in chat to (gracefully) 152 | shutdown the bot. _Optional parameter_. 153 | 154 | * `ListenAddressPrivate` and `ListenPortPrivate` are attributes to set up 155 | the private server for the bot. With the example configuration, you would 156 | (gracefully) shutdown the bot with 157 | 158 | ```bash 159 | curl http://localhost:8080/shutdown 160 | ``` 161 | 162 | _Optional parameters_. 163 | 164 | ### Setting other variables 165 | 166 | Inside file `appvariables.toml`. Set for instance open source notice 167 | 168 | ```toml 169 | OpenSource1 = """Did you know that this bot is opensource? It is licensed \ 170 | under AGPL 3.0. The official source code for this bot is available at 171 | \n\n 172 | https://github.com/IThoughtUGNU/GoforPomodoro 173 | \n\n 174 | You can read what the license consists at 175 | \n\n 176 | https://www.gnu.org/licenses/#AGPL 177 | """ 178 | ``` 179 | 180 | These variables are not a secret and therefore can be put in the repository. 181 | If they should be put out of repository, use `appsettings.toml`. 182 | 183 | ### Testing that the configuration is OK 184 | 185 | You can test the configuration by running 186 | 187 | ```bash 188 | # Run from the project's folder 189 | go run cmd/GoforPomodoroCheck/main.go 190 | ``` 191 | 192 | An output that tells that all is ok will look like 193 | 194 | ``` 195 | Go for Pomodoro FOSS -- sanity check. 196 | -------------------------------------------------------------- 197 | (Go runtime version: go1.19.2) 198 | 199 | - [✅] appsettings.toml file 200 | 201 | - [✅] Database connected 202 | 203 | - [✅] Telegram API connection 204 | Authorized on account 205 | 206 | -------------------------------------------------------------- 207 | ``` 208 | 209 | The bot can work also without a connected database, but in that case you will 210 | obviously lose persistence of the data after application closing or PC 211 | shut-down. It is up to you to decide whether that's ok or not for your bot 212 | instance. 213 | 214 | Also, obviously, the bot **cannot** work without a valid API key or verified 215 | Telegram API connection. 216 | 217 | ### Running the application from source 218 | 219 | As in Go it is very simple to compile and run projects, you just need to 220 | perform this command. 221 | 222 | ```bash 223 | # Run from the project's folder 224 | go run cmd/GoforPomodoroBot/main.go 225 | ``` 226 | 227 | ### Building (and running) the application from source 228 | 229 | The same applies to a build that will leave you an executable file. 230 | 231 | ```bash 232 | # Run from the project's folder 233 | go build cmd/GoforPomodoroBot/main.go 234 | 235 | # To execute 236 | ./main 237 | ``` 238 | 239 | ### Building (and running) the application with Docker 240 | 241 | You can build and run the application in a container with Docker. You can build the container image directly with Docker CLI or you can use Docker Compose. 242 | 243 | Using Docker CLI: 244 | 245 | ```bash 246 | # Run all the following commands from the project's folder 247 | 248 | # Build container image 249 | docker build -t goforpomodoro . 250 | 251 | # Run container 252 | docker run -d --name goforopomodorobot -v :/app/data/go4pom_data.db -v :/app/appsettings.toml goforpomodoro 253 | ``` 254 | 255 | Using Docker Compose: 256 | 257 | ```bash 258 | # Run the following command from the project's folder 259 | 260 | 261 | # Build and run container 262 | BOT_DATA_DIR= docker-compose up -d 263 | ``` 264 | -------------------------------------------------------------------------------- /internal/botmodule/CommandMenu.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package botmodule 17 | 18 | import ( 19 | "GoforPomodoro/internal/data" 20 | "GoforPomodoro/internal/domain" 21 | "GoforPomodoro/internal/inputprocess" 22 | "GoforPomodoro/internal/sessionmanager" 23 | "GoforPomodoro/internal/utils" 24 | "fmt" 25 | tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" 26 | "io" 27 | "log" 28 | "net/http" 29 | "os" 30 | "strings" 31 | ) 32 | 33 | /* 34 | var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup( 35 | tgbotapi.NewInlineKeyboardRow( 36 | tgbotapi.NewInlineKeyboardButtonURL("1.com", "http://1.com"), 37 | tgbotapi.NewInlineKeyboardButtonData("2", "2"), 38 | tgbotapi.NewInlineKeyboardButtonData("3", "3"), 39 | ), 40 | tgbotapi.NewInlineKeyboardRow( 41 | tgbotapi.NewInlineKeyboardButtonData("4", "4"), 42 | tgbotapi.NewInlineKeyboardButtonData("5", "5"), 43 | tgbotapi.NewInlineKeyboardButtonData("6", "6"), 44 | ), 45 | )*/ 46 | 47 | func ListenPrivateHTTP(appState *domain.AppState, address string, port int) { 48 | http.HandleFunc("/hello", getHello) 49 | http.HandleFunc("/shutdown", func(w http.ResponseWriter, r *http.Request) { 50 | // dispatchServerAction <- domain.DispatchServerAction{Shutdown: true} 51 | log.Println("[ListenPrivateHTTP] Shutdown request from HTTP.") 52 | data.PrepareForShutdown( 53 | appState, 54 | func() { 55 | log.Println("[ListenPrivateHTTP] DB lock acquired.") 56 | _, _ = io.WriteString(w, "shutting down\n") 57 | go os.Exit(0) 58 | }, 59 | ) 60 | }) 61 | 62 | err := http.ListenAndServe(fmt.Sprintf("%s:%d", address, port), nil) 63 | if err != nil { 64 | log.Fatal(err) 65 | } 66 | } 67 | 68 | func getHello(w http.ResponseWriter, r *http.Request) { 69 | _ = r 70 | fmt.Printf("got /hello request\n") 71 | _, err := io.WriteString(w, "Hello, HTTP!\n") 72 | if err != nil { 73 | log.Println("getHello err:", err) 74 | } 75 | } 76 | 77 | func CommandMenuLoop( 78 | settings *domain.AppSettings, 79 | appVariables *domain.AppVariables, 80 | appState *domain.AppState, 81 | ) { 82 | bot, err := tgbotapi.NewBotAPI(settings.ApiToken) 83 | if err != nil { 84 | log.Panic(err) 85 | } 86 | 87 | settings.BotName = bot.Self.UserName 88 | 89 | debugMode := settings.DebugMode 90 | bot.Debug = debugMode 91 | 92 | log.Printf("Authorized on account %s", bot.Self.UserName) 93 | 94 | u := tgbotapi.NewUpdate(0) 95 | u.Timeout = 60 96 | 97 | RestoreSessions(appState, appVariables, bot) 98 | 99 | PrivacyPolicyEnabled := appVariables.PrivacyPolicyEnabled 100 | privacyVersion := appVariables.PrivacySettingsVersion 101 | 102 | updates := bot.GetUpdatesChan(u) 103 | 104 | mainLoop: 105 | for update := range updates { 106 | if update.Message != nil { // If we got a message 107 | senderId := domain.ChatID(update.Message.From.ID) 108 | chatId := domain.ChatID(update.Message.Chat.ID) 109 | 110 | newChat := data.IsThisNewUser(appState, chatId) 111 | 112 | if debugMode { 113 | log.Printf("[%s] %s\n", update.Message.From.UserName, update.Message.Text) 114 | log.Printf("New chat? | %v\n", utils.YesNo(newChat)) 115 | } 116 | 117 | msgText := update.Message.Text 118 | 119 | // var replyMsg tgbotapi.MessageConfig 120 | // var replyMsgText string 121 | 122 | command := inputprocess.CommandFrom(settings, msgText) 123 | parameters := inputprocess.ParametersFrom(msgText) 124 | 125 | if debugMode { 126 | log.Printf("command: %s\n", command) 127 | } 128 | 129 | isGroup := update.Message.Chat.IsGroup() || update.Message.Chat.IsSuperGroup() 130 | data.AdjustChatType(appState, chatId, senderId, isGroup) 131 | 132 | communicator := GetCommunicator(appState, appVariables, chatId, bot) 133 | 134 | if PrivacyPolicyEnabled { 135 | // Check privacy policy agreement 136 | userPrivacy, userPrivacyVersion := data.GetUserPrivacyPolicy(appState, chatId) 137 | if userPrivacy.IsZero() || privacyVersion > userPrivacyVersion { 138 | // The user has no privacy policy set (or it is too old). 139 | 140 | // If the user is changing privacy now, we manage the change. 141 | if inputprocess.IsPrivacySettingsCommand(command) { 142 | switch command { 143 | case "/accept_essential": 144 | data.SetUserPrivacyPolicy(appState, chatId, domain.AcceptedEssential, privacyVersion) 145 | case "/accept_all": 146 | data.SetUserPrivacyPolicy(appState, chatId, domain.AcceptedAll, privacyVersion) 147 | } 148 | communicator.PrivacySettingsUpdated() 149 | 150 | data.DefaultUserSettingsIfNeeded(appState, chatId) 151 | } else { 152 | // Otherwise, must show privacy policy 153 | communicator.ShowPrivacyPolicy() 154 | communicator.ShowLicenseNotice() 155 | } 156 | continue 157 | } 158 | } else { 159 | if newChat { 160 | communicator.Info() 161 | communicator.Help() 162 | data.DefaultUserSettingsIfNeeded(appState, chatId) 163 | } 164 | } 165 | 166 | switch command { 167 | // Admin commands 168 | case "/shutdown": 169 | isAdmin := utils.Contains(settings.AdminIds, senderId) 170 | if isAdmin { 171 | communicator.ReplyWith("Soft shutting down...") 172 | data.PrepareForShutdown( 173 | appState, 174 | func() { 175 | communicator.ReplyWith("DB lock acquired.") 176 | os.Exit(0) 177 | }, 178 | ) 179 | break mainLoop 180 | } 181 | // Group commands 182 | case "/join": 183 | if !isGroup { 184 | communicator.ReplyWith("This command works only in groups, sorry.") 185 | continue 186 | } 187 | senderChat, err := bot.GetChat(tgbotapi.ChatInfoConfig{ChatConfig: tgbotapi.ChatConfig{ChatID: int64(senderId)}}) 188 | if err != nil { 189 | communicator.ReplyWith("Error with your account.") 190 | continue 191 | } 192 | 193 | communicator.Subscribe( 194 | data.SubscribeUserInGroup(appState, chatId, senderId), 195 | update, 196 | senderChat.UserName, 197 | ) 198 | case "/leave": 199 | if !isGroup { 200 | communicator.OnlyGroupsCommand() 201 | continue 202 | } 203 | 204 | communicator.Unsubscribe(data.UnsubscribeUser(appState, chatId, senderId)) 205 | // Personal commands 206 | case "/autorun": 207 | if len(parameters) > 0 { 208 | param := parameters[0] 209 | var autorun bool 210 | if param == "on" { 211 | autorun = true 212 | } else if param == "off" { 213 | autorun = false 214 | } else { 215 | communicator.CommandError() 216 | continue 217 | } 218 | data.SetUserAutorun(appState, chatId, senderId, autorun) 219 | communicator.ReplyWith("Autorun set " + strings.ToUpper(param) + ".") 220 | } else { 221 | data.SetUserAutorun(appState, chatId, senderId, true) 222 | communicator.ReplyWith("Autorun set ON.") 223 | } 224 | case "/se", "/session": 225 | session := data.GetUserSessionRunning(appState, chatId, senderId) 226 | communicator.SessionState(*session) 227 | case "/p", "/pause": 228 | session := data.GetUserSessionRunning(appState, chatId, senderId) 229 | err := sessionmanager.PauseSession(session) 230 | communicator.SessionPaused(err, *session) 231 | case "/c", "/cancel": 232 | ActionCancelSprint(senderId, chatId, appState, communicator) 233 | case "/resume": 234 | ActionResumeSprint(senderId, chatId, appState, communicator) 235 | case "/d", "/default": 236 | data.UpdateDefaultUserSession(appState, chatId, senderId, domain.DefaultSession()) 237 | ActionStartSprint(senderId, chatId, appState, communicator) 238 | case "/s", "/start_sprint": 239 | ActionStartSprint(senderId, chatId, appState, communicator) 240 | case "/reset": 241 | data.CleanUserSettings(appState, chatId, senderId) 242 | communicator.DataCleaned() 243 | case "/help": 244 | communicator.Help() 245 | case "/info": 246 | communicator.Info() 247 | case "/clessidra": 248 | communicator.Hourglass() 249 | default: 250 | sessionDataOpt := inputprocess.ParsePatternToSession(nil, msgText) 251 | sessionData, err := sessionDataOpt.GetValue() 252 | if err != nil { 253 | // Session wasn't parsed 254 | continue 255 | } 256 | _, err = inputprocess.ValidateSessionParsed(sessionData) 257 | if err == nil { 258 | data.UpdateDefaultUserSession(appState, chatId, senderId, sessionData) 259 | communicator.NewSession(sessionData) 260 | autorun := data.GetUserAutorun(appState, chatId, senderId) 261 | if autorun { 262 | ActionStartSprint(senderId, chatId, appState, communicator) 263 | } 264 | } else { 265 | communicator.ErrorSessionTooLong() 266 | } 267 | } 268 | } else if update.CallbackQuery != nil { 269 | // Respond to the callback query, telling Telegram to show the user 270 | // a message with the data received. 271 | 272 | switch update.CallbackQuery.Data { 273 | case "⌛": 274 | chatId := domain.ChatID(update.CallbackQuery.Message.Chat.ID) 275 | senderId := domain.ChatID(update.CallbackQuery.Message.From.ID) 276 | 277 | session := data.GetUserSessionRunning(appState, chatId, senderId) 278 | 279 | // We reply with a toast (callback) 280 | toastText := session.LeftTimeMessage() 281 | callback := tgbotapi.NewCallback(update.CallbackQuery.ID, toastText) 282 | if _, err := bot.Request(callback); err != nil { 283 | log.Println("[ERROR] " + err.Error()) 284 | } 285 | 286 | // To reply with a message 287 | // sg := tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, update.CallbackQuery.Data) 288 | // if _, err := bot.Send(msg); err != nil { 289 | // // manage error 290 | // } 291 | 292 | } 293 | } 294 | } 295 | } 296 | -------------------------------------------------------------------------------- /internal/botmodule/Communicator.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package botmodule 17 | 18 | import ( 19 | "GoforPomodoro/internal/data" 20 | "GoforPomodoro/internal/domain" 21 | "GoforPomodoro/internal/sessionmanager" 22 | "GoforPomodoro/internal/utils" 23 | "fmt" 24 | tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" 25 | "log" 26 | "math/rand" 27 | "strings" 28 | "time" 29 | ) 30 | 31 | var simpleHourglassKeyboard = tgbotapi.NewInlineKeyboardMarkup( 32 | tgbotapi.NewInlineKeyboardRow( 33 | tgbotapi.NewInlineKeyboardButtonData("⌛", "⌛"), 34 | ), 35 | ) 36 | 37 | type Communicator struct { 38 | appState *domain.AppState 39 | appVariables *domain.AppVariables 40 | ChatID domain.ChatID 41 | Bot *tgbotapi.BotAPI 42 | Subscribers []domain.ChatID 43 | IsGroup bool 44 | } 45 | 46 | func GetCommunicator(appState *domain.AppState, appVariables *domain.AppVariables, chatId domain.ChatID, bot *tgbotapi.BotAPI) *Communicator { 47 | communicator := new(Communicator) 48 | 49 | communicator.appState = appState 50 | communicator.appVariables = appVariables 51 | communicator.ChatID = chatId 52 | communicator.Bot = bot 53 | communicator.Subscribers = data.GetSubscribers(appState, chatId) 54 | communicator.IsGroup = data.IsGroup(appState, chatId) 55 | 56 | return communicator 57 | } 58 | 59 | func (c *Communicator) subscribersAsString() string { 60 | bot := c.Bot 61 | 62 | var sb strings.Builder 63 | 64 | errors := 0 65 | for _, id := range c.Subscribers { 66 | subscriberChat, err := bot.GetChat(tgbotapi.ChatInfoConfig{ChatConfig: tgbotapi.ChatConfig{ChatID: int64(id)}}) 67 | if err != nil { 68 | errors += 1 69 | continue 70 | } 71 | sb.WriteString("@") 72 | sb.WriteString(subscriberChat.UserName) 73 | sb.WriteString(" ") 74 | } 75 | 76 | return sb.String() 77 | } 78 | 79 | func (c *Communicator) toNotify(message string) string { 80 | // Update subscribers in case they changed 81 | c.Subscribers = data.GetSubscribers(c.appState, c.ChatID) 82 | 83 | if !c.IsGroup || len(c.Subscribers) == 0 { 84 | // This function is identity function if we're not in a group or there are no subscribers. 85 | return message 86 | } 87 | 88 | return message + "\n\n———\n" + c.subscribersAsString() 89 | } 90 | 91 | func (c *Communicator) Subscribe(err error, update tgbotapi.Update, username string) { 92 | if err != nil { 93 | switch err.Error() { 94 | case domain.AlreadySubscribed{}.Error(): 95 | c.ReplyWith("You already subscribed this chat group.\n\n" + 96 | "Remember you can use /leave to cancel subscription.") 97 | case domain.SubscriptionError{}.Error(): 98 | c.ReplyWith("There has been an error with this operation (subscription).") 99 | } 100 | } else { 101 | c.ReplyWith(fmt.Sprintf("Done! You will be tagged (@%s) in sprints' messages.", username)) 102 | } 103 | } 104 | 105 | func (c *Communicator) Unsubscribe(err error) { 106 | if err != nil { 107 | switch err.Error() { 108 | case domain.AlreadyUnsubscribed{}.Error(): 109 | c.ReplyWith("You are (were) not subscribed in this chat group.") 110 | case domain.SubscriptionError{}.Error(): 111 | c.ReplyWith("There has been an error with this operation (subscription).") 112 | } 113 | } else { 114 | c.ReplyWith("Done! You no longer subscribe in this chat group thus will not be tagged in future messages.") 115 | } 116 | } 117 | 118 | func (c *Communicator) ReplyWith(text string) { 119 | bot := c.Bot 120 | chatId := int64(c.ChatID) 121 | 122 | msg := tgbotapi.NewMessage(chatId, text) 123 | _, err := bot.Send(msg) 124 | if err != nil { 125 | log.Printf("ERROR: %s", err.Error()) 126 | } 127 | } 128 | 129 | func (c *Communicator) ReplyWithParseMode(text string, parseMode string, disablePreview bool) { 130 | bot := c.Bot 131 | chatId := int64(c.ChatID) 132 | 133 | msg := tgbotapi.NewMessage(chatId, text) 134 | msg.ParseMode = parseMode 135 | msg.DisableWebPagePreview = disablePreview 136 | _, err := bot.Send(msg) 137 | if err != nil { 138 | log.Printf("ERROR: %s", err.Error()) 139 | } 140 | } 141 | 142 | func (c *Communicator) ReplyAndNotify(text string) { 143 | c.ReplyWith(c.toNotify(text)) 144 | } 145 | 146 | func (c *Communicator) ReplyWithAndHourglass(text string) { 147 | msg := tgbotapi.NewMessage(int64(c.ChatID), text) 148 | msg.ReplyMarkup = simpleHourglassKeyboard 149 | _, err := c.Bot.Send(msg) 150 | if err != nil { 151 | log.Printf("ERROR: %s", err.Error()) 152 | } 153 | } 154 | 155 | func (c *Communicator) ReplyWithAndHourglassAndNotify(text string) { 156 | c.ReplyWithAndHourglass(c.toNotify(text)) 157 | } 158 | 159 | func (c *Communicator) SessionStarted(session *domain.Session, err error) { 160 | if err == nil { 161 | sessionTime := session.CalculateSessionTimeInSeconds() 162 | var replyStr string 163 | 164 | if session.IsSprintDurationUnspecified() { 165 | replyStr = "This session will go as long as you want to keep focusing." 166 | } else { 167 | replyStr = fmt.Sprintf("This session will last for %s\n\nSession started!", utils.NiceTimeFormatting64(sessionTime)) 168 | } 169 | c.ReplyWithAndHourglassAndNotify(replyStr) 170 | } else { 171 | c.ReplyWith("Session was not set.\nPlease set a session or use /default for classic 4x25m+25m.") 172 | } 173 | } 174 | 175 | /* 176 | func (c *Communicator) SessionFinished() { 177 | 178 | } 179 | 180 | func (c *Communicator) SessionResumed() { 181 | 182 | } 183 | 184 | func (c *Communicator) SessionPaused() { 185 | 186 | }*/ 187 | 188 | func (c *Communicator) SessionFinishedHandler(id domain.ChatID, session *domain.Session, endKind sessionmanager.PomodoroEndKind) { 189 | switch endKind { 190 | case sessionmanager.PomodoroFinished: 191 | c.ReplyAndNotify("Pomodoro done! The session is complete, congratulations!") 192 | case sessionmanager.PomodoroCanceled: 193 | c.ReplyAndNotify("Session canceled.") 194 | } 195 | } 196 | 197 | func (c *Communicator) SessionPausedHandler(id domain.ChatID, session *domain.Session) { 198 | c.ReplyAndNotify("Your session has paused.") 199 | } 200 | 201 | func (c *Communicator) RestFinishedHandler(id domain.ChatID, session *domain.Session) { 202 | text := fmt.Sprintf( 203 | "Pomodoro %s started.", 204 | utils.NiceTimeFormatting(session.GetPomodoroDurationSet().Seconds()), 205 | ) 206 | c.ReplyWithAndHourglassAndNotify(text) 207 | } 208 | 209 | func (c *Communicator) RestBeginHandler(id domain.ChatID, session *domain.Session) { 210 | text := fmt.Sprintf( 211 | "Pomodoro done! Have rest for %s now.", 212 | utils.NiceTimeFormatting(session.GetRestDurationSet().Seconds()), 213 | ) 214 | 215 | c.ReplyAndNotify(text) 216 | } 217 | 218 | func (c *Communicator) SessionAlreadyRunning() { 219 | c.ReplyWith("A session already running.") 220 | } 221 | 222 | func (c *Communicator) SessionResumed(err error, session *domain.Session) { 223 | if err != nil { 224 | if session.IsZero() { 225 | c.ReplyWith("Session was not set.") 226 | } else if session.IsCanceled() { 227 | c.ReplyWith("Last session was canceled.") 228 | } else if !session.IsStopped() { 229 | c.ReplyWith("Session is already running.") 230 | } else { 231 | c.ReplyWith("Server error.") 232 | } 233 | return 234 | } 235 | 236 | c.ReplyWithAndHourglassAndNotify("Session resumed!") 237 | } 238 | 239 | func (c *Communicator) OnlyGroupsCommand() { 240 | c.ReplyWith("This command works only in groups, sorry.") 241 | } 242 | 243 | func (c *Communicator) NewSession(session domain.SessionDefaultData) { 244 | c.ReplyWith(fmt.Sprintf("New session!\n\n%s", session.String())) 245 | } 246 | 247 | func (c *Communicator) Info() { 248 | c.ReplyWith("I am a pomodoro bot written in Go!") 249 | c.ShowLicenseNotice() 250 | } 251 | 252 | func (c *Communicator) DataCleaned() { 253 | c.ReplyWith("Your data has been cleaned.") 254 | } 255 | 256 | func (c *Communicator) Help() { 257 | c.ReplyWith("Set a session (examples)\n/25for4rest5 --> 4 🍅, 25 minutes + 5m for rest.\n" + 258 | "The latter is also achieved with /default.\n" + 259 | "/30for4 --> 4 🍅, 30 minutes (default: +5m for rest).\n" + 260 | "/25 --> 1 🍅, 25 minutes (single pomodoro sprint)\n" + 261 | "/30forXrest7 --> unspecified no. of 🍅s, 30 minutes + 7m for rest.\n\n" + 262 | "Other commands:\n" + 263 | "(/s) /start_sprint to start (if /autorun is set off)\n" + 264 | "(/p) /pause to pause a session in run\n" + 265 | "(/c) /cancel to cancel a session\n" + 266 | "/resume to resume a paused session.\n" + 267 | "(/se) /session to check your session settings and status.\n" + 268 | "/reset to reset your profile/chat settings.\n" + 269 | "/info to have some info on this bot.") 270 | } 271 | 272 | func (c *Communicator) SessionPaused(err error, session domain.Session) { 273 | if err != nil { 274 | if !session.IsStopped() { 275 | c.ReplyWith("Session was not running.") 276 | } else { 277 | c.ReplyWith("Server error.") 278 | } 279 | } 280 | } 281 | 282 | func (c *Communicator) SessionCanceled(err error, session domain.Session) { 283 | if err != nil { 284 | if session.IsStopped() { 285 | c.ReplyWith("Session was not running.") 286 | } else { 287 | c.ReplyWith("Server error.") 288 | } 289 | } 290 | } 291 | 292 | func (c *Communicator) SessionState(session domain.Session) { 293 | var stateStr = session.State() 294 | 295 | var replyMsgText string 296 | if session.IsCanceled() { 297 | replyMsgText = fmt.Sprintf("Your session state: %s.", stateStr) 298 | } else { 299 | replyMsgText = session.String() 300 | } 301 | c.ReplyWith(replyMsgText) 302 | } 303 | 304 | func (c *Communicator) CommandError() { 305 | c.ReplyWith("Command error.") 306 | } 307 | 308 | func (c *Communicator) Hourglass() { 309 | c.ReplyWithAndHourglass("Here is an hourglass") 310 | } 311 | 312 | func (c *Communicator) ShowPrivacyPolicy() { 313 | c.ReplyWithParseMode(c.appVariables.PrivacyPolicy1, "html", true) 314 | } 315 | 316 | func (c *Communicator) PrivacySettingsUpdated() { 317 | c.ReplyWith("Your privacy settings have been updated!") 318 | } 319 | 320 | func (c *Communicator) ShowLicenseNotice() { 321 | c.ReplyWithParseMode(c.appVariables.OpenSource1, "html", true) 322 | } 323 | 324 | func (c *Communicator) ErrorSessionTooLong() { 325 | tooLongMessages := [...]string{ 326 | "I don't have time for this, sorry.", 327 | "That's too much time for a session that I can manage.", 328 | "Bammer. Loooong session.", 329 | "The session you specified lasts too long.", 330 | } 331 | rand.Seed(time.Now().UnixNano()) 332 | c.ReplyWith(tooLongMessages[rand.Intn(len(tooLongMessages))]) 333 | } 334 | -------------------------------------------------------------------------------- /internal/data/DataModel.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package data 17 | 18 | import ( 19 | "GoforPomodoro/internal/data/persistence" 20 | "GoforPomodoro/internal/domain" 21 | "GoforPomodoro/internal/utils" 22 | "github.com/BurntSushi/toml" 23 | "log" 24 | ) 25 | 26 | func PreloadUsersSettings( 27 | appState *domain.AppState, 28 | pairs []utils.Pair[domain.ChatID, *domain.Settings], 29 | ) { 30 | appState.UsersSettingsLock.Lock() 31 | defer appState.UsersSettingsLock.Unlock() 32 | 33 | for _, pair := range pairs { 34 | chatId := pair.First 35 | settings := pair.Second 36 | 37 | appState.UsersSettings[chatId] = settings 38 | } 39 | } 40 | 41 | func LoadAppSettings() (*domain.AppSettings, error) { 42 | settings := new(domain.AppSettings) 43 | _, err := toml.DecodeFile("appsettings.toml", settings) 44 | 45 | return settings, err 46 | } 47 | 48 | func LoadAppVariables() (*domain.AppVariables, error) { 49 | appVariables := new(domain.AppVariables) 50 | _, err := toml.DecodeFile("appvariables.toml", appVariables) 51 | 52 | return appVariables, err 53 | } 54 | 55 | func LoadAppState(persistenceManager persistence.Manager, debugMode bool) (*domain.AppState, error) { 56 | appState := new(domain.AppState) 57 | 58 | appState.DebugMode = debugMode 59 | 60 | appState.PersistenceManager = persistenceManager 61 | 62 | appState.UsersSettingsLock.Lock() 63 | appState.UsersSettings = make(map[domain.ChatID]*domain.Settings) 64 | appState.UsersSettingsLock.Unlock() 65 | 66 | return appState, nil 67 | } 68 | 69 | func DefaultUserSettingsIfNeeded(appState *domain.AppState, chatId domain.ChatID) { 70 | defaultUserSettingsIfNeeded(appState, chatId) 71 | } 72 | 73 | func defaultUserSettingsIfNeeded(appState *domain.AppState, chatId domain.ChatID) { 74 | if appState.ReadSettings(chatId) == nil { 75 | // Check if there is in the database, otherwise we create new settings in-place 76 | if appState.PersistenceManager == nil { 77 | chatSettings := new(domain.Settings) 78 | chatSettings.Autorun = true 79 | appState.WriteSettings(chatId, chatSettings) 80 | } else { 81 | chatSettings, err := appState.PersistenceManager.GetChatSettings(chatId) 82 | 83 | if err != nil { 84 | chatSettings = new(domain.Settings) 85 | chatSettings.Autorun = true 86 | appState.WriteSettings(chatId, chatSettings) 87 | } else { // err == nil 88 | appState.WriteSettings(chatId, chatSettings) 89 | } 90 | 91 | storeErr := appState.PersistenceManager.StoreChatSettings(chatId, chatSettings) 92 | 93 | if storeErr != nil { 94 | log.Printf("[defaultUserSettingsIfNeeded] Storing ERROR: %v\n", storeErr.Error()) 95 | } 96 | } 97 | } 98 | } 99 | 100 | func SetUserPrivacyPolicy( 101 | appState *domain.AppState, 102 | chatId domain.ChatID, 103 | privacyPolicy domain.PrivacySettingsType, 104 | privacyVersion domain.PrivacySettingsVersion, 105 | ) { 106 | defaultUserSettingsIfNeeded(appState, chatId) 107 | 108 | settings := appState.ReadSettings(chatId) 109 | 110 | settings.PrivacySettings = settings.PrivacySettings | privacyPolicy 111 | settings.PrivacySettingsVersion = privacyVersion 112 | } 113 | 114 | func GetUserPrivacyPolicy( 115 | appState *domain.AppState, 116 | chatId domain.ChatID, 117 | ) (domain.PrivacySettingsType, 118 | domain.PrivacySettingsVersion, 119 | ) { 120 | defaultUserSettingsIfNeeded(appState, chatId) 121 | 122 | settings := appState.ReadSettings(chatId) 123 | 124 | return settings.PrivacySettings, settings.PrivacySettingsVersion 125 | } 126 | 127 | func IsThisNewUser(appState *domain.AppState, chatId domain.ChatID) bool { 128 | if appState.ReadSettings(chatId) == nil { 129 | // Check if there is in the database, otherwise we create new settings in-place 130 | if appState.PersistenceManager == nil { 131 | return true 132 | } else { 133 | _, err := appState.PersistenceManager.GetChatSettings(chatId) 134 | 135 | // log.Println("Settings:", settings) 136 | // log.Println("Err:", err) 137 | if err != nil { 138 | return true 139 | } else { // err == nil 140 | return false 141 | } 142 | } 143 | } 144 | return false 145 | } 146 | 147 | func AdjustChatType(appState *domain.AppState, chatId domain.ChatID, senderId domain.ChatID, isGroup bool) { 148 | defaultUserSettingsIfNeeded(appState, chatId) 149 | 150 | appState.ReadSettings(chatId).IsGroup = isGroup 151 | } 152 | 153 | func IsGroup(appState *domain.AppState, chatId domain.ChatID) bool { 154 | defaultUserSettingsIfNeeded(appState, chatId) 155 | 156 | return appState.ReadSettings(chatId).IsGroup 157 | } 158 | 159 | func GetSubscribers(appState *domain.AppState, chatId domain.ChatID) []domain.ChatID { 160 | defaultUserSettingsIfNeeded(appState, chatId) 161 | 162 | return appState.ReadSettings(chatId).Subscribers 163 | } 164 | 165 | func SubscribeUserInGroup(appState *domain.AppState, chatId domain.ChatID, senderId domain.ChatID) error { 166 | defaultUserSettingsIfNeeded(appState, chatId) 167 | 168 | if chatId == senderId { 169 | return domain.SubscriptionError{} 170 | } 171 | 172 | settings := appState.ReadSettings(chatId) 173 | 174 | subscribers := (*settings).Subscribers 175 | if !utils.Contains(subscribers, senderId) { 176 | (*settings).Subscribers = append(subscribers, senderId) 177 | } else { 178 | return domain.AlreadySubscribed{} 179 | } 180 | return nil 181 | } 182 | 183 | func UnsubscribeUser(appState *domain.AppState, chatId domain.ChatID, senderId domain.ChatID) error { 184 | defaultUserSettingsIfNeeded(appState, chatId) 185 | 186 | if chatId == senderId { 187 | return domain.SubscriptionError{} 188 | } 189 | 190 | settings := appState.ReadSettings(chatId) 191 | 192 | subscribers := (*settings).Subscribers 193 | if utils.Contains(subscribers, senderId) { 194 | newS, err := utils.AfterRemoveEl(subscribers, senderId) 195 | if err != nil { 196 | if appState.DebugMode { 197 | log.Printf("[UnsubscribeUser] Error while removing %d\n", senderId) 198 | } 199 | return domain.OperationError{} 200 | } 201 | (*settings).Subscribers = newS 202 | } else { 203 | if appState.DebugMode { 204 | log.Printf("[UnsubscribeUser] %d was not subscribed.", senderId) 205 | } 206 | return domain.AlreadyUnsubscribed{} 207 | } 208 | return nil 209 | } 210 | 211 | func CleanUserSettings(appState *domain.AppState, chatId domain.ChatID, senderId domain.ChatID) { 212 | appState.WriteSettings(chatId, nil) 213 | 214 | if appState.PersistenceManager != nil { 215 | err := appState.PersistenceManager.DeleteChatSettings(chatId) 216 | if err != nil { 217 | log.Printf("[DataModel::CleanUserSettings] error in deleting. (%v)\n", err.Error()) 218 | } 219 | } 220 | // defaultUserSettingsIfNeeded(appState, chatId) 221 | } 222 | 223 | func SetUserAutorun(appState *domain.AppState, chatId domain.ChatID, senderId domain.ChatID, autorun bool) { 224 | defaultUserSettingsIfNeeded(appState, chatId) 225 | 226 | chatSettings := appState.ReadSettings(chatId) 227 | 228 | chatSettings.Autorun = autorun 229 | 230 | if appState.PersistenceManager != nil { 231 | err := appState.PersistenceManager.StoreChatSettings(chatId, chatSettings) 232 | if err != nil { 233 | log.Printf("[DataModel::SetUserAutorun] error in storing. (%v)\n", err.Error()) 234 | } 235 | } 236 | } 237 | 238 | func GetUserAutorun(appState *domain.AppState, chatId domain.ChatID, senderId domain.ChatID) bool { 239 | defaultUserSettingsIfNeeded(appState, chatId) 240 | 241 | return appState.ReadSettings(chatId).Autorun 242 | } 243 | 244 | func UpdateUserSessionRunning(appState *domain.AppState, chatId domain.ChatID) { 245 | 246 | settings := appState.ReadSettings(chatId) 247 | 248 | // TODO: Dispatch this call to a goroutine using a channel instead of spawning a go-func 249 | go func() { 250 | if appState.PersistenceManager != nil { 251 | err := appState.PersistenceManager.StoreChatSettings(chatId, settings) 252 | if err != nil { 253 | log.Printf("[DataModel::UpdateUserSessionRunning] error in storing. (%v)\n", err.Error()) 254 | } 255 | } 256 | }() 257 | } 258 | 259 | func UpdateDefaultUserSession(appState *domain.AppState, chatId domain.ChatID, senderId domain.ChatID, sdd domain.SessionDefaultData) { 260 | defaultUserSettingsIfNeeded(appState, chatId) 261 | 262 | settings := appState.ReadSettings(chatId) 263 | 264 | settings.SessionDefault = sdd 265 | 266 | if appState.PersistenceManager != nil { 267 | err := appState.PersistenceManager.StoreChatSettings(chatId, settings) 268 | if err != nil { 269 | log.Printf("[DataModel::UpdateDefaultUserSession] error in storing. (%v)\n", err.Error()) 270 | } 271 | } 272 | } 273 | 274 | func GetUserSessionFromSettings(appState *domain.AppState, chatId domain.ChatID, senderId domain.ChatID) domain.SessionInitData { 275 | defaultUserSettingsIfNeeded(appState, chatId) 276 | 277 | session := &appState.ReadSettings(chatId).SessionDefault 278 | 279 | sData := session.ToInitData() 280 | sData.IsPaused = true 281 | 282 | return sData // this instantiates a new session object 283 | } 284 | 285 | func GetNewUserSessionRunning(appState *domain.AppState, chatId domain.ChatID, senderId domain.ChatID) *domain.Session { 286 | defaultUserSettingsIfNeeded(appState, chatId) 287 | 288 | sessionDef := GetUserSessionFromSettings(appState, chatId, senderId) 289 | 290 | sessionDef.PomodoroDuration = sessionDef.PomodoroDurationSet 291 | sessionDef.SprintDuration = sessionDef.SprintDurationSet 292 | sessionDef.RestDuration = sessionDef.RestDurationSet 293 | sessionDef.IsPaused = true 294 | 295 | sessionRunning := sessionDef.ToSession().InitChannel() 296 | 297 | settings := appState.ReadSettings(chatId) 298 | 299 | settings.SessionRunning = sessionRunning 300 | 301 | return sessionRunning 302 | } 303 | 304 | func GetUserSessionRunning(appState *domain.AppState, chatId domain.ChatID, senderId domain.ChatID) *domain.Session { 305 | defaultUserSettingsIfNeeded(appState, chatId) 306 | 307 | sessionRunning := appState.ReadSettings(chatId).SessionRunning 308 | 309 | // var sessionRunning *domain.Session 310 | 311 | if sessionRunning == nil { 312 | sessionDef := GetUserSessionFromSettings(appState, chatId, senderId) 313 | 314 | sessionDef.PomodoroDuration = sessionDef.PomodoroDurationSet 315 | sessionDef.SprintDuration = sessionDef.SprintDurationSet 316 | sessionDef.RestDuration = sessionDef.RestDurationSet 317 | 318 | sessionDef.IsPaused = true 319 | 320 | sessionRunning = sessionDef.ToSession().InitChannel() 321 | 322 | appState.ReadSettings(chatId).SessionRunning = sessionRunning 323 | 324 | /* 325 | appState.UsersSettings[chatId].SessionRunning = new(domain.Session).InitChannel() 326 | 327 | sessionRunning = appState.UsersSettings[chatId].SessionRunning 328 | 329 | sessionRunning.pomodoroDurationSet = sessionDef.pomodoroDurationSet 330 | sessionRunning.sprintDurationSet = sessionDef.sprintDurationSet 331 | sessionRunning.restDurationSet = sessionDef.restDurationSet 332 | 333 | sessionRunning.Data.PomodoroDuration = sessionDef.pomodoroDurationSet 334 | sessionRunning.Data.SprintDuration = sessionDef.sprintDurationSet 335 | sessionRunning.Data.RestDuration = sessionDef.restDurationSet 336 | 337 | sessionRunning.Data.IsPaused = true*/ 338 | } else { 339 | sessionRunning = appState.ReadSettings(chatId).SessionRunning 340 | 341 | if sessionRunning.ActionsChannel == nil { 342 | sessionRunning = sessionRunning.InitChannel() 343 | } 344 | } 345 | return sessionRunning 346 | } 347 | 348 | func PrepareForShutdown(appState *domain.AppState, callback func()) { 349 | if appState.PersistenceManager != nil { 350 | // We wait for all DB operations to complete 351 | appState.PersistenceManager.LockDB() 352 | } 353 | callback() 354 | } 355 | -------------------------------------------------------------------------------- /internal/data/persistence/SqliteManager.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package persistence 17 | 18 | import ( 19 | "GoforPomodoro/internal/domain" 20 | "GoforPomodoro/internal/utils" 21 | "database/sql" 22 | "encoding/json" 23 | "log" 24 | _ "modernc.org/sqlite" 25 | "os" 26 | "sync" 27 | "time" 28 | ) 29 | 30 | type SqliteManager struct { 31 | db *sql.DB 32 | 33 | dbLock sync.RWMutex 34 | 35 | // getChatSettingsItem 1 parameter (chat_id) 36 | getChatSettingsItem *sql.Stmt 37 | 38 | getActiveChatsSettings *sql.Stmt 39 | 40 | // upsertChatSettingsItem all parameters (chat_id, ...) 41 | upsertChatSettingsItem *sql.Stmt 42 | 43 | // deleteChatSettingsItem 1 parameter (chat_id) 44 | deleteChatSettingsItem *sql.Stmt 45 | 46 | requestChan chan interface{} 47 | } 48 | 49 | var _ Manager = &SqliteManager{} 50 | 51 | func NewSqliteManager(db *sql.DB, getChatSettingsItem, getActiveChatsSettings, storeChatSettingsItem, deleteChatSettingsItem *sql.Stmt) *SqliteManager { 52 | manager := &SqliteManager{ 53 | db: db, 54 | getChatSettingsItem: getChatSettingsItem, 55 | getActiveChatsSettings: getActiveChatsSettings, 56 | upsertChatSettingsItem: storeChatSettingsItem, 57 | deleteChatSettingsItem: deleteChatSettingsItem, 58 | requestChan: make(chan interface{}), 59 | } 60 | go manager.run() 61 | return manager 62 | } 63 | 64 | type GetChatSettingsRequest struct { 65 | chatId domain.ChatID 66 | responseChan chan GetChatSettingsResponse 67 | } 68 | 69 | type GetChatSettingsResponse struct { 70 | settings *domain.Settings 71 | err error 72 | } 73 | 74 | type StoreChatSettingsRequest struct { 75 | id domain.ChatID 76 | settings *domain.Settings 77 | responseChan chan error 78 | } 79 | 80 | type DeleteChatSettingsRequest struct { 81 | id domain.ChatID 82 | responseChan chan error 83 | } 84 | 85 | type GetActiveChatSettingsRequest struct { 86 | responseChan chan GetActiveChatSettingsResponse 87 | } 88 | 89 | type GetActiveChatSettingsResponse struct { 90 | settings []utils.Pair[domain.ChatID, *domain.Settings] 91 | err error 92 | } 93 | 94 | // Ensure that there is only a single SqliteManager at a time running for the same DB. 95 | // This channeled approach is designed to avoid locking/unlocking of resources 96 | // No more than one instance at a time should access to the DB. 97 | func (m *SqliteManager) run() { 98 | for req := range m.requestChan { 99 | switch r := req.(type) { 100 | case GetChatSettingsRequest: 101 | row := m.getChatSettingsItem.QueryRow(r.chatId) 102 | settings, err := m.getChatSettings(&r.chatId, row) 103 | r.responseChan <- GetChatSettingsResponse{settings: settings, err: err} 104 | case StoreChatSettingsRequest: 105 | err := m.storeChatSettings(r.id, r.settings) 106 | r.responseChan <- err 107 | case DeleteChatSettingsRequest: 108 | err := m.deleteChatSettings(r.id) 109 | r.responseChan <- err 110 | case GetActiveChatSettingsRequest: 111 | settings, err := m.getActiveChatSettings() 112 | r.responseChan <- GetActiveChatSettingsResponse{settings: settings, err: err} 113 | } 114 | } 115 | } 116 | 117 | func (m *SqliteManager) GetChatSettings(chatId domain.ChatID) (*domain.Settings, error) { 118 | responseChan := make(chan GetChatSettingsResponse) 119 | request := GetChatSettingsRequest{ 120 | chatId: chatId, 121 | responseChan: responseChan, 122 | } 123 | m.requestChan <- request 124 | response := <-responseChan 125 | return response.settings, response.err 126 | } 127 | 128 | func (m *SqliteManager) StoreChatSettings(id domain.ChatID, settings *domain.Settings) error { 129 | responseChan := make(chan error) 130 | request := StoreChatSettingsRequest{ 131 | id: id, 132 | settings: settings, 133 | responseChan: responseChan, 134 | } 135 | m.requestChan <- request 136 | return <-responseChan 137 | } 138 | 139 | func (m *SqliteManager) DeleteChatSettings(id domain.ChatID) error { 140 | responseChan := make(chan error) 141 | request := DeleteChatSettingsRequest{ 142 | id: id, 143 | responseChan: responseChan, 144 | } 145 | m.requestChan <- request 146 | return <-responseChan 147 | } 148 | 149 | func (m *SqliteManager) GetActiveChatSettings() ([]utils.Pair[domain.ChatID, *domain.Settings], error) { 150 | print("GetActiveChatSettings()") 151 | responseChan := make(chan GetActiveChatSettingsResponse) 152 | request := GetActiveChatSettingsRequest{ 153 | responseChan: responseChan, 154 | } 155 | print("GetActiveChatSettings -- before request") 156 | m.requestChan <- request 157 | print("GetActiveChatSettings -- after request / before response") 158 | response := <-responseChan 159 | print("GetActiveChatSettings -- after response") 160 | return response.settings, response.err 161 | } 162 | 163 | func (m *SqliteManager) OpenDatabase(dataSourceName string) error { 164 | if _, err := os.Stat(dataSourceName); err != nil { 165 | // file does not exist or is not available. 166 | return err 167 | } 168 | 169 | db, err := sql.Open("sqlite", dataSourceName) 170 | 171 | if err != nil { 172 | log.Println("[SqliteManager] ERROR AT OPENING DATABASE") 173 | } else { 174 | m.db = db 175 | m.InitializePreparedStatements() 176 | m.requestChan = make(chan interface{}) 177 | go m.run() 178 | } 179 | 180 | return err 181 | } 182 | 183 | func (m *SqliteManager) InitializePreparedStatements() { 184 | var err error 185 | 186 | m.getChatSettingsItem, err = m.db.Prepare(` 187 | SELECT * 188 | FROM chat_settings 189 | WHERE chat_id = ?`) 190 | if err != nil { 191 | log.Printf("[SQLITE MANAGER] ERROR IN PREPARING STATEMENTS (SELECT)! (%s)\n", err.Error()) 192 | panic(err) 193 | } 194 | 195 | m.getActiveChatsSettings, err = m.db.Prepare(` 196 | SELECT * 197 | FROM chat_settings 198 | WHERE active = true`) 199 | 200 | m.upsertChatSettingsItem, err = m.db.Prepare(` 201 | INSERT INTO chat_settings 202 | (chat_id, 203 | default_sprint_duration_set, 204 | default_pomodoro_duration_set, 205 | default_rest_duration_set, 206 | running_sprint_duration_set, 207 | running_pomodoro_duration_set, 208 | running_rest_duration_set, 209 | running_sprint_duration, 210 | running_pomodoro_duration, 211 | running_rest_duration, 212 | running_end_next_sprint_ts, 213 | running_end_next_rest_ts, 214 | running_is_cancel, 215 | running_is_paused, 216 | running_is_rest, 217 | running_is_finished, 218 | autorun, 219 | is_group, 220 | subscribers, 221 | active) 222 | VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) 223 | ON CONFLICT (chat_id) DO UPDATE SET 224 | default_sprint_duration_set = ?, 225 | default_pomodoro_duration_set = ?, 226 | default_rest_duration_set = ?, 227 | running_sprint_duration_set = ?, 228 | running_pomodoro_duration_set = ?, 229 | running_rest_duration_set = ?, 230 | running_sprint_duration = ?, 231 | running_pomodoro_duration = ?, 232 | running_rest_duration = ?, 233 | running_end_next_sprint_ts = ?, 234 | running_end_next_rest_ts = ?, 235 | running_is_cancel = ?, 236 | running_is_paused = ?, 237 | running_is_rest = ?, 238 | running_is_finished = ?, 239 | autorun = ?, 240 | is_group = ?, 241 | subscribers = ?, 242 | active = ? 243 | WHERE chat_id = ? 244 | `) 245 | if err != nil { 246 | log.Printf("[SQLITE MANAGER] ERROR IN PREPARING STATEMENTS (INSERT)! (%s)\n", err.Error()) 247 | panic(err) 248 | } 249 | /* 250 | m.updateChatSettingsItem, err = m.db.Prepare(` 251 | UPDATE chat_settings SET 252 | chat_id = ?, 253 | default_sprint_duration_set = ?, 254 | default_pomodoro_duration_set = ?, 255 | default_rest_duration_set = ?, 256 | running_sprint_duration_set = ?, 257 | running_pomodoro_duration_set = ?, 258 | running_rest_duration_set = ?, 259 | running_sprint_duration = ?, 260 | running_pomodoro_duration = ?, 261 | running_rest_duration = ?, 262 | running_end_next_sprint_ts = ?, 263 | running_end_next_rest_ts = ?, 264 | running_is_cancel = ?, 265 | running_is_paused = ?, 266 | running_is_rest = ?, 267 | running_is_finished = ?, 268 | autorun = ?, 269 | is_group = ?, 270 | subscribers = ?, 271 | active = ? 272 | WHERE chat_id = ?;`) 273 | if err != nil { 274 | log.Printf("[SQLITE MANAGER] ERROR IN PREPARING STATEMENTS (UPDATE)! (%s)\n", err.Error()) 275 | panic(err) 276 | } 277 | */ 278 | m.deleteChatSettingsItem, err = m.db.Prepare(` 279 | DELETE FROM chat_settings 280 | WHERE chat_id = ?`) 281 | if err != nil { 282 | log.Printf("[SqliteManager] ERROR IN PREPARING STATEMENTS (DELETE)! (%s)\n", err.Error()) 283 | panic(err) 284 | } 285 | } 286 | 287 | type Scannable interface { 288 | Err() error 289 | Scan(dest ...any) error 290 | } 291 | 292 | func (m *SqliteManager) getChatSettings(chatId *domain.ChatID, row Scannable) (*domain.Settings, error) { 293 | if row.Err() != nil { 294 | log.Printf("[SqliteManager] ERROR AT RETRIEVING CHAT ID (%v), error: %v\n", chatId, row.Err()) 295 | return nil, row.Err() 296 | } 297 | 298 | autorun := false 299 | isGroup := false 300 | 301 | var subscribers []domain.ChatID 302 | var subscribersText string 303 | var active bool 304 | 305 | defaultS := domain.SessionDefaultData{} 306 | 307 | runningS := domain.SessionInitData{} 308 | 309 | var endNextSprintTimestamp *time.Time 310 | var endNextRestTimestamp *time.Time 311 | 312 | var _chatId domain.ChatID 313 | scanErr := row.Scan( 314 | &_chatId, 315 | &defaultS.SprintDurationSet, 316 | &defaultS.PomodoroDurationSet, 317 | &defaultS.RestDurationSet, 318 | 319 | &runningS.SprintDurationSet, 320 | &runningS.PomodoroDurationSet, 321 | &runningS.RestDurationSet, 322 | 323 | &runningS.SprintDuration, 324 | &runningS.PomodoroDuration, 325 | &runningS.RestDuration, 326 | 327 | &endNextSprintTimestamp, 328 | &endNextRestTimestamp, 329 | 330 | &runningS.IsCancel, 331 | &runningS.IsPaused, 332 | &runningS.IsRest, 333 | &runningS.IsFinished, 334 | &autorun, 335 | &isGroup, 336 | &subscribersText, 337 | &active, 338 | ) 339 | 340 | // log.Println("_chatId:", _chatId) 341 | 342 | if scanErr != nil { 343 | // log.Printf("[SqliteManager] ERROR IN SCANNING (%v)\n", scanErr.Error()) 344 | 345 | return nil, scanErr 346 | } 347 | 348 | if *chatId == 0 { 349 | *chatId = _chatId 350 | } else if *chatId != _chatId { 351 | log.Println("[SqliteManager] This condition should have never happened.") 352 | } 353 | 354 | if endNextSprintTimestamp != nil { 355 | runningS.EndNextSprintTimestamp = *endNextSprintTimestamp 356 | } 357 | 358 | if endNextRestTimestamp != nil { 359 | runningS.EndNextRestTimestamp = *endNextRestTimestamp 360 | } 361 | 362 | if subscribersText != "" { 363 | jsonErr := json.Unmarshal([]byte(subscribersText), &subscribers) 364 | if jsonErr != nil { 365 | 366 | log.Printf("[SqliteManager] ERROR AT DECODING JSON FROM (%v)\n", subscribersText) 367 | 368 | return nil, jsonErr 369 | } 370 | } 371 | 372 | settings := &domain.Settings{ 373 | SessionDefault: defaultS, 374 | SessionRunning: runningS.ToSession(), 375 | Autorun: autorun, 376 | IsGroup: isGroup, 377 | Subscribers: subscribers, 378 | } 379 | return settings, nil 380 | } 381 | 382 | func (m *SqliteManager) getChatSettingsOuter(chatId domain.ChatID) (*domain.Settings, error) { 383 | row := m.getChatSettingsItem.QueryRow(chatId) 384 | 385 | return m.getChatSettings(&chatId, row) 386 | } 387 | 388 | func (m *SqliteManager) storeChatSettings(chatId domain.ChatID, settings *domain.Settings) error { 389 | if chatId == 0 { 390 | return nil 391 | } 392 | 393 | sessionRunning := settings.SessionRunning 394 | if sessionRunning == nil { 395 | sessionRunning = new(domain.Session) 396 | } 397 | 398 | defaultSprintDurationSet := settings.SessionDefault.SprintDurationSet 399 | defaultPomodoroDurationSet := settings.SessionDefault.PomodoroDurationSet 400 | defaultRestDurationSet := settings.SessionDefault.RestDurationSet 401 | 402 | runningSprintDurationSet := sessionRunning.GetSprintDurationSet() 403 | runningPomodoroDurationSet := sessionRunning.GetPomodoroDurationSet() 404 | runningRestDurationSet := sessionRunning.GetRestDurationSet() 405 | 406 | runningSprintDuration := sessionRunning.GetSprintDuration() 407 | runningPomodoroDuration := sessionRunning.GetPomodoroDuration() 408 | runningRestDuration := sessionRunning.GetRestDuration() 409 | 410 | endNextSprintTs := sessionRunning.EndNextSprintTimestamp() 411 | endNextRestTs := sessionRunning.EndNextRestTimestamp() 412 | 413 | runningIsCancel := sessionRunning.IsCanceled() 414 | runningIsPaused := sessionRunning.IsPaused() 415 | runningIsRest := sessionRunning.IsRest() 416 | runningIsFinished := sessionRunning.IsFinished() 417 | autorun := settings.Autorun 418 | isGroup := settings.IsGroup 419 | subscribers, errM := json.Marshal(settings.Subscribers) 420 | if errM != nil { 421 | subscribers = nil 422 | log.Printf("[SqliteManager] ERROR AT ENCODING JSON FROM (%v)\n", settings.Subscribers) 423 | } 424 | active := sessionRunning.State() == "Running" 425 | 426 | _, err := m.upsertChatSettingsItem.Exec(chatId, 427 | defaultSprintDurationSet, 428 | defaultPomodoroDurationSet, 429 | defaultRestDurationSet, 430 | runningSprintDurationSet, 431 | runningPomodoroDurationSet, 432 | runningRestDurationSet, 433 | runningSprintDuration, 434 | runningPomodoroDuration, 435 | runningRestDuration, 436 | endNextSprintTs, 437 | endNextRestTs, 438 | runningIsCancel, 439 | runningIsPaused, 440 | runningIsRest, 441 | runningIsFinished, 442 | autorun, 443 | isGroup, 444 | subscribers, 445 | active, 446 | defaultSprintDurationSet, 447 | defaultPomodoroDurationSet, 448 | defaultRestDurationSet, 449 | runningSprintDurationSet, 450 | runningPomodoroDurationSet, 451 | runningRestDurationSet, 452 | runningSprintDuration, 453 | runningPomodoroDuration, 454 | runningRestDuration, 455 | endNextSprintTs, 456 | endNextRestTs, 457 | runningIsCancel, 458 | runningIsPaused, 459 | runningIsRest, 460 | runningIsFinished, 461 | autorun, 462 | isGroup, 463 | subscribers, 464 | active, 465 | chatId, 466 | ) 467 | 468 | if err != nil { 469 | log.Printf("[SqliteManager] ERROR AT STORING RECORD! (%v)\n", err.Error()) 470 | } 471 | 472 | return err 473 | } 474 | 475 | func (m *SqliteManager) deleteChatSettings(chatId domain.ChatID) error { 476 | _, err := m.deleteChatSettingsItem.Exec(chatId) 477 | 478 | return err 479 | } 480 | 481 | func (m *SqliteManager) getActiveChatSettings() ([]utils.Pair[domain.ChatID, *domain.Settings], error) { 482 | rows, err := m.getActiveChatsSettings.Query() 483 | if err != nil { 484 | return nil, err 485 | } 486 | 487 | defer func() { 488 | err := rows.Close() 489 | if err != nil { 490 | log.Printf("[GetActiveChatSettings] err at Close(): %v\n", err.Error()) 491 | } 492 | }() 493 | 494 | var pairs []utils.Pair[domain.ChatID, *domain.Settings] 495 | 496 | for rows.Next() { 497 | var chatId domain.ChatID 498 | 499 | settings, scanErr := m.getChatSettings(&chatId, rows) 500 | 501 | if scanErr != nil { 502 | log.Println("[GetActiveChatSettings] internal scan error.") 503 | continue 504 | } 505 | 506 | newPair := utils.Pair[domain.ChatID, *domain.Settings]{ 507 | First: chatId, 508 | Second: settings, 509 | } 510 | pairs = append(pairs, newPair) 511 | } 512 | return pairs, nil 513 | } 514 | 515 | func (m *SqliteManager) LockDB() { 516 | m.dbLock.Lock() 517 | } 518 | 519 | func (m *SqliteManager) UnlockDB() { 520 | m.dbLock.Unlock() 521 | } 522 | -------------------------------------------------------------------------------- /internal/domain/Session.go: -------------------------------------------------------------------------------- 1 | // This file is part of GoforPomodoro. 2 | // 3 | // GoforPomodoro is free software: you can redistribute it and/or modify 4 | // it under the terms of the GNU Affero General Public License as published by 5 | // the Free Software Foundation, either version 3 of the License, or 6 | // (at your option) any later version. 7 | // 8 | // GoforPomodoro is distributed in the hope that it will be useful, 9 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | // GNU Affero General Public License for more details. 12 | // 13 | // You should have received a copy of the GNU Affero General Public License 14 | // along with GoforPomodoro. If not, see . 15 | 16 | package domain 17 | 18 | import ( 19 | "GoforPomodoro/internal/utils" 20 | "fmt" 21 | "log" 22 | "time" 23 | ) 24 | 25 | type DispatchAction struct { 26 | Paused bool 27 | Canceled bool 28 | Finished bool 29 | Resumed bool 30 | RestStarted bool 31 | RestFinished bool 32 | } 33 | 34 | type SprintDuration int 35 | type PomodoroDuration int64 36 | type RestDuration int64 37 | 38 | const UnspecifiedSprintCardinality = -100 39 | const DefaultRestTime = 5 * 60 40 | 41 | func (d SprintDuration) ToInt() int { 42 | return int(d) 43 | } 44 | 45 | func (d PomodoroDuration) Seconds() int { 46 | return int(d) 47 | } 48 | 49 | func (d RestDuration) Seconds() int { 50 | return int(d) 51 | } 52 | 53 | type SessionData struct { 54 | // SprintDuration captures the number of sprints that the session has yet. 55 | // It can be updated during the run of a session. 56 | // 57 | // Use SprintDurationSet if you want to refer to the total number of 58 | // sprints. 59 | SprintDuration 60 | 61 | // PomodoroDuration is used with reference to how much time is left for the 62 | // current pomodoro in run. 63 | // 64 | // Use PomodoroDurationSet if you want to refer to the defined pomodoro 65 | // duration for the session. 66 | PomodoroDuration 67 | 68 | // RestDuration is used with reference to how much time is left for the 69 | // current pomodoro rest in run. 70 | // 71 | // Use RestDurationSet if you want to refer to the defined pomodoro rest 72 | // duration for the session. 73 | RestDuration 74 | 75 | IsRest bool 76 | IsPaused bool 77 | IsCancel bool 78 | IsFinished bool 79 | } 80 | 81 | type SessionDefaultData struct { 82 | SprintDurationSet SprintDuration 83 | PomodoroDurationSet PomodoroDuration 84 | RestDurationSet RestDuration 85 | } 86 | 87 | func SessionDefaultDataFromSession(s *Session) (sdd SessionDefaultData) { 88 | sdd.PomodoroDurationSet = s.GetPomodoroDurationSet() 89 | sdd.RestDurationSet = s.GetRestDurationSet() 90 | sdd.SprintDurationSet = s.GetSprintDurationSet() 91 | 92 | return 93 | } 94 | 95 | func (sdd SessionDefaultData) ToInitData() (sid SessionInitData) { 96 | sid.SprintDurationSet = sdd.SprintDurationSet 97 | sid.PomodoroDurationSet = sdd.PomodoroDurationSet 98 | sid.RestDurationSet = sdd.RestDurationSet 99 | 100 | sid.SprintDuration = sdd.SprintDurationSet 101 | sid.PomodoroDuration = sdd.PomodoroDurationSet 102 | sid.RestDuration = sdd.RestDurationSet 103 | 104 | sid.IsPaused = true 105 | sid.IsRest = false 106 | sid.IsFinished = false 107 | sid.IsCancel = false 108 | 109 | return 110 | } 111 | 112 | // SessionInitData represents a struct you use to initialize a session. 113 | type SessionInitData struct { 114 | SprintDurationSet SprintDuration 115 | PomodoroDurationSet PomodoroDuration 116 | RestDurationSet RestDuration 117 | 118 | SprintDuration 119 | PomodoroDuration 120 | RestDuration 121 | 122 | EndNextSprintTimestamp time.Time 123 | EndNextRestTimestamp time.Time 124 | 125 | IsRest bool 126 | IsPaused bool 127 | IsCancel bool 128 | IsFinished bool 129 | } 130 | 131 | func (sid SessionInitData) ToSession() (s *Session) { 132 | s = new(Session) 133 | 134 | s.sprintDurationSet = sid.SprintDurationSet 135 | s.pomodoroDurationSet = sid.PomodoroDurationSet 136 | s.restDurationSet = sid.RestDurationSet 137 | 138 | s.data.SprintDuration = sid.SprintDuration 139 | s.data.PomodoroDuration = sid.PomodoroDuration 140 | s.data.RestDuration = sid.RestDuration 141 | 142 | s.data.IsCancel = sid.IsCancel 143 | s.data.IsPaused = sid.IsPaused 144 | s.data.IsRest = sid.IsRest 145 | s.data.IsFinished = sid.IsFinished 146 | 147 | if !sid.EndNextRestTimestamp.IsZero() { 148 | s.endNextRestTimestamp = &sid.EndNextRestTimestamp 149 | } 150 | if !sid.EndNextSprintTimestamp.IsZero() { 151 | s.endNextSprintTimestamp = &sid.EndNextSprintTimestamp 152 | } 153 | 154 | return 155 | } 156 | 157 | func (s *Session) ToInitData() (sid SessionInitData) { 158 | sid.SprintDurationSet = s.sprintDurationSet 159 | sid.PomodoroDurationSet = s.pomodoroDurationSet 160 | sid.RestDurationSet = s.restDurationSet 161 | 162 | sid.SprintDuration = s.data.SprintDuration 163 | sid.PomodoroDuration = s.data.PomodoroDuration 164 | sid.RestDuration = s.data.RestDuration 165 | 166 | sid.IsPaused = s.data.IsPaused 167 | sid.IsRest = s.data.IsRest 168 | sid.IsFinished = s.data.IsFinished 169 | sid.IsCancel = s.data.IsCancel 170 | 171 | return 172 | } 173 | 174 | type Session struct { 175 | ActionsChannel chan DispatchAction 176 | 177 | endNextSprintTimestamp *time.Time 178 | endNextRestTimestamp *time.Time 179 | 180 | // sprintDurationSet represents how many sprints the session is the session 181 | // intended to have. 182 | // 183 | // For example, sprintDurationSet == 4 means that there will be 4 different 184 | // sprints in the session, separated by (4-1) rests. 185 | // 186 | // Unlike SprintDuration, this variable is intended to be kept constant 187 | // during all the session. SprintDuration is used with reference to how 188 | // many sprints are left. 189 | sprintDurationSet SprintDuration 190 | 191 | // pomodoroDurationSet represents the time of duration of a pomodoro 192 | // expressed in SECONDS. 193 | // 194 | // Unlike PomodoroDuration, this variable is intended to be kept constant 195 | // during all the session. PomodoroDuration is used with reference to how 196 | // much time is left for the current pomodoro in run. 197 | pomodoroDurationSet PomodoroDuration 198 | 199 | // restDurationSet represents the time of rest duration of a pomodoro 200 | // expressed in SECONDS. 201 | // 202 | // Unlike RestDuration, this variable is intended to be kept constant 203 | // during all the session. RestDuration is used with reference to how 204 | // much time is left for the current pomodoro rest in run. 205 | restDurationSet RestDuration 206 | 207 | data SessionData 208 | } 209 | 210 | // GetRestDuration returns how much time (in SECONDS) the actual rest 211 | // will go on before its end. 212 | // 213 | // (Decreases while the rest goes on) 214 | func (s *Session) GetRestDuration() RestDuration { 215 | if s.IsFinished() { 216 | return 0 217 | } 218 | 219 | if s.endNextRestTimestamp == nil || s.IsPaused() { 220 | // log.Println("Fallback to s.RestDuration") 221 | return s.data.RestDuration 222 | } 223 | 224 | return RestDuration(s.endNextRestTimestamp.Sub(time.Now()).Seconds()) // s.PomodoroDuration 225 | 226 | // return s.RestDuration 227 | } 228 | 229 | // GetRestDurationSet returns the time of duration of a rest (in the current 230 | // session expressed in SECONDS. 231 | // 232 | // Unlike GetRestDuration, this method returns a constant value 233 | // during all the session. If you want to know how much time is left in the 234 | // rest (if it's rest time), use GetRestDuration instead. 235 | func (s *Session) GetRestDurationSet() RestDuration { 236 | return s.restDurationSet 237 | } 238 | 239 | // GetPomodoroDuration returns how much time (in SECONDS) the actual sprint 240 | // will go on before its end. 241 | // 242 | // (Decreases while the sprint goes on) 243 | func (s *Session) GetPomodoroDuration() PomodoroDuration { 244 | if s.IsFinished() { 245 | return 0 246 | } 247 | 248 | if s.endNextSprintTimestamp == nil || s.IsPaused() { 249 | // log.Println("Fallback to s.PomodoroDuration") 250 | return s.data.PomodoroDuration 251 | } 252 | 253 | return PomodoroDuration(s.endNextSprintTimestamp.Sub(time.Now()).Seconds()) 254 | } 255 | 256 | // GetPomodoroDurationSet returns the time of duration of a pomodoro 257 | // expressed in SECONDS. 258 | // 259 | // Unlike GetPomodoroDuration, this method returns a constant value 260 | // during all the session. If you want to know how much time is left in this 261 | // sprint, use GetPomodoroDuration instead. 262 | func (s *Session) GetPomodoroDurationSet() PomodoroDuration { 263 | return s.pomodoroDurationSet 264 | } 265 | 266 | // GetSprintDuration returns how many sprints the session are left. 267 | // 268 | // (Decreases while the session goes on) 269 | func (s *Session) GetSprintDuration() SprintDuration { 270 | return s.data.SprintDuration 271 | } 272 | 273 | func (s *Session) SprintDurationFinished() bool { 274 | return s.data.SprintDuration > UnspecifiedSprintCardinality && 275 | s.data.SprintDuration < 0 276 | } 277 | 278 | func (s *Session) IsSprintDurationUnspecified() bool { 279 | return s.data.SprintDuration <= UnspecifiedSprintCardinality 280 | } 281 | 282 | // GetSprintDurationSet returns how many sprints the session should have 283 | // (independently of how many remain) 284 | func (s *Session) GetSprintDurationSet() SprintDuration { 285 | return s.sprintDurationSet 286 | } 287 | 288 | // IsRest returns true if it is rest time for the session. 289 | func (s *Session) IsRest() bool { 290 | return s.data.IsRest 291 | } 292 | 293 | // DefaultSession Return a default session. 294 | // 295 | // ActionsChannel not initialized, therefore should call .InitChannel() if you 296 | // plan to run a session from this object's value. 297 | func DefaultSession() SessionDefaultData { 298 | return SessionDefaultData{ 299 | SprintDurationSet: 4, 300 | PomodoroDurationSet: 25 * 60, 301 | RestDurationSet: 5 * 60, 302 | } 303 | } 304 | 305 | // InitChannel initialize ActionsChannel attribute; currently done with a 306 | // buffer of 10 elements. 307 | func (s *Session) InitChannel() *Session { 308 | s.ActionsChannel = make(chan DispatchAction, 10) 309 | return s 310 | } 311 | 312 | // assignTimestamps Assign timestamp fields for integrity of Session structure. 313 | // 314 | // After each sprint or rest end, their fields should be updated. 315 | // 316 | // This method is currently called internally in Session methods and therefore 317 | // has been made private. 318 | func (s *Session) assignTimestamps() { 319 | s.endNextSprintTimestamp = nil 320 | s.endNextRestTimestamp = nil 321 | 322 | var pomodoroDurationTime time.Duration = 0 323 | var restDurationTime time.Duration = 0 324 | 325 | if s.IsRest() { 326 | restDurationTime = time.Second * time.Duration(s.data.RestDuration) 327 | 328 | s.endNextRestTimestamp = utils.TimePtr(time.Now().Local().Add(restDurationTime)) 329 | } else { 330 | pomodoroDurationTime = time.Second * time.Duration(s.data.PomodoroDuration) 331 | restDurationTime = time.Second * time.Duration(s.restDurationSet) 332 | 333 | s.endNextSprintTimestamp = utils.TimePtr(time.Now().Local().Add(pomodoroDurationTime)) 334 | 335 | s.endNextRestTimestamp = utils.TimePtr(time.Now().Local().Add(pomodoroDurationTime + restDurationTime)) 336 | } 337 | } 338 | 339 | // ReadingActionChannel Get the ActionsChannel in receive-only mode. 340 | func (s *Session) ReadingActionChannel() <-chan DispatchAction { 341 | return s.ActionsChannel 342 | } 343 | 344 | // WritingActionChannel Get the ActionsChannel in send-only mode. 345 | func (s *Session) WritingActionChannel() chan<- DispatchAction { 346 | return s.ActionsChannel 347 | } 348 | 349 | // IsZero Returns true if this session object was instantiated but not 350 | // meaningfully initialized. 351 | func (s *Session) IsZero() bool { 352 | return s == nil || s.GetPomodoroDurationSet() == 0 353 | } 354 | 355 | // String Print the state's session in human-readable format (aimed at the 356 | // user). 357 | func (s *Session) String() string { 358 | if s == nil { 359 | return "nil" 360 | } 361 | 362 | if s.GetPomodoroDurationSet() == 0 { 363 | return "No session" 364 | } 365 | 366 | var middleStr string 367 | sprintDuration := s.GetSprintDuration() 368 | if s.IsRest() { 369 | sprintDuration += 1 370 | 371 | middleStr = fmt.Sprintf("\nTime for current rest remaining: %s", utils.NiceTimeFormatting(s.GetRestDuration().Seconds())) 372 | } else { 373 | middleStr = fmt.Sprintf("\nTime for current pomodoro remaining: %s", utils.NiceTimeFormatting(s.GetPomodoroDuration().Seconds())) 374 | } 375 | 376 | var sprintDurationSetStr string 377 | var pomodorosRemainingStr string 378 | if s.IsSprintDurationUnspecified() { 379 | pomodorosRemainingStr = "Unspecified" 380 | sprintDurationSetStr = "X" 381 | } else { 382 | pomodorosRemainingStr = fmt.Sprintf("%d", sprintDuration) 383 | sprintDurationSetStr = fmt.Sprintf("%d", s.GetSprintDurationSet()) 384 | } 385 | 386 | return fmt.Sprintf("Session of %s🍅 x %dm + %dm", 387 | sprintDurationSetStr, s.GetPomodoroDurationSet()/60, s.GetRestDurationSet()/60) + 388 | fmt.Sprintf("\nPomodoros remaining: %s", pomodorosRemainingStr) + 389 | middleStr + 390 | fmt.Sprintf("\n\nCurrent session state: %s", s.State()) 391 | } 392 | 393 | func (sdd SessionDefaultData) String() string { 394 | if sdd.PomodoroDurationSet == 0 { 395 | return "No session" 396 | } 397 | 398 | var middleStr string 399 | sprintDuration := sdd.SprintDurationSet 400 | 401 | var sprintDurationSetStr string 402 | var pomodorosRemainingStr string 403 | if sdd.SprintDurationSet <= UnspecifiedSprintCardinality { 404 | pomodorosRemainingStr = "Unspecified" 405 | sprintDurationSetStr = "X" 406 | } else { 407 | pomodorosRemainingStr = fmt.Sprintf("%d", sprintDuration) 408 | sprintDurationSetStr = fmt.Sprintf("%d", sdd.SprintDurationSet) 409 | } 410 | 411 | return fmt.Sprintf("Session of %s🍅 x %dm + %dm", 412 | sprintDurationSetStr, sdd.PomodoroDurationSet/60, sdd.RestDurationSet/60) + 413 | fmt.Sprintf("\nPomodoros remaining: %s", pomodorosRemainingStr) + 414 | middleStr + 415 | fmt.Sprintf("\n\nCurrent session state: Pending") 416 | } 417 | 418 | // LeftTimeMessage Print in a string in human-readable format (aimed at the 419 | // user) how much time is left either for task time or for rest. 420 | func (s *Session) LeftTimeMessage() string { 421 | if s.IsPaused() && !s.IsFinished() { 422 | return "Pomodoro in pause. (use /resume)" 423 | } 424 | if s.IsZero() || s.IsCanceled() || s.IsStopped() { 425 | return "No running pomodoros!" 426 | } 427 | if s.IsRest() { 428 | return "Rest for other " + utils.NiceTimeFormatting(s.GetRestDuration().Seconds()) 429 | } else { 430 | return "Task time: " + utils.NiceTimeFormatting(s.GetPomodoroDuration().Seconds()) + " left." 431 | } 432 | } 433 | 434 | func (s *Session) IsStopped() bool { 435 | if s.GetPomodoroDuration() <= 0 || 436 | (!s.IsSprintDurationUnspecified() && s.GetSprintDuration() < 0) || 437 | s.data.IsPaused || 438 | s.data.IsCancel || 439 | s.data.IsFinished { 440 | return true 441 | } 442 | 443 | return false 444 | } 445 | 446 | // IsCanceled returns true if Session has been canceled, otherwise false. 447 | func (s *Session) IsCanceled() bool { 448 | return s.data.IsCancel 449 | } 450 | 451 | // IsPaused returns true if Session has been paused or never started, otherwise false. 452 | func (s *Session) IsPaused() bool { 453 | return s.data.IsPaused 454 | } 455 | 456 | // IsFinished returns true if Session has been completed, otherwise false. 457 | // Note that sessions are not expected to be revived after they become 458 | // finished. 459 | func (s *Session) IsFinished() bool { 460 | return s.data.IsFinished 461 | } 462 | 463 | // State return the Session's state as a string. 464 | // 465 | // # The values are 466 | // 467 | // "Pending" if the session was never started (and is actually on pause) 468 | // 469 | // "Paused" if the session is on pause, and it was started earlier. 470 | // 471 | // "Canceled" if the session has been canceled (s.IsCanceled() == true) 472 | // 473 | // "Finished" if the session is finished (s.IsFinished() == true) 474 | // 475 | // "Stopped" if the session is not running and none result of the above was 476 | // the state. 477 | // 478 | // "Running" if the session is actually running 479 | func (s *Session) State() string { 480 | var stateStr string 481 | if s.IsPaused() { 482 | if s.GetPomodoroDuration() == s.GetPomodoroDurationSet() && 483 | s.GetSprintDuration() == s.GetSprintDurationSet() && 484 | s.GetRestDuration() == s.GetRestDurationSet() { 485 | 486 | stateStr = "Pending" 487 | } else { 488 | stateStr = "Paused" 489 | } 490 | } else if s.IsCanceled() { 491 | stateStr = "Canceled" 492 | } else if s.IsFinished() { 493 | stateStr = "Finished" 494 | } else if s.IsStopped() { 495 | stateStr = "Stopped" 496 | } else { 497 | stateStr = "Running" 498 | } 499 | return stateStr 500 | } 501 | 502 | // Pause Prepare a Session to be paused. 503 | // This method modifies Session data structures, so should be used 504 | // in a context where it is actually safe to do so. 505 | // 506 | // At the time of writing, each Session obj in this project is managed by one 507 | // and only one goroutine. Pause() call is internal to such goroutine, 508 | // therefore, it should not happen elsewhere. 509 | func (s *Session) Pause() { 510 | // Cache pomodoro and rest duration. We will use them again to assign new timestamps. 511 | s.data.PomodoroDuration = s.GetPomodoroDuration() 512 | s.data.RestDuration = s.GetRestDuration() 513 | 514 | // Nil the timestamps (they have to be re-calculated) 515 | s.endNextSprintTimestamp = nil 516 | s.endNextRestTimestamp = nil 517 | 518 | s.data.IsPaused = true 519 | } 520 | 521 | // Cancel Set IsCancel internal attribute to true. 522 | // This method modifies Session data structures, so should be used 523 | // in a context where it is actually safe to do so. 524 | func (s *Session) Cancel() { 525 | s.data.IsCancel = true 526 | } 527 | 528 | // SetFinished Set IsFinished internal attribute to true. 529 | // This method modifies Session data structures, so should be used 530 | // in a context where it is actually safe to do so. 531 | func (s *Session) SetFinished() { 532 | s.data.IsFinished = true 533 | } 534 | 535 | // Resume Prepare a Session to be resumed. 536 | // This method modifies Session data structures, so should be used 537 | // in a context where it is actually safe to do so. 538 | func (s *Session) Resume() { 539 | s.data.IsPaused = false 540 | 541 | s.assignTimestamps() 542 | } 543 | 544 | // Start Prepare a Session for the start. 545 | // This method modifies Session data structures, so should be used 546 | // in a context where it is actually safe to do so. 547 | func (s *Session) Start() { 548 | s.data.IsPaused = false 549 | s.data.IsCancel = false 550 | 551 | s.data.SprintDuration -= 1 552 | 553 | s.assignTimestamps() 554 | } 555 | 556 | // RestStarted Prepare a Session object for rest start. 557 | // This method modifies Session data structures, so should be used 558 | // in a context where it is actually safe to do so. 559 | // 560 | // At the time of writing, each Session obj in this project is managed by one 561 | // and only one goroutine. RestStarted() call is internal to such goroutine, 562 | // therefore, it should not happen elsewhere. 563 | func (s *Session) RestStarted() { 564 | s.data.IsRest = true 565 | s.data.RestDuration = s.restDurationSet 566 | s.assignTimestamps() 567 | } 568 | 569 | // RestFinished Prepare a Session object for rest end. 570 | // This method modifies Session data structures, so should be used 571 | // in a context where it is actually safe to do so. 572 | // 573 | // At the time of writing, each Session obj in this project is managed by one 574 | // and only one goroutine. RestFinished() call is internal to such goroutine, 575 | // therefore, it should not happen elsewhere. 576 | func (s *Session) RestFinished() { 577 | s.data.IsRest = false 578 | s.data.PomodoroDuration = s.pomodoroDurationSet 579 | s.assignTimestamps() 580 | } 581 | 582 | // DecreaseSprintDuration Diminish by 1 the SprintDuration attribute. 583 | // This method modifies Session data structures, so should be used 584 | // in a context where it is actually safe to do so. 585 | // 586 | // At the time of writing, each Session obj in this project is managed by one 587 | // and only one goroutine. DecreaseSprintDuration() call is internal to such 588 | // goroutine, therefore, it should not happen elsewhere. 589 | func (s *Session) DecreaseSprintDuration() { 590 | if s.data.SprintDuration == UnspecifiedSprintCardinality { 591 | return 592 | } 593 | 594 | s.data.SprintDuration -= 1 595 | } 596 | 597 | // ClearChannel close and clear (set to nil) ActionsChannel attribute. 598 | // Call this method after a session object is discarded (its session manager 599 | // dropped it away). Should be the session be revived (e.g., after a Resume) 600 | // the channel field should be populated again. 601 | func (s *Session) ClearChannel() { 602 | close(s.ActionsChannel) 603 | s.ActionsChannel = nil 604 | } 605 | 606 | // HasSprintEndTimePassed 607 | // Returns true if sprint should be ended at this time, otherwise false. 608 | // It returns false if a timestamp was not set, but this would be an error case 609 | // and printed in the log. 610 | func (s *Session) HasSprintEndTimePassed() bool { 611 | if s.endNextSprintTimestamp == nil { 612 | log.Println("[PROBLEM] s.endNextSprintTimestamp IS nil.") 613 | return false 614 | } 615 | 616 | return time.Now().Local().After(*s.endNextSprintTimestamp) 617 | } 618 | 619 | // HasRestEndTimePassed 620 | // Returns true if rest should be ended at this time, otherwise false. 621 | // It returns false if a timestamp was not set, but this would be an error case 622 | // and printed in the log. 623 | func (s *Session) HasRestEndTimePassed() bool { 624 | if s.endNextRestTimestamp == nil { 625 | log.Println("[PROBLEM] s.endNextRestTimestamp IS nil.") 626 | return false 627 | } 628 | 629 | return time.Now().Local().After(*s.endNextRestTimestamp) 630 | } 631 | 632 | func (s *Session) EndNextSprintTimestamp() *time.Time { 633 | return s.endNextSprintTimestamp 634 | } 635 | 636 | func (s *Session) EndNextRestTimestamp() *time.Time { 637 | return s.endNextRestTimestamp 638 | } 639 | 640 | func (s *Session) CalculateSessionTimeInSeconds() int64 { 641 | numberOfSprints := int64(s.GetSprintDurationSet().ToInt()) 642 | sessionTime := int64(s.GetPomodoroDurationSet().Seconds()) * numberOfSprints 643 | if numberOfSprints > 1 { 644 | sessionTime += int64(s.GetRestDurationSet().Seconds()) * (numberOfSprints - 1) 645 | } 646 | return sessionTime 647 | } 648 | 649 | func (sdd SessionDefaultData) CalculateSessionTimeInSeconds() int64 { 650 | numberOfSprints := int64(sdd.SprintDurationSet) 651 | sessionTime := int64(sdd.PomodoroDurationSet) * numberOfSprints 652 | if numberOfSprints > 1 { 653 | sessionTime += int64(sdd.RestDurationSet) * (numberOfSprints - 1) 654 | } 655 | return sessionTime 656 | } 657 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 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 by 637 | 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 | . 662 | --------------------------------------------------------------------------------