commands

package
v0.0.0-...-69ed63b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 7, 2024 License: AGPL-3.0 Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CacheClanLeaderboard = &cobra.Command{
	Use:   "cache:leaderboard:clan",
	Short: "Caches the clan leaderboard",
	Run: func(cmd *cobra.Command, args []string) {
		batchSize := 1000
		offset := 0

		logrus.Info("Caching clan leaderboards...")

		for {
			var clans = make([]*db.Clan, 0)

			result := db.SQL.
				Preload("Stats").
				Limit(batchSize).
				Offset(offset).
				Order("id ASC").
				Find(&clans)

			if result.Error != nil {
				logrus.Error(result.Error)
				return
			}

			if len(clans) == 0 {
				break
			}

			for _, clan := range clans {
				if err := db.UpdateAllClanLeaderboards(clan); err != nil {
					logrus.Error(err)
					return
				}
			}

			offset += batchSize
		}

		logrus.Info("Complete!")
	},
}
View Source
var CacheClearCmd = &cobra.Command{
	Use:   "cache:clear",
	Short: "Clears the cache",
	Long:  `Clears the application cache.`,
	Run: func(cmd *cobra.Command, args []string) {
		keys, err := db.Redis.Keys(db.RedisCtx, "quaver:*").Result()

		if err != nil && err != redis.Nil {
			logrus.Println(err)
			return
		}

		if len(keys) > 0 {
			delCount, err := db.Redis.Del(db.RedisCtx, keys...).Result()

			if err != nil {
				logrus.Errorf("Failed to DELETE keys: %v", err)
				return
			}

			logrus.Printf("Deleted %d keys\n", delCount)
		}

		logrus.Println("Cache has been cleared.")
	},
}
View Source
var CacheLeaderboardCmd = &cobra.Command{
	Use:   "cache:leaderboard",
	Short: "Populates the leaderboards in cache",
	Run: func(cmd *cobra.Command, args []string) {
		if len(args) > 0 && strings.ToLower(args[0]) == "delete-all" {
			if err := deleteOldLeaderboards(); err != nil {
				logrus.Error(err)
				return
			}
		}

		logrus.Println("Populating leaderboards...")

		if err := populateLeaderboard(); err != nil {
			logrus.Error(err)
			return
		}

		logrus.Println("Leaderboards populated.")
	},
}
View Source
var CacheScoreboardClearCmd = &cobra.Command{
	Use:   "cache:scoreboards:clear",
	Short: "Clears the scoreboard cache",
	Long:  `Clears the scoreboard cache.`,
	Run: func(cmd *cobra.Command, args []string) {
		keys, err := db.Redis.Keys(db.RedisCtx, "quaver:scoreboard:*").Result()

		if err != nil && err != redis.Nil {
			logrus.Println(err)
			return
		}

		if len(keys) > 0 {
			delCount, err := db.Redis.Del(db.RedisCtx, keys...).Result()

			if err != nil {
				logrus.Errorf("Failed to DELETE keys: %v", err)
				return
			}

			logrus.Printf("Deleted %d keys\n", delCount)
		}

		logrus.Info("Scoreboard cache has been cleared.")
	},
}
View Source
var DatabaseBackupCmd = &cobra.Command{
	Use:   "backup:database",
	Short: "Backs up the database and uploads to azure",
	Run: func(cmd *cobra.Command, args []string) {
		sqlPath, _ := filepath.Abs(fmt.Sprintf("%v/backup.sql", files.GetBackupsDirectory()))
		zipPath, _ := filepath.Abs(fmt.Sprintf("%v/backup.sql.zip", files.GetBackupsDirectory()))

		if err := deletePreviousBackups(databaseBackupContainer, 28); err != nil {
			logrus.Error(err)
			_ = webhooks.SendBackupWebhook(false, err)
			return
		}

		blobs, err := azure.Client.ListBlobs(databaseBackupContainer)

		if err != nil {
			logrus.Error(err)
			_ = webhooks.SendBackupWebhook(false, err)
			return
		}

		azureFileName := "001.zip"

		if len(blobs) > 0 {
			fileNumber, err := strconv.Atoi(strings.Replace(blobs[len(blobs)-1], ".zip", "", -1))

			if err != nil {
				logrus.Error(err)
				_ = webhooks.SendBackupWebhook(false, err)
				return
			}

			azureFileName = fmt.Sprintf("%03d.zip", fileNumber+1)
		}

		if err := performDatabaseBackupBackup(sqlPath, zipPath, databaseBackupContainer, azureFileName); err != nil {
			_ = webhooks.SendBackupWebhook(false, err)
			return
		}

		_ = webhooks.SendBackupWebhook(true)
	},
}
View Source
var DatabaseBackupHourlyCmd = &cobra.Command{
	Use:   "backup:database:hourly",
	Short: "Backs up the database hourly and uploads to azure",
	Run: func(cmd *cobra.Command, args []string) {
		sqlPath, _ := filepath.Abs(fmt.Sprintf("%v/backup-hourly.sql", files.GetBackupsDirectory()))
		azureFileName := "backup-hourly.sql.zip"
		zipPath, _ := filepath.Abs(fmt.Sprintf("%v/%v", files.GetBackupsDirectory(), azureFileName))

		if err := performDatabaseBackupBackup(sqlPath, zipPath, databaseBackupHourlyContainer, azureFileName); err != nil {
			_ = webhooks.SendBackupWebhook(false, err)
			return
		}

		_ = webhooks.SendBackupWebhook(true)
	},
}
View Source
var ElasticIndexMapsets = &cobra.Command{
	Use:   "elastic:index:mapsets",
	Short: "Indexes all mapsets in Elastic Search",
	Run: func(cmd *cobra.Command, args []string) {
		if err := db.IndexAllElasticSearchMapsets(true); err != nil {
			logrus.Error(err)
			return
		}

		logrus.Info("Complete!")
	},
}
View Source
var PlayerDonatorCheckCmd = &cobra.Command{
	Use:   "player:donator:check",
	Short: "Checks if a player is a donator",
	Run: func(cmd *cobra.Command, args []string) {
		expiredUsers := map[int]*db.UserNotification{}

		removeExpiredDonator(expiredUsers)
		addDiscordPremiumDonator(expiredUsers)

		for _, notification := range expiredUsers {
			if err := notification.Insert(); err != nil {
				logrus.Error("Error inserting donator expired notification: ", err)
			}
		}
	},
}
View Source
var SupervisorActivityCmd = &cobra.Command{
	Use:   "supervisor:activity",
	Short: "Handles providing donator for supervisor activity",
	Run: func(cmd *cobra.Command, args []string) {
		supervisors, err := db.GetRankingSupervisors(true)

		if err != nil {
			logrus.Error("Error retrieving supervisors from DB: ", err)
			return
		}

		if len(supervisors) == 0 {
			return
		}

		timeStart := time.Now().AddDate(0, 0, -7).UnixMilli()
		timeEnd := time.Now().UnixMilli()

		var userActions = map[*db.User]int{}

		for _, supervisor := range supervisors {
			actions, err := db.GetUserRankingQueueComments(supervisor.Id, timeStart, timeEnd)

			if err != nil {
				logrus.Error("Error retrieving ranking queue comments: ", err)
				return
			}

			userActions[supervisor] = len(actions)

			if len(actions) < config.Instance.RankingQueue.WeeklyRequiredSupervisorActions {
				continue
			}

			var endTime int64

			if supervisor.DonatorEndTime == 0 {
				endTime = time.Now().AddDate(0, 0, 7).UnixMilli()
			} else {
				endTime = time.UnixMilli(supervisor.DonatorEndTime).AddDate(0, 0, 7).UnixMilli()
			}

			if err := supervisor.UpdateDonatorEndTime(endTime); err != nil {
				logrus.Error("Error updating supervisor donator end time: ", err)
				return
			}

			logrus.Infof("[Supervisor Activity] Gave 1 week donator to: %v (#%v)", supervisor.Username, supervisor.Id)

			if enums.HasUserGroup(supervisor.UserGroups, enums.UserGroupDonator) {
				continue
			}

			if err := supervisor.UpdateUserGroups(supervisor.UserGroups | enums.UserGroupDonator); err != nil {
				logrus.Error("Error updating supervisor donator usergroup: ", err)
				return
			}

			logrus.Infof("[Supervisor Activity] Gave dono group to: %v (#%v)", supervisor.Username, supervisor.Id)
		}

		_ = webhooks.SendSupervisorActivityWebhook(userActions, timeStart, timeEnd)
	},
}
View Source
var UserRankCmd = &cobra.Command{
	Use:   "stats:rank",
	Short: "Inserts the rank stats for all users ",
	Run: func(cmd *cobra.Command, args []string) {
		batchSize := 1000
		offset := 0

		for {
			var users = make([]*db.User, 0)

			result := db.SQL.
				Where("allowed = 1").
				Limit(batchSize).
				Offset(offset).
				Find(&users)

			if result.Error != nil {
				logrus.Println(result.Error)
			}

			if len(users) == 0 {
				break
			}

			for _, user := range users {
				for i := 1; i <= 2; i++ {
					key := fmt.Sprintf("quaver:leaderboard:%v", i)
					userStr := fmt.Sprintf("%v", user.Id)

					data, err := db.Redis.ZRevRankWithScore(db.RedisCtx, key, userStr).Result()

					if err != nil {
						logrus.Error(err)
						return
					}

					switch enums.GameMode(i) {
					case enums.GameModeKeys4:
						rank := &db.UserRankKeys4{
							UserId:                   user.Id,
							Rank:                     int(data.Rank + 1),
							OverallPerformanceRating: data.Score,
							Timestamp:                time.Now(),
						}

						if err := db.SQL.Create(&rank).Error; err != nil {
							logrus.Error(err)
							return
						}

					case enums.GameModeKeys7:
						rank := &db.UserRankKeys7{
							UserId:                   user.Id,
							Rank:                     int(data.Rank + 1),
							OverallPerformanceRating: data.Score,
							Timestamp:                time.Now(),
						}

						if err := db.SQL.Create(&rank).Error; err != nil {
							logrus.Error(err)
							return
						}
					}

					logrus.Info("Inserted rank for user: ", user.Id)
				}
			}

			offset += batchSize
		}

		for i := 1; i <= 2; i++ {
			table := fmt.Sprintf("user_rank_%v", enums.GetGameModeString(enums.GameMode(i)))
			query := fmt.Sprintf("DELETE FROM %v WHERE timestamp <= (CURDATE() - INTERVAL 90 DAY)", table)

			result := db.SQL.Exec(query)

			if result.Error != nil {
				logrus.Error(result.Error)
				return
			}
		}

		logrus.Info("Complete!")
	},
}
View Source
var WeeklyMostPlayedMapsetsCmd = &cobra.Command{
	Use:   "mapsets:weekly:cache",
	Short: "Caches the most played mapsets of the week in redis",
	Run: func(cmd *cobra.Command, args []string) {
		mapsets, err := db.GetWeeklyMostPlayedMapsets(true)

		if err != nil {
			logrus.Error("Error caching weekly most played mapsets", err)
		}

		logrus.Infof("Successfully cached: %v weekly most played mapsets", len(mapsets))
	},
}

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL