Compare commits
No commits in common. 'main' and '1.1.0' have entirely different histories.
19 changed files with 333 additions and 855 deletions
@ -0,0 +1,330 @@
|
||||
package main |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"image" |
||||
"image/color" |
||||
"image/png" |
||||
"io" |
||||
"log" |
||||
"os" |
||||
"path/filepath" |
||||
"strings" |
||||
"sync" |
||||
"time" |
||||
) |
||||
|
||||
var ( |
||||
// used as a flag if the program executed for "the first time"
|
||||
settingsFileExisted bool = false |
||||
WG sync.WaitGroup |
||||
) |
||||
|
||||
const ( |
||||
settingsFilename string = "settings.json" |
||||
) |
||||
|
||||
// struct for json settings` file contents
|
||||
type Settings struct { |
||||
OsuDir string `json:"pathToOsu"` |
||||
ReplacementImagePath string `json:"pathToimage"` |
||||
CreateBlackBGImage bool `json:"createBlackBackgoundImage"` |
||||
MaxWorkers uint `json:"maxConcurrentWorkers"` |
||||
} |
||||
|
||||
// creates directory for logs and sets output to file
|
||||
func setUpLogs() { |
||||
logsDir := filepath.Join(".", "logs") |
||||
err := os.MkdirAll(logsDir, os.ModePerm) |
||||
if err != nil { |
||||
panic(err) |
||||
} |
||||
file, err := os.Create(filepath.Join(logsDir, "logs.log")) |
||||
log.SetOutput(file) |
||||
} |
||||
|
||||
// creates "settings.json" and sets the flag
|
||||
func createSettingsFile() { |
||||
files, err := os.ReadDir(".") |
||||
if err != nil { |
||||
log.Fatal("ERROR : Unable to read current directory") |
||||
} |
||||
for _, file := range files { |
||||
if file.IsDir() == false { |
||||
if file.Name() == settingsFilename { |
||||
log.Println("Found settings file") |
||||
settingsFileExisted = true |
||||
return |
||||
} |
||||
} |
||||
} |
||||
file, err := os.Create("settings.json") |
||||
if err != nil { |
||||
log.Fatal("ERROR: Error creating settings file... : ", err) |
||||
} |
||||
settings := Settings{ |
||||
OsuDir: "", |
||||
ReplacementImagePath: "", |
||||
CreateBlackBGImage: true, |
||||
MaxWorkers: 50, |
||||
} |
||||
jsonEncodedSettings, err := json.MarshalIndent(settings, "", " ") |
||||
if err != nil { |
||||
log.Println("ERROR: Error creating settings file... : ", err) |
||||
} |
||||
file.Write(jsonEncodedSettings) |
||||
|
||||
file.Close() |
||||
log.Println("Successfully created new settingsFile") |
||||
} |
||||
|
||||
// filepath.Joins the main osu directory with its songs folder
|
||||
func getSongsDir(osudir string) string { |
||||
songsDir := filepath.Join(osudir, "Songs") |
||||
|
||||
stat, err := os.Stat(songsDir) |
||||
if err != nil { |
||||
log.Fatal("ERROR: Error reading path : ", err) |
||||
} |
||||
if !stat.IsDir() { |
||||
log.Fatal("ERROR: Given osu! directory is not a directory") |
||||
} |
||||
|
||||
return songsDir |
||||
} |
||||
|
||||
// unmarshalls settings.json into struct
|
||||
func getSettings() Settings { |
||||
settingsFile, err := os.ReadFile(settingsFilename) |
||||
if err != nil { |
||||
log.Fatal("ERROR: Could not read settings file : ", err) |
||||
} |
||||
var settings Settings |
||||
err = json.Unmarshal(settingsFile, &settings) |
||||
if err != nil { |
||||
log.Fatal("ERROR: Error unmarshalling json file : ", err) |
||||
} |
||||
if settings.MaxWorkers <= 0 { |
||||
log.Println("`maxConcurrentWorkers` is set to 0 or less. Replaced with 1") |
||||
settings.MaxWorkers = 1 |
||||
} |
||||
return settings |
||||
} |
||||
|
||||
// checks if given string contains ".osu"
|
||||
func isBeatmap(filename string) bool { |
||||
if len(filename) < 5 { |
||||
return false |
||||
} |
||||
if filename[len(filename)-4:] == ".osu" { |
||||
return true |
||||
} |
||||
return false |
||||
} |
||||
|
||||
func isImage(filename string) bool { |
||||
var imageExtentions []string = []string{"jpeg", "jpg", "png", "JPEG", "JPG", "PNG"} |
||||
for _, extention := range imageExtentions { |
||||
if strings.Contains(filename, extention) { |
||||
return true |
||||
} |
||||
} |
||||
return false |
||||
} |
||||
|
||||
// parses .osu file and returns the filename of its background
|
||||
func getBackgroundName(pathToOSUbeatmap string) (string, error) { |
||||
beatmapBytes, err := os.ReadFile(pathToOSUbeatmap) |
||||
if err != nil { |
||||
return "", err |
||||
} |
||||
beatmapContents := string(beatmapBytes) |
||||
|
||||
eventsIndex := strings.Index(beatmapContents, "[Events]") |
||||
if eventsIndex == -1 { |
||||
return "", nil |
||||
} |
||||
breakPeriodsIndex := strings.Index(beatmapContents, "//Break Periods") |
||||
if eventsIndex == -1 { |
||||
return "", nil |
||||
} |
||||
contentBetween := strings.Split(beatmapContents[eventsIndex:breakPeriodsIndex], ",") |
||||
|
||||
for _, chunk := range contentBetween { |
||||
if isImage(chunk) { |
||||
return strings.Split(chunk, "\"")[1], nil |
||||
} |
||||
} |
||||
return "", nil |
||||
} |
||||
|
||||
// opens given files, copies one into another
|
||||
func copyFile(src, dst string) error { |
||||
srcFile, err := os.Open(src) |
||||
if err != nil { |
||||
log.Println("ERROR: ", err) |
||||
return err |
||||
} |
||||
defer srcFile.Close() |
||||
|
||||
dstFile, err := os.OpenFile(dst, os.O_WRONLY, os.ModePerm) |
||||
if err != nil { |
||||
log.Println("ERROR: ", err) |
||||
return err |
||||
} |
||||
defer dstFile.Close() |
||||
|
||||
_, err = io.Copy(dstFile, srcFile) |
||||
if err != nil { |
||||
log.Println("ERROR: Error copying files : ", err) |
||||
return err |
||||
} |
||||
return nil |
||||
} |
||||
|
||||
// reads contents of given dir; searches for .osu files; parses them for background info;
|
||||
// removes original background and replaces it with copied version of given image
|
||||
func replaceBackgrounds(beatmapFolder, replacementPicPath string) (successful, failed uint64) { |
||||
files, err := os.ReadDir(beatmapFolder) |
||||
if err != nil { |
||||
log.Fatal("ERROR: Wrong path : ", err) |
||||
} |
||||
for _, file := range files { |
||||
filename := file.Name() |
||||
|
||||
if isBeatmap(filename) { |
||||
|
||||
beatmapBackgroundFilename, err := getBackgroundName(filepath.Join(beatmapFolder, filename)) |
||||
if err != nil { |
||||
failed++ |
||||
continue |
||||
} |
||||
if beatmapBackgroundFilename == "" { |
||||
log.Println("BEATMAP: ", filename, " Could not find beatmap name") |
||||
failed++ |
||||
continue |
||||
} |
||||
|
||||
backgroundPath := filepath.Join(beatmapFolder, beatmapBackgroundFilename) |
||||
log.Println("BEATMAP: ", filename, " found background") |
||||
|
||||
// remove old background
|
||||
err = os.Remove(backgroundPath) |
||||
if err != nil { |
||||
failed++ |
||||
log.Println("ERROR: Error removing old background : ", err, " file: ", backgroundPath) |
||||
} |
||||
|
||||
// create new background file
|
||||
bgFile, err := os.Create(backgroundPath) |
||||
if err != nil { |
||||
failed++ |
||||
log.Println("ERROR: Error creating new background file : ", err) |
||||
continue |
||||
} |
||||
defer bgFile.Close() |
||||
|
||||
// copy the contents of a given image to the newly created bg file
|
||||
err = copyFile(replacementPicPath, backgroundPath) |
||||
if err != nil { |
||||
failed++ |
||||
} |
||||
successful++ |
||||
} |
||||
|
||||
} |
||||
return successful, failed |
||||
} |
||||
|
||||
// creates a complete black image file
|
||||
func createBlackBG(width, height int) { |
||||
bg, err := os.Create("blackBG.png") |
||||
if err != nil { |
||||
log.Println("ERROR: Error creating black background : ", err, "Continuing to run...") |
||||
} |
||||
image := image.NewRGBA(image.Rect(0, 0, width, height)) |
||||
bounds := image.Bounds() |
||||
|
||||
for y := 0; y < bounds.Max.Y; y++ { |
||||
for x := 0; x < bounds.Max.X; x++ { |
||||
image.Set(x, y, color.Black) |
||||
} |
||||
} |
||||
png.Encode(bg, image) |
||||
bg.Close() |
||||
|
||||
log.Println("Successfully created black background") |
||||
} |
||||
|
||||
// a basic implementation of a concurrent worker
|
||||
func worker(paths <-chan string, replacementImage string, successful, failed *uint64, WG *sync.WaitGroup) { |
||||
defer WG.Done() |
||||
for songPath := range paths { |
||||
s, f := replaceBackgrounds(songPath, replacementImage) |
||||
*successful += s |
||||
*failed += f |
||||
} |
||||
|
||||
} |
||||
|
||||
func init() { |
||||
setUpLogs() |
||||
createSettingsFile() |
||||
} |
||||
|
||||
func main() { |
||||
// settings file didn`t exist, created now
|
||||
if !settingsFileExisted { |
||||
return |
||||
} |
||||
startingTime := time.Now().UTC() |
||||
|
||||
settings := getSettings() |
||||
|
||||
// process the given settings
|
||||
if settings.CreateBlackBGImage == true { |
||||
createBlackBG(1920, 1080) |
||||
} |
||||
|
||||
osuSongsDir := getSongsDir(settings.OsuDir) |
||||
|
||||
replacementImage := settings.ReplacementImagePath |
||||
if replacementImage == "" || replacementImage == " " { |
||||
log.Fatal("Image path not specified ! Specify `pathToimage` in settings file !") |
||||
} |
||||
|
||||
// reading contents of `Songs` folder
|
||||
osuSongsDirContents, err := os.ReadDir(osuSongsDir) |
||||
if err != nil { |
||||
log.Fatal("ERROR: Error reading osu songs directory : ", err) |
||||
} |
||||
|
||||
// storing all paths to each beatmap
|
||||
songPaths := make(chan string, len(osuSongsDirContents)) |
||||
for _, songDir := range osuSongsDirContents { |
||||
if songDir.IsDir() { |
||||
songPaths <- filepath.Join(osuSongsDir, songDir.Name()) |
||||
} |
||||
} |
||||
log.Printf("Found %d song folders", len(songPaths)) |
||||
|
||||
// check if there is less job than workers
|
||||
if int(settings.MaxWorkers) > len(songPaths) { |
||||
settings.MaxWorkers = uint(len(songPaths)) |
||||
} |
||||
|
||||
// replacing backgrounds for each beatmap concurrently
|
||||
var successful, failed uint64 = 0, 0 |
||||
for i := 0; i < int(settings.MaxWorkers); i++ { |
||||
WG.Add(1) |
||||
go worker(songPaths, replacementImage, &successful, &failed, &WG) |
||||
} |
||||
|
||||
close(songPaths) |
||||
WG.Wait() |
||||
|
||||
endTime := time.Now().UTC() |
||||
|
||||
log.Printf("\n\nDONE in %v . %d successful; %d failed", endTime.Sub(startingTime), successful, failed) |
||||
|
||||
} |
@ -1,180 +0,0 @@
|
||||
package main |
||||
|
||||
import ( |
||||
"flag" |
||||
"fmt" |
||||
"os" |
||||
"sync" |
||||
"time" |
||||
|
||||
"unbewohnte/OBM/logger" |
||||
"unbewohnte/OBM/manager" |
||||
"unbewohnte/OBM/settings" |
||||
"unbewohnte/OBM/util" |
||||
) |
||||
|
||||
const orderMessage string = "Order: Replace -> Retrieve -> Remove\n" |
||||
|
||||
var ( |
||||
cmdlnBeatmap = flag.String("beatmap", "", `Specifies a certain beatmap. |
||||
If set to non "" - the program will search for given name and perform the magic |
||||
provided in settings if successful`) |
||||
showOrder = flag.Bool("showOrder", false, "Prints an order in which functions are performed on a beatmap") |
||||
) |
||||
|
||||
// a basic implementation of a concurrent worker
|
||||
func worker(jobs <-chan job, results chan result, WG *sync.WaitGroup) { |
||||
defer WG.Done() |
||||
for job := range jobs { |
||||
var successful, failed uint = 0, 0 |
||||
|
||||
// the order is: Replace->Retrieve->Remove (if all 3 options are enabled)
|
||||
if job.replacementImagePath != "" { |
||||
s, f := job.beatmap.ReplaceBackgrounds(job.replacementImagePath) |
||||
successful += s |
||||
failed += f |
||||
} |
||||
if job.retrievementPath != "" { |
||||
s, f := job.beatmap.RetrieveBackgrounds(job.retrievementPath) |
||||
successful += s |
||||
failed += f |
||||
} |
||||
if job.remove == true { |
||||
s, f := job.beatmap.RemoveBackgrounds() |
||||
successful += s |
||||
failed += f |
||||
} |
||||
|
||||
results <- result{ |
||||
beatmapName: job.beatmap.Name, |
||||
numberOfDiffs: uint(len(job.beatmap.Diffs)), |
||||
successful: successful, |
||||
failed: failed, |
||||
} |
||||
} |
||||
|
||||
} |
||||
|
||||
// the `starter` that `glues` workers and jobs together
|
||||
func workerPool(jobs chan job, results chan result, numOfWorkers int, WG *sync.WaitGroup) { |
||||
// check if there are less jobs than workers
|
||||
if numOfWorkers > len(jobs) { |
||||
numOfWorkers = len(jobs) |
||||
} |
||||
|
||||
// replacing backgrounds for each beatmap concurrently
|
||||
for i := 0; i < numOfWorkers; i++ { |
||||
WG.Add(1) |
||||
go worker(jobs, results, WG) |
||||
} |
||||
} |
||||
|
||||
type result struct { |
||||
beatmapName string |
||||
numberOfDiffs uint |
||||
successful uint |
||||
failed uint |
||||
} |
||||
|
||||
type job struct { |
||||
beatmap manager.Beatmap |
||||
replacementImagePath string |
||||
retrievementPath string |
||||
remove bool |
||||
} |
||||
|
||||
func init() { |
||||
exists, err := settings.DoesExist() |
||||
if err != nil { |
||||
logger.LogError(true, err) |
||||
} |
||||
if !exists { |
||||
// settings file does not exist, so create it and exit (assuming that this is the first run)
|
||||
settings.Create() |
||||
logger.LogInfo("Successfully created new settings file") |
||||
os.Exit(0) |
||||
} |
||||
logger.LogInfo("Found settings file") |
||||
|
||||
// parse for `-beatmap` argument
|
||||
flag.Parse() |
||||
|
||||
// if `-showOrder` is checked - show the message and exit
|
||||
if *showOrder == true { |
||||
fmt.Print(orderMessage) |
||||
os.Exit(0) |
||||
} |
||||
return |
||||
} |
||||
|
||||
func main() { |
||||
var WG sync.WaitGroup |
||||
|
||||
startingTime := time.Now() |
||||
|
||||
SETTINGS := settings.Get() |
||||
|
||||
// creating black image if enabled
|
||||
if SETTINGS.CreateBlackBGImage.Enabled { |
||||
err := util.CreateBlackBG(SETTINGS.CreateBlackBGImage.Width, SETTINGS.CreateBlackBGImage.Height) |
||||
if err == nil { |
||||
logger.LogInfo("Successfully created black background") |
||||
} else { |
||||
logger.LogWarning(fmt.Sprintf("Could not create black background : %s; continuing to run...", err)) |
||||
} |
||||
} |
||||
|
||||
// get an array of all beatmaps
|
||||
beatmaps, err := manager.GetBeatmaps(SETTINGS.OsuDir) |
||||
if err != nil { |
||||
logger.LogError(true, "Error getting beatmaps: ", err) |
||||
} |
||||
logger.LogInfo(fmt.Sprintf("Found %d beatmaps", len(beatmaps))) |
||||
|
||||
// If `-beatmap` flag is specified - do the magic only on found beatmaps
|
||||
if *cmdlnBeatmap != "" { |
||||
logger.LogInfo(fmt.Sprintf("Trying to locate \"%s\"...", *cmdlnBeatmap)) |
||||
found, n := manager.Search(beatmaps, *cmdlnBeatmap) |
||||
logger.LogInfo(fmt.Sprintf("Checked %d beatmaps. Found %d instance(s)", n, len(found))) |
||||
|
||||
// if found nothing - exit
|
||||
if len(found) == 0 { |
||||
os.Exit(0) |
||||
} |
||||
// replace all beatmaps with found ones
|
||||
beatmaps = found |
||||
} |
||||
|
||||
// creating jobs for workers
|
||||
jobs := make(chan job, len(beatmaps)) |
||||
for _, beatmap := range beatmaps { |
||||
jobs <- job{ |
||||
beatmap: beatmap, |
||||
replacementImagePath: SETTINGS.BackgroundReplacement.ReplacementImagePath, |
||||
retrievementPath: SETTINGS.BackgroundRetrievement.RetrievementPath, |
||||
remove: SETTINGS.BackgroundRemovement.Enabled, |
||||
} |
||||
} |
||||
close(jobs) |
||||
|
||||
// perform the magic
|
||||
results := make(chan result, len(jobs)) |
||||
workerPool(jobs, results, SETTINGS.Workers, &WG) |
||||
WG.Wait() |
||||
close(results) |
||||
|
||||
// extracting results and logging the last message
|
||||
var successful, failed uint = 0, 0 |
||||
for result := range results { |
||||
successful += result.successful |
||||
failed += result.failed |
||||
|
||||
logger.LogInfo(fmt.Sprintf("Beatmap: %s; Number of diffs: %d;\n Successful: %d; Failed: %d", |
||||
result.beatmapName, result.numberOfDiffs, result.successful, result.failed)) |
||||
} |
||||
total := successful + failed |
||||
|
||||
logger.LogInfo(fmt.Sprintf("DONE in %v. %d operations successful (%.2f%%/100%%); %d failed (%.2f%%/100%%)", |
||||
time.Since(startingTime), successful, float32(successful)/float32(total)*100, failed, float32(failed)/float32(total)*100)) |
||||
|
||||
} |
@ -1,53 +0,0 @@
|
||||
package logger |
||||
|
||||
import ( |
||||
"log" |
||||
"os" |
||||
"path/filepath" |
||||
) |
||||
|
||||
var ( |
||||
infoLogger *log.Logger |
||||
warningLogger *log.Logger |
||||
errorLogger *log.Logger |
||||
) |
||||
|
||||
// creates directory for logs and sets output to file
|
||||
func createLogsfile() *os.File { |
||||
logsDir := filepath.Join(".", "logs") |
||||
err := os.MkdirAll(logsDir, os.ModePerm) |
||||
if err != nil { |
||||
panic(err) |
||||
} |
||||
logfile, err := os.Create(filepath.Join(logsDir, "logs.log")) |
||||
log.SetOutput(logfile) |
||||
|
||||
return logfile |
||||
} |
||||
|
||||
// creates new custom loggers
|
||||
func setUpLoggers(logfile *os.File) { |
||||
infoLogger = log.New(logfile, "INFO: ", log.Ldate|log.Ltime) |
||||
warningLogger = log.New(logfile, "WARNING: ", log.Ldate|log.Ltime) |
||||
errorLogger = log.New(logfile, "ERROR: ", log.Ldate|log.Ltime) |
||||
} |
||||
|
||||
func init() { |
||||
logfile := createLogsfile() |
||||
setUpLoggers(logfile) |
||||
} |
||||
|
||||
func LogInfo(message ...interface{}) { |
||||
infoLogger.Println(message...) |
||||
} |
||||
|
||||
func LogWarning(message ...interface{}) { |
||||
warningLogger.Println(message...) |
||||
} |
||||
|
||||
func LogError(isFatal bool, message ...interface{}) { |
||||
if isFatal { |
||||
errorLogger.Fatal(message...) |
||||
} |
||||
errorLogger.Println(message...) |
||||
} |
@ -1,88 +0,0 @@
|
||||
package manager |
||||
|
||||
import ( |
||||
"fmt" |
||||
"os" |
||||
"path/filepath" |
||||
|
||||
"unbewohnte/OBM/util" |
||||
) |
||||
|
||||
// the main beatmap struct, contains necessary data for functions
|
||||
type Beatmap struct { |
||||
Name string |
||||
Path string |
||||
Diffs []string |
||||
} |
||||
|
||||
// filepath.Joins the main osu directory with its songs folder
|
||||
func getSongsDir(baseOsuDir string) (string, error) { |
||||
songsDir := filepath.Join(baseOsuDir, "Songs") |
||||
|
||||
stat, err := os.Stat(songsDir) |
||||
if err != nil { |
||||
return "", fmt.Errorf("could not process the given path : %s", err) |
||||
} |
||||
if !stat.IsDir() { |
||||
return "", fmt.Errorf("given Osu! directory is not a directory") |
||||
} |
||||
|
||||
return songsDir, nil |
||||
} |
||||
|
||||
// checks for .osu files in given path and returns all found instances
|
||||
func getDiffs(path string) ([]string, error) { |
||||
files, err := os.ReadDir(path) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("could not read a directory : %s", err) |
||||
} |
||||
|
||||
var diffs []string |
||||
for _, file := range files { |
||||
filename := file.Name() |
||||
if util.IsBeatmap(filename) { |
||||
diffs = append(diffs, filename) |
||||
} |
||||
} |
||||
return diffs, nil |
||||
} |
||||
|
||||
// constructs a `Beatmap` struct and returns it
|
||||
func newBeatmap(name, path string, diffs []string) Beatmap { |
||||
return Beatmap{ |
||||
Name: name, |
||||
Path: path, |
||||
Diffs: diffs, |
||||
} |
||||
} |
||||
|
||||
// returns an array of beatmaps from given base Osu! directory
|
||||
func GetBeatmaps(baseOsuDir string) ([]Beatmap, error) { |
||||
songsDir, err := getSongsDir(baseOsuDir) |
||||
if err != nil { |
||||
return nil, err |
||||
} |
||||
contents, err := os.ReadDir(songsDir) |
||||
if err != nil { |
||||
return nil, fmt.Errorf("could not read a directory : %s", err) |
||||
} |
||||
|
||||
var beatmaps []Beatmap |
||||
// looping through all folders in yourOsuDir/Songs/ directory
|
||||
for _, file := range contents { |
||||
if file.IsDir() { |
||||
// retrieving all necessary data for creating a new instance of a beatmap
|
||||
beatmapName := file.Name() |
||||
pathToBeatmap := filepath.Join(songsDir, beatmapName) |
||||
diffs, err := getDiffs(pathToBeatmap) |
||||
if err != nil { |
||||
continue |
||||
} |
||||
newBeatmap := newBeatmap(beatmapName, pathToBeatmap, diffs) |
||||
|
||||
beatmaps = append(beatmaps, newBeatmap) |
||||
} |
||||
} |
||||
|
||||
return beatmaps, nil |
||||
} |
@ -1,43 +0,0 @@
|
||||
package manager |
||||
|
||||
import ( |
||||
"fmt" |
||||
"os" |
||||
"path/filepath" |
||||
"strings" |
||||
|
||||
"unbewohnte/OBM/util" |
||||
) |
||||
|
||||
// parses given .osu file and returns the filename of its background
|
||||
// NOTE: Osu! beatmap (as whole) can have multiple backgrounds for each .osu file
|
||||
// the perfect example : https://osu.ppy.sh/beatmapsets/43701#osu/137122
|
||||
// this is why this function asks for a certain difficulty (.osu filename) to be sure
|
||||
// to return the correct background name
|
||||
func (BEATMAP *Beatmap) GetBackgroundName(diff string) (string, error) { |
||||
beatmapBytes, err := os.ReadFile(filepath.Join(BEATMAP.Path, diff)) |
||||
if err != nil { |
||||
return "", err |
||||
} |
||||
beatmapContents := string(beatmapBytes) |
||||
|
||||
// get index of "[Events]" (this is where BG filename is stored)
|
||||
eventsIndex := strings.Index(beatmapContents, "[Events]") |
||||
if eventsIndex == -1 { |
||||
return "", fmt.Errorf("could not retrieve index of \"[Events]\"") |
||||
} |
||||
// get index of [TimingPoints] (this tag is right after the previous "[Events]" tag,
|
||||
// so we can grab the whole "[Events]" tag contents)
|
||||
timingPointsIndex := strings.Index(beatmapContents, "[TimingPoints]") |
||||
if timingPointsIndex == -1 { |
||||
return "", fmt.Errorf("could not retrieve index of \"[TimingPoints]\"") |
||||
} |
||||
contentBetween := strings.Split(beatmapContents[eventsIndex:timingPointsIndex], ",") |
||||
|
||||
for _, chunk := range contentBetween { |
||||
if util.IsImage(chunk) { |
||||
return strings.Split(chunk, "\"")[1], nil |
||||
} |
||||
} |
||||
return "", nil |
||||
} |
@ -1,31 +0,0 @@
|
||||
package manager |
||||
|
||||
import ( |
||||
"fmt" |
||||
"os" |
||||
"path/filepath" |
||||
|
||||
"unbewohnte/OBM/logger" |
||||
) |
||||
|
||||
// parses each difficulty for background info, removes found backgrounds
|
||||
func (BEATMAP *Beatmap) RemoveBackgrounds() (successful, failed uint) { |
||||
// looping through each .osu file of a beatmap
|
||||
for _, diff := range BEATMAP.Diffs { |
||||
background, err := BEATMAP.GetBackgroundName(diff) |
||||
if err != nil || background == "" { |
||||
logger.LogError(false, fmt.Sprintf("BEATMAP: %s: Error getting background filename: %s", diff, err)) |
||||
failed++ |
||||
continue |
||||
} |
||||
// remove background
|
||||
err = os.Remove(filepath.Join(BEATMAP.Path, background)) |
||||
if err != nil { |
||||
// background file does not exist (success ???)
|
||||
successful++ |
||||
continue |
||||
} |
||||
successful++ |
||||
} |
||||
return successful, failed |
||||
} |
@ -1,36 +0,0 @@
|
||||
package manager |
||||
|
||||
import ( |
||||
"fmt" |
||||
"os" |
||||
"path/filepath" |
||||
|
||||
"unbewohnte/OBM/logger" |
||||
"unbewohnte/OBM/util" |
||||
) |
||||
|
||||
// parses each beatmap`s .osu file for background info;
|
||||
// removes original background and replaces it with copied version of given image
|
||||
func (BEATMAP *Beatmap) ReplaceBackgrounds(replacementImgPath string) (successful, failed uint) { |
||||
// looping through each .osu file of a beatmap
|
||||
for _, diff := range BEATMAP.Diffs { |
||||
background, err := BEATMAP.GetBackgroundName(diff) |
||||
if err != nil || background == "" { |
||||
logger.LogError(false, fmt.Sprintf("BEATMAP: %s: Error getting background filename: %s", diff, err)) |
||||
failed++ |
||||
continue |
||||
} |
||||
// remove old bg (if there is no background file - no need to worry)
|
||||
os.Remove(filepath.Join(BEATMAP.Path, background)) |
||||
|
||||
// copy given picture, thus replacing background
|
||||
err = util.CopyFile(replacementImgPath, filepath.Join(BEATMAP.Path, background)) |
||||
if err != nil { |
||||
logger.LogError(false, fmt.Sprintf("BEATMAP: %s: Could not copy: %s", diff, err)) |
||||
failed++ |
||||
continue |
||||
} |
||||
successful++ |
||||
} |
||||
return successful, failed |
||||
} |
@ -1,52 +0,0 @@
|
||||
package manager |
||||
|
||||
import ( |
||||
"fmt" |
||||
"os" |
||||
"path/filepath" |
||||
|
||||
"unbewohnte/OBM/logger" |
||||
"unbewohnte/OBM/util" |
||||
) |
||||
|
||||
// retrieves backgrounds from given beatmap folder (same as in `ReplaceBackgrounds`) and copies them to the retrievement path
|
||||
func (BEATMAP *Beatmap) RetrieveBackgrounds(retrievementPath string) (successful, failed uint) { |
||||
// looping through each .osu file of a beatmap
|
||||
for _, diff := range BEATMAP.Diffs { |
||||
background, err := BEATMAP.GetBackgroundName(diff) |
||||
if err != nil || background == "" { |
||||
logger.LogError(false, fmt.Sprintf("BEATMAP: %s: Error getting background filename: %s", diff, err)) |
||||
failed++ |
||||
continue |
||||
} |
||||
|
||||
// check if the background does exist
|
||||
exists := util.DoesExist(filepath.Join(BEATMAP.Path, background)) |
||||
if !exists { |
||||
// if not - we cannot copy it, so moving to the next diff
|
||||
logger.LogWarning(fmt.Sprintf("BEATMAP: %s: Background does not exist", diff)) |
||||
failed++ |
||||
continue |
||||
} |
||||
|
||||
// creating directory that represents current beatmap
|
||||
dstPath := filepath.Join(retrievementPath, BEATMAP.Name) |
||||
|
||||
err = os.MkdirAll(dstPath, os.ModePerm) |
||||
if err != nil { |
||||
logger.LogError(false, fmt.Sprintf("BEATMAP: %s: Error creating a directory: %s", diff, err)) |
||||
failed++ |
||||
continue |
||||
} |
||||
|
||||
// copy background to the `retrievementPath`
|
||||
err = util.CopyFile(filepath.Join(BEATMAP.Path, background), filepath.Join(dstPath, background)) |
||||
if err != nil { |
||||
logger.LogError(false, fmt.Sprintf("BEATMAP: %s: Could not copy: %s", diff, err)) |
||||
failed++ |
||||
continue |
||||
} |
||||
successful++ |
||||
} |
||||
return successful, failed |
||||
} |
@ -1,20 +0,0 @@
|
||||
package manager |
||||
|
||||
import "strings" |
||||
|
||||
// Search tries to locate instances of beatmaps with the provided name (or part of the name);
|
||||
// returns a slice of found beatmaps and a number of searched beatmaps
|
||||
func Search(beatmaps []Beatmap, name string) ([]Beatmap, uint64) { |
||||
var instances []Beatmap |
||||
var searched uint64 = 0 |
||||
|
||||
// to make the search case-insensitive
|
||||
name = strings.ToLower(name) |
||||
for _, beatmap := range beatmaps { |
||||
if strings.Contains(strings.ToLower(beatmap.Name), name) { |
||||
instances = append(instances, beatmap) |
||||
} |
||||
searched++ |
||||
} |
||||
return instances, searched |
||||
} |
@ -1,123 +0,0 @@
|
||||
package settings |
||||
|
||||
import ( |
||||
"encoding/json" |
||||
"fmt" |
||||
"os" |
||||
|
||||
"unbewohnte/OBM/logger" |
||||
"unbewohnte/OBM/util" |
||||
) |
||||
|
||||
const ( |
||||
settingsFilename string = "settings.json" |
||||
) |
||||
|
||||
// checks if the settings.json exists in current directory
|
||||
func DoesExist() (bool, error) { |
||||
files, err := os.ReadDir(".") |
||||
if err != nil { |
||||
return false, fmt.Errorf("wasn`t able to read current directory %s", err) |
||||
} |
||||
|
||||
for _, file := range files { |
||||
if !file.IsDir() && file.Name() == settingsFilename { |
||||
return true, nil |
||||
} |
||||
} |
||||
|
||||
return false, nil |
||||
} |
||||
|
||||
// creates "settings.json" in current directory
|
||||
func Create() error { |
||||
exists, err := DoesExist() |
||||
if err != nil { |
||||
return err |
||||
} |
||||
if exists { |
||||
return nil |
||||
} |
||||
|
||||
file, err := os.Create(settingsFilename) |
||||
if err != nil { |
||||
return fmt.Errorf("could not create settings file : %s", err) |
||||
} |
||||
defer file.Close() |
||||
|
||||
// marshaling default settings
|
||||
settingsJson, err := json.MarshalIndent(Settings{ |
||||
OsuDir: "", |
||||
BackgroundReplacement: backgroundReplacement{ |
||||
Enabled: true, |
||||
ReplacementImagePath: "", |
||||
}, |
||||
BackgroundRetrievement: backgroundRetrievement{ |
||||
Enabled: false, |
||||
RetrievementPath: "", |
||||
}, |
||||
BackgroundRemovement: backgroundRemovement{ |
||||
Enabled: false, |
||||
}, |
||||
CreateBlackBGImage: backgroundCreatement{ |
||||
Enabled: true, |
||||
Width: 1920, |
||||
Height: 1080, |
||||
}, |
||||
Workers: 100, |
||||
}, "", " ") |
||||
if err != nil { |
||||
return fmt.Errorf("could not marshal settings into file : %s", err) |
||||
} |
||||
|
||||
file.Write(settingsJson) |
||||
|
||||
return nil |
||||
} |
||||
|
||||
// unmarshalls settings.json into struct and processes the edge-cases
|
||||
func Get() Settings { |
||||
settingsFileContents, err := os.ReadFile(settingsFilename) |
||||
if err != nil { |
||||
logger.LogError(true, fmt.Sprintf("Could not read settings file : %s", err)) |
||||
} |
||||
|
||||
var settings Settings |
||||
err = json.Unmarshal(settingsFileContents, &settings) |
||||
if err != nil { |
||||
logger.LogError(true, fmt.Sprintf("Could not unmarshal json file : %s", err)) |
||||
} |
||||
|
||||
// if all features are disabled
|
||||
if !settings.BackgroundReplacement.Enabled && !settings.BackgroundRetrievement.Enabled && !settings.BackgroundRemovement.Enabled { |
||||
logger.LogInfo("No features enabled. Exiting...") |
||||
os.Exit(0) |
||||
} |
||||
|
||||
// checking for edge cases or mistakes made in the settings file,
|
||||
// enabled and disabled fields
|
||||
if settings.BackgroundReplacement.Enabled { |
||||
if settings.BackgroundReplacement.ReplacementImagePath == "" || settings.BackgroundReplacement.ReplacementImagePath == " " { |
||||
logger.LogError(true, "`replacementImagePath` is not specified !") |
||||
} else if !util.IsImage(settings.BackgroundReplacement.ReplacementImagePath) { |
||||
logger.LogError(true, "`replacementImagePath` is pointing to a non-image file !`") |
||||
} |
||||
} else { |
||||
settings.BackgroundReplacement.ReplacementImagePath = "" |
||||
} |
||||
|
||||
if settings.BackgroundRetrievement.Enabled { |
||||
if settings.BackgroundRetrievement.RetrievementPath == "" || settings.BackgroundRetrievement.RetrievementPath == " " { |
||||
logger.LogError(true, "`retrievementPath` is not specified !") |
||||
} |
||||
} else { |
||||
settings.BackgroundRetrievement.RetrievementPath = "" |
||||
} |
||||
|
||||
if settings.Workers <= 0 { |
||||
settings.Workers = 1 |
||||
logger.LogWarning("`workers` is set to 0 or less. Replaced with 1") |
||||
} |
||||
|
||||
return settings |
||||
} |
@ -1,35 +0,0 @@
|
||||
package settings |
||||
|
||||
// the idea behind `Enabled` field is that if it`s not true - then
|
||||
// we treat the path below as "" (blank string) , which workers will just ignore
|
||||
// (therefore will not perform the replacement or retrievement)
|
||||
|
||||
type backgroundReplacement struct { |
||||
Enabled bool `json:"enabled"` |
||||
ReplacementImagePath string `json:"pathToimage"` |
||||
} |
||||
|
||||
type backgroundRetrievement struct { |
||||
Enabled bool `json:"enabled"` |
||||
RetrievementPath string `json:"retrievementPath"` |
||||
} |
||||
|
||||
type backgroundRemovement struct { |
||||
Enabled bool `json:"enabled"` |
||||
} |
||||
|
||||
type backgroundCreatement struct { |
||||
Enabled bool `json:"enabled"` |
||||
Width uint `json:"width"` |
||||
Height uint `json:"height"` |
||||
} |
||||
|
||||
// struct for json settings` file contents
|
||||
type Settings struct { |
||||
OsuDir string `json:"pathToOsu"` |
||||
BackgroundReplacement backgroundReplacement `json:"backgroundReplacement"` |
||||
BackgroundRetrievement backgroundRetrievement `json:"backgroundRetrievement"` |
||||
BackgroundRemovement backgroundRemovement `json:"backgroundRemovement"` |
||||
CreateBlackBGImage backgroundCreatement `json:"blackBackgroundCreatement"` |
||||
Workers int `json:"workers"` |
||||
} |
@ -1,36 +0,0 @@
|
||||
package util |
||||
|
||||
import ( |
||||
"errors" |
||||
"fmt" |
||||
"image" |
||||
"image/color" |
||||
"image/png" |
||||
"os" |
||||
) |
||||
|
||||
// creates a complete black image file in current working directory
|
||||
func CreateBlackBG(width, height uint) error { |
||||
bgfile, err := os.Create("blackBG.png") |
||||
if err != nil { |
||||
return errors.New(fmt.Sprintf("Could not create black background file : %s", err)) |
||||
} |
||||
image := image.NewRGBA(image.Rect(0, 0, int(width), int(height))) |
||||
bounds := image.Bounds() |
||||
|
||||
for y := 0; y < bounds.Max.Y; y++ { |
||||
for x := 0; x < bounds.Max.X; x++ { |
||||
image.Set(x, y, color.Black) |
||||
} |
||||
} |
||||
err = png.Encode(bgfile, image) |
||||
if err != nil { |
||||
return errors.New(fmt.Sprintf("Could not encode an image : %s", err)) |
||||
} |
||||
err = bgfile.Close() |
||||
if err != nil { |
||||
return errors.New(fmt.Sprintf("Could not close the background file : %s", err)) |
||||
} |
||||
|
||||
return nil |
||||
} |
@ -1,56 +0,0 @@
|
||||
package util |
||||
|
||||
import ( |
||||
"os" |
||||
"strings" |
||||
) |
||||
|
||||
// checks if given path is a directory
|
||||
func IsDir(path string) bool { |
||||
info, err := os.Stat(path) |
||||
if err != nil { |
||||
// path error
|
||||
return false |
||||
} |
||||
if !info.IsDir() { |
||||
return false |
||||
} |
||||
return true |
||||
} |
||||
|
||||
// checks if given string contains ".osu" file extention
|
||||
func IsBeatmap(filename string) bool { |
||||
if len(filename) < 5 { |
||||
// too short filename to be a beatmap file
|
||||
return false |
||||
} |
||||
if filename[len(filename)-4:] == ".osu" { |
||||
return true |
||||
} |
||||
return false |
||||
} |
||||
|
||||
// checks if given string contains the image file extention
|
||||
func IsImage(filename string) bool { |
||||
if IsDir(filename) { |
||||
// given filename is actually a directory
|
||||
return false |
||||
} |
||||
|
||||
var imageExtentions []string = []string{"jpeg", "jpg", "png", "JPEG", "JPG", "PNG"} |
||||
for _, extention := range imageExtentions { |
||||
if strings.Contains(filename, extention) { |
||||
return true |
||||
} |
||||
} |
||||
return false |
||||
} |
||||
|
||||
// checks if given directory/file does exist
|
||||
func DoesExist(path string) bool { |
||||
_, err := os.Stat(path) |
||||
if err != nil { |
||||
return false |
||||
} |
||||
return true |
||||
} |
@ -1,32 +0,0 @@
|
||||
package util |
||||
|
||||
import ( |
||||
"errors" |
||||
"fmt" |
||||
"io" |
||||
"os" |
||||
) |
||||
|
||||
// opens given files, copies one into another
|
||||
func CopyFile(srcPath, dstPath string) error { |
||||
// open for reading (source)
|
||||
srcFile, err := os.Open(srcPath) |
||||
if err != nil { |
||||
return errors.New(fmt.Sprintf("Could not open src file : %s", err)) |
||||
} |
||||
defer srcFile.Close() |
||||
|
||||
// open for writing (destination) (create file, if it does not exist already)
|
||||
dstFile, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE, os.ModePerm) |
||||
if err != nil { |
||||
return errors.New(fmt.Sprintf("Could not open dst file : %s", err)) |
||||
} |
||||
defer dstFile.Close() |
||||
|
||||
_, err = io.Copy(dstFile, srcFile) |
||||
if err != nil { |
||||
return errors.New(fmt.Sprintf("Could not copy file : %s", err)) |
||||
} |
||||
|
||||
return nil |
||||
} |
Loading…
Reference in new issue