Browse Source

Make all fields private

master
Trevor Slocum 2 years ago
parent
commit
a17ada4291
  1. 98
      database.go
  2. 24
      main.go
  3. 2
      web.go

98
database.go

@ -19,14 +19,14 @@ import (
// Note: SQLite may not be compiled with support for UPDATE/DELETE LIMIT
const (
DatabaseVersion = 1
AccountKeyLength = 32 // Was using MD5 hashes
MessageMaxLength = 4096
GoogleOAuthURL = "https://www.googleapis.com/oauth2/v3/userinfo?alt=json&access_token="
databaseVersion = 1
accountKeyLength = 32 // Was using MD5 hashes
messageMaxLength = 4096
googleOAuthURL = "https://www.googleapis.com/oauth2/v3/userinfo?alt=json&access_token="
)
// TODO: Add indexes
var DatabaseTables = map[string][]string{
var databaseTables = map[string][]string{
"accounts": {
"`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT",
"`key` VARCHAR(145) NOT NULL DEFAULT ''",
@ -68,20 +68,20 @@ var DatabaseTables = map[string][]string{
"`key` VARCHAR(50) NOT NULL PRIMARY KEY",
"`value` TEXT NOT NULL DEFAULT ''"}}
type Database struct {
type database struct {
db *sql.DB
FuncGreatest string
}
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
type Account struct {
type account struct {
ID int
Key string
StreakBuffer int
}
type Session struct {
type session struct {
ID int `json:"id"`
Posted int `json:"posted"`
Started int `json:"started"`
@ -92,24 +92,24 @@ type Session struct {
Modified int `json:"modified"`
}
type RecentSession struct {
Session
type recentSession struct {
session
AccountID int
AccountName string
AccountEmail string
}
func generateKey() string {
b := make([]rune, AccountKeyLength)
b := make([]rune, accountKeyLength)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
func Connect(driver string, dataSource string) (*Database, error) {
func connect(driver string, dataSource string) (*database, error) {
var err error
d := new(Database)
d := new(database)
d.db, err = sql.Open(driver, dataSource)
if err != nil {
@ -141,7 +141,7 @@ func Connect(driver string, dataSource string) (*Database, error) {
return d, nil
}
func (d *Database) CreateTables() error {
func (d *database) CreateTables() error {
var (
tcolumns string
err error
@ -152,7 +152,7 @@ func (d *Database) CreateTables() error {
createQueryExtra = " ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE utf8_unicode_ci"
}
for tname, tcols := range DatabaseTables {
for tname, tcols := range databaseTables {
tcolumns = strings.Join(tcols, ",")
if config.DBDriver == "mysql" {
tcolumns = strings.Replace(tcolumns, "AUTOINCREMENT", "AUTO_INCREMENT", -1)
@ -167,7 +167,7 @@ func (d *Database) CreateTables() error {
return nil
}
func (d *Database) Migrate() error {
func (d *database) Migrate() error {
rows, err := d.db.Query("SELECT `value` FROM meta WHERE `key`=?", "version")
if err != nil {
return fmt.Errorf("failed to fetch database version: %s", err)
@ -190,17 +190,17 @@ func (d *Database) Migrate() error {
if version == -1 {
panic("Unable to migrate database: database version unknown")
} else if version == 0 {
_, err := d.db.Exec("UPDATE meta SET `value`=? WHERE `key`=?", strconv.Itoa(DatabaseVersion), "version")
_, err := d.db.Exec("UPDATE meta SET `value`=? WHERE `key`=?", strconv.Itoa(databaseVersion), "version")
if err != nil {
return fmt.Errorf("failed to save database version: %s", err)
}
}
migrated := false
for version < DatabaseVersion {
for version < databaseVersion {
switch version {
case 1:
// DatabaseVersion 2 migration queries will go here
// databaseVersion 2 migration queries will go here
}
version++
@ -208,7 +208,7 @@ func (d *Database) Migrate() error {
}
if migrated {
_, err := d.db.Exec("UPDATE meta SET `value`=? WHERE `key`=?", strconv.Itoa(DatabaseVersion), "version")
_, err := d.db.Exec("UPDATE meta SET `value`=? WHERE `key`=?", strconv.Itoa(databaseVersion), "version")
if err != nil {
return fmt.Errorf("failed to save updated database version: %s", err)
}
@ -217,10 +217,10 @@ func (d *Database) Migrate() error {
return nil
}
func (d *Database) authenticate(token string) (*Account, error) {
func (d *database) authenticate(token string) (*account, error) {
key := ""
resp, err := http.Get(GoogleOAuthURL + token)
resp, err := http.Get(googleOAuthURL + token)
if err != nil {
return nil, fmt.Errorf("failed to get userinfo from Google: %s", err)
}
@ -284,8 +284,8 @@ func (d *Database) authenticate(token string) (*Account, error) {
return account, nil
}
func (d *Database) getAccount(key string) (*Account, error) {
a := new(Account)
func (d *database) getAccount(key string) (*account, error) {
a := new(account)
err := d.db.QueryRow("SELECT `id`, `key`, `streakbuffer` FROM accounts WHERE `key`=?", key).Scan(&a.ID, &a.Key, &a.StreakBuffer)
if err == sql.ErrNoRows {
return nil, nil
@ -296,7 +296,7 @@ func (d *Database) getAccount(key string) (*Account, error) {
return a, nil
}
func (d *Database) getStreak(accountID int) (int64, int64, int64, error) {
func (d *database) getStreak(accountID int) (int64, int64, int64, error) {
streakDay := int64(0)
streakEnd := int64(0)
topStreak := int64(0)
@ -322,7 +322,7 @@ func (d *Database) getStreak(accountID int) (int64, int64, int64, error) {
return streakDay, streakEnd, topStreak, nil
}
func (d *Database) updateLastActive(accountID int) error {
func (d *database) updateLastActive(accountID int) error {
_, err := d.db.Exec("UPDATE accounts SET `lastactive`=? WHERE `id`=?", time.Now().Unix(), accountID)
if err != nil {
err = fmt.Errorf("failed to update last active: %s", err)
@ -330,7 +330,7 @@ func (d *Database) updateLastActive(accountID int) error {
return err
}
func (d *Database) updateTopStreak(accountID int) error {
func (d *database) updateTopStreak(accountID int) error {
_, err := d.db.Exec("UPDATE accounts SET `topstreak`="+d.FuncGreatest+"(`streak`, `topstreak`) WHERE `id`=?", accountID)
if err != nil {
err = fmt.Errorf("failed to update top streak: %s", err)
@ -338,7 +338,7 @@ func (d *Database) updateTopStreak(accountID int) error {
return err
}
func (d *Database) updateStreakBuffer(accountID int, streakBuffer int) error {
func (d *database) updateStreakBuffer(accountID int, streakBuffer int) error {
_, err := d.db.Exec("UPDATE accounts SET `streakbuffer`=? WHERE `id`=?", streakBuffer, accountID)
if err != nil {
err = fmt.Errorf("failed to update streak buffer: %s", err)
@ -346,7 +346,7 @@ func (d *Database) updateStreakBuffer(accountID int, streakBuffer int) error {
return err
}
func (d *Database) calculateStreak(accountID int, streakBuffer int, tz *time.Location) (int, error) {
func (d *database) calculateStreak(accountID int, streakBuffer int, tz *time.Location) (int, error) {
streak := 0
t := time.Now().In(tz)
@ -372,7 +372,7 @@ func (d *Database) calculateStreak(accountID int, streakBuffer int, tz *time.Loc
return streak, nil
}
func (d *Database) setStreak(streakDay int, accountID int, streakBuffer int, tz *time.Location) error {
func (d *database) setStreak(streakDay int, accountID int, streakBuffer int, tz *time.Location) error {
t := time.Now().In(tz)
if beforeWindowStart(t, streakBuffer) {
t = t.AddDate(0, 0, 1)
@ -396,7 +396,7 @@ func (d *Database) setStreak(streakDay int, accountID int, streakBuffer int, tz
return nil
}
func (d *Database) setSessionStreakDay(started int, streakDay int, accountID int) error {
func (d *database) setSessionStreakDay(started int, streakDay int, accountID int) error {
_, err := d.db.Exec("UPDATE sessions SET `streakday`=? WHERE `account`=? AND `started`=?", streakDay, accountID, started)
if err != nil {
return fmt.Errorf("failed to set session streak day: %s", err)
@ -405,8 +405,8 @@ func (d *Database) setSessionStreakDay(started int, streakDay int, accountID int
return nil
}
func (d *Database) scanSession(rows *sql.Rows) (*Session, error) {
s := new(Session)
func (d *database) scanSession(rows *sql.Rows) (*session, error) {
s := new(session)
err := rows.Scan(&s.ID, &s.Posted, &s.Started, &s.StreakDay, &s.Length, &s.Completed, &s.Message, &s.Modified)
if err != nil {
return nil, fmt.Errorf("failed to scan session: %s", err)
@ -415,8 +415,8 @@ func (d *Database) scanSession(rows *sql.Rows) (*Session, error) {
return s, nil
}
func (d *Database) scanRecentSession(rows *sql.Rows) (*RecentSession, error) {
s := new(RecentSession)
func (d *database) scanRecentSession(rows *sql.Rows) (*recentSession, error) {
s := new(recentSession)
err := rows.Scan(&s.ID, &s.Posted, &s.Started, &s.StreakDay, &s.Length, &s.Completed, &s.Message, &s.Modified, &s.AccountID, &s.AccountName, &s.AccountEmail)
if err != nil {
return nil, fmt.Errorf("failed to scan session: %s", err)
@ -425,11 +425,11 @@ func (d *Database) scanRecentSession(rows *sql.Rows) (*RecentSession, error) {
return s, nil
}
func (d *Database) addSession(s Session, updateSessionStarted int, accountID int, appVer string, appMarket string) (bool, error) {
func (d *database) addSession(s session, updateSessionStarted int, accountID int, appVer string, appMarket string) (bool, error) {
var (
existingSession *Session
updateSession *Session
keepSession *Session
existingSession *session
updateSession *session
keepSession *session
err error
)
@ -450,8 +450,8 @@ func (d *Database) addSession(s Session, updateSessionStarted int, accountID int
return false, nil
}
if len(s.Message) > MessageMaxLength {
s.Message = s.Message[:MessageMaxLength]
if len(s.Message) > messageMaxLength {
s.Message = s.Message[:messageMaxLength]
}
// Fix zero completed from older versions of the app
@ -484,7 +484,7 @@ func (d *Database) addSession(s Session, updateSessionStarted int, accountID int
return true, nil
}
func (d *Database) getSessionByID(sessionID int, accountID int) (*Session, error) {
func (d *database) getSessionByID(sessionID int, accountID int) (*session, error) {
rows, err := d.db.Query("SELECT `id`, `posted`, `started`, `streakday`, `length`, `completed`, `message`, `modified` FROM sessions WHERE `account`=? AND `id`=?", accountID, sessionID)
if err != nil {
return nil, fmt.Errorf("failed to fetch session: %s", err)
@ -498,7 +498,7 @@ func (d *Database) getSessionByID(sessionID int, accountID int) (*Session, error
return nil, nil
}
func (d *Database) getSessionByStarted(started int, accountID int) (*Session, error) {
func (d *database) getSessionByStarted(started int, accountID int) (*session, error) {
rows, err := d.db.Query("SELECT `id`, `posted`, `started`, `streakday`, `length`, `completed`, `message`, `modified` FROM sessions WHERE `account`=? AND `started`=?", accountID, started)
if err != nil {
return nil, fmt.Errorf("failed to fetch session: %s", err)
@ -512,7 +512,7 @@ func (d *Database) getSessionByStarted(started int, accountID int) (*Session, er
return nil, nil
}
func (d *Database) sessionExistsByDate(date time.Time, accountID int, streakBuffer int) (bool, error) {
func (d *database) sessionExistsByDate(date time.Time, accountID int, streakBuffer int) (bool, error) {
windowStart := atWindowStart(date, streakBuffer)
windowEnd := atWindowStart(windowStart.AddDate(0, 0, 1), streakBuffer)
@ -527,8 +527,8 @@ func (d *Database) sessionExistsByDate(date time.Time, accountID int, streakBuff
return sessionid > 0, nil
}
func (d *Database) getAllSessions(accountID int) ([]*Session, error) {
var sessions []*Session
func (d *database) getAllSessions(accountID int) ([]*session, error) {
var sessions []*session
rows, err := d.db.Query("SELECT `id`, `posted`, `started`, `streakday`, `length`, `completed`, `message`, `modified` FROM sessions WHERE `account`=?", accountID)
if err != nil {
@ -548,8 +548,8 @@ func (d *Database) getAllSessions(accountID int) ([]*Session, error) {
return sessions, nil
}
func (d *Database) getRecentSessions() ([]*RecentSession, error) {
var sessions []*RecentSession
func (d *database) getRecentSessions() ([]*recentSession, error) {
var sessions []*recentSession
rows, err := d.db.Query("SELECT `sessions`.`id`, `sessions`.`posted`, `sessions`.`started`, `sessions`.`streakday`, `sessions`.`length`, `sessions`.`completed`, `sessions`.`message`, `sessions`.`modified`, `accounts`.`id` AS `accountid`, `accounts`.`name`, `accounts`.`email` FROM `sessions` LEFT OUTER JOIN `accounts` ON `sessions`.`account` = `accounts`.`id` WHERE `accounts`.`sessionspublic` = 1 AND `sessions`.`length` > 110 ORDER BY `sessions`.`completed` DESC LIMIT 50")
if err != nil {
@ -569,7 +569,7 @@ func (d *Database) getRecentSessions() ([]*RecentSession, error) {
return sessions, nil
}
func (d *Database) deleteSession(started int, accountID int) (bool, error) {
func (d *database) deleteSession(started int, accountID int) (bool, error) {
r, err := d.db.Exec("DELETE FROM sessions WHERE `account`=? AND `started`=?", accountID, started)
if err != nil {
return false, fmt.Errorf("failed to delete session: %s", err)

24
main.go

@ -1,4 +1,4 @@
// MediNET - Session repository and community portal for Meditation Assistant
// MediNET - session repository and community portal for Meditation Assistant
// https://gitlab.com/tslocum/medinet
//
// This program is free software: you can redistribute it and/or modify
@ -29,7 +29,7 @@ import (
"gopkg.in/yaml.v2"
)
type Config struct {
type configuration struct {
TimeZone string
DBDriver string
DBSource string
@ -37,7 +37,7 @@ type Config struct {
Web string
}
type Statistics struct {
type statistics struct {
AccountsCreated int
ActiveAccounts []int
@ -46,10 +46,10 @@ type Statistics struct {
}
var (
db *Database
config *Config
PrintDebug bool
stats *Statistics
db *database
config *configuration
printDebug bool
stats *statistics
serverLocation *time.Location
regexpNumbers = regexp.MustCompile("[0-9]+")
@ -57,7 +57,7 @@ var (
)
func logDebug(message string) {
if PrintDebug {
if printDebug {
log.Println(message)
}
}
@ -133,7 +133,7 @@ func main() {
log.Fatalf("Failed to read %s: %v", opts.ConfigFile, err)
}
config = new(Config)
config = new(configuration)
err = yaml.Unmarshal(configData, config)
if err != nil {
log.Fatalf("Failed to read %s: %v", opts.ConfigFile, err)
@ -153,12 +153,12 @@ func main() {
failOnError(err)
serverLocation = loc
PrintDebug = opts.Debug
printDebug = opts.Debug
stats = new(Statistics)
stats = new(statistics)
go printStatistics()
db, err = Connect(config.DBDriver, config.DBSource)
db, err = connect(config.DBDriver, config.DBSource)
failOnError(err)
initWeb()

2
web.go

@ -151,7 +151,7 @@ func handleMediNET(w http.ResponseWriter, r *http.Request) {
postsession := r.FormValue("postsession")
updateSessionStarted, _ := strconv.Atoi(r.FormValue("editstarted"))
var uploadsessions []Session
var uploadsessions []session
err = json.Unmarshal([]byte(u), &uploadsessions)
if err != nil {
log.Printf("ERROR! %v", err)

Loading…
Cancel
Save