Something went wrong. Try again.
osu!lazer maps/scores/settings bidirectional diff/export/sync tool
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702module Osync.Sync
open Systemopen System.IOopen System.Text.Json
type MachineState = { BeatmapSetIds: Set<int> SkinIdentifiers: Map<string, string> // hash -> name ScoreHashes: Set<string> Settings: Map<string, string> RawSettingsLines: string array AutoDownload: bool DataPath: string RealmPath: string SettingsPath: string }
// --- Extraction ---
let extractLocal (dirOverride: string option) : Result<MachineState, string> = try let dataPath = dirOverride |> Option.defaultWith Realm.getOsuDataPath
let settingsPath = Path.Combine(dataPath, "game.ini")
let (beatmapSetIds, skinIdentifiers, scoreHashes) = use realm = Realm.openRealm dataPath
(Realm.beatmapSetIdsFrom realm, Realm.skinIdentifiersFrom realm, Realm.scoreHashesFrom realm)
let rawLines = if File.Exists(settingsPath) then File.ReadAllLines(settingsPath) else Array.empty
let settings = Settings.parseLines rawLines
let autoDownload = settings |> Map.tryFind "AutomaticallyDownloadMissingBeatmaps" |> Option.map (fun v -> v.ToLowerInvariant() = "true" || v = "1") |> Option.defaultValue false
let realmPath = Realm.findRealmPath dataPath
Ok { BeatmapSetIds = beatmapSetIds SkinIdentifiers = skinIdentifiers ScoreHashes = scoreHashes Settings = settings RawSettingsLines = rawLines AutoDownload = autoDownload DataPath = dataPath RealmPath = realmPath SettingsPath = settingsPath } with ex -> Error $"Failed to extract local state: {ex.Message}"
let serializeExtractJson (state: MachineState) : string = use stream = new MemoryStream() use writer = new Utf8JsonWriter(stream, JsonWriterOptions(Indented = true))
writer.WriteStartObject()
writer.WritePropertyName("beatmapSetIds") writer.WriteStartArray()
for id in state.BeatmapSetIds do writer.WriteNumberValue(id)
writer.WriteEndArray()
writer.WritePropertyName("skinIdentifiers") writer.WriteStartObject()
for kv in state.SkinIdentifiers do writer.WriteString(kv.Key, kv.Value)
writer.WriteEndObject()
writer.WritePropertyName("scoreHashes") writer.WriteStartArray()
for h in state.ScoreHashes do writer.WriteStringValue(h)
writer.WriteEndArray()
writer.WritePropertyName("settings") writer.WriteStartObject()
for kv in state.Settings do writer.WriteString(kv.Key, kv.Value)
writer.WriteEndObject()
writer.WritePropertyName("rawSettingsLines") writer.WriteStartArray()
for line in state.RawSettingsLines do writer.WriteStringValue(line)
writer.WriteEndArray()
writer.WriteBoolean("autoDownload", state.AutoDownload) writer.WriteString("dataPath", state.DataPath) writer.WriteString("realmPath", state.RealmPath) writer.WriteString("settingsPath", state.SettingsPath)
writer.WriteEndObject() writer.Flush()
System.Text.Encoding.UTF8.GetString(stream.ToArray())
let parseExtractJson (json: string) : Result<MachineState, string> = try let doc = JsonDocument.Parse(json) let root = doc.RootElement
let beatmapSetIds = root.GetProperty("beatmapSetIds").EnumerateArray() |> Seq.map (fun e -> e.GetInt32()) |> Set.ofSeq
let skinIdentifiers = root.GetProperty("skinIdentifiers").EnumerateObject() |> Seq.map (fun p -> p.Name, p.Value.GetString()) |> Map.ofSeq
let scoreHashes = root.GetProperty("scoreHashes").EnumerateArray() |> Seq.map (fun e -> e.GetString()) |> Set.ofSeq
let settings = root.GetProperty("settings").EnumerateObject() |> Seq.map (fun p -> p.Name, p.Value.GetString()) |> Map.ofSeq
let rawSettingsLines = root.GetProperty("rawSettingsLines").EnumerateArray() |> Seq.map (fun e -> e.GetString()) |> Seq.toArray
let autoDownload = root.GetProperty("autoDownload").GetBoolean() let dataPath = root.GetProperty("dataPath").GetString()
let realmPath = root.GetProperty("realmPath").GetString()
let settingsPath = root.GetProperty("settingsPath").GetString()
Ok { BeatmapSetIds = beatmapSetIds SkinIdentifiers = skinIdentifiers ScoreHashes = scoreHashes Settings = settings RawSettingsLines = rawSettingsLines AutoDownload = autoDownload DataPath = dataPath RealmPath = realmPath SettingsPath = settingsPath } with ex -> Error $"Failed to parse extract JSON: {ex.Message}"
// --- Host resolution ---
type ResolvedHost = | Localhost | Remote of string
let extractState (host: ResolvedHost) (dirOverride: string option) (osyncPath: string) : Result<MachineState, string> = match host with | Localhost -> extractLocal dirOverride | Remote hostname -> let cmd = match dirOverride with | Some d -> $"{osyncPath} extract --dir {Ssh.shellEscape d}" | None -> $"{osyncPath} extract"
Ssh.runRemote hostname cmd |> Result.bind parseExtractJson
// --- Helpers ---
let private mapUrl (id: int) = $"https://osu.ppy.sh/beatmapsets/{id}"
let private promptYesNo (message: string) : bool = eprintfn "%s [y/N] " message let input = Console.ReadLine()
match input with | null -> false | s -> s.Trim().ToLowerInvariant() = "y"
let private promptSettingChoice (diff: Settings.SettingsDiff) (fromLabel: string) (toLabel: string) : char = eprintfn ""
match diff.LocalValue, diff.RemoteValue with | Some lv, Some rv -> eprintfn " %s: %s=%s, %s=%s" diff.Key fromLabel lv toLabel rv | Some lv, None -> eprintfn " %s: %s=%s, %s=(missing)" diff.Key fromLabel lv toLabel | None, Some rv -> eprintfn " %s: %s=(missing), %s=%s" diff.Key fromLabel toLabel rv | None, None -> ()
eprintfn " [F]rom (%s) / [T]o (%s) / [S]kip?" fromLabel toLabel
let rec loop () = eprintf " > " let input = Console.ReadLine()
match input with | null -> 'S' | s -> match s.Trim().ToUpperInvariant() with | "F" -> 'L' | "T" -> 'R' | "S" -> 'S' | _ -> eprintfn " Invalid choice. Enter F, T, or S." loop ()
loop ()
let private writeSettings (host: ResolvedHost) (path: string) (rawLines: string array) (updates: Map<string, string>) : Result<unit, string> = let patched = Settings.patchLines rawLines updates let content = String.Join("\n", patched)
match host with | Localhost -> try File.WriteAllText(path, content) Ok() with ex -> Error $"Failed to write settings to {path}: {ex.Message}" | Remote hostname -> Ssh.writeRemoteFile hostname path content
let private enableAutoDownload (host: ResolvedHost) (state: MachineState) : Result<unit, string> = let updated = Map.add "AutomaticallyDownloadMissingBeatmaps" "True" state.Settings writeSettings host state.SettingsPath state.RawSettingsLines updated
// --- Run modes ---
type SyncMode = | Sync | Diff
type RunConfig = { Mode: SyncMode FromHost: ResolvedHost ToHost: ResolvedHost FromDir: string option ToDir: string option FromOsync: string ToOsync: string FromLabel: string ToLabel: string }
let private printBeatmapDiffs (fromState: MachineState) (toState: MachineState) (fromLabel: string) (toLabel: string) = let missingOnTo = Set.difference fromState.BeatmapSetIds toState.BeatmapSetIds let missingOnFrom = Set.difference toState.BeatmapSetIds fromState.BeatmapSetIds
eprintfn "" eprintfn "=== Beatmap Differences ==="
if Set.isEmpty missingOnTo && Set.isEmpty missingOnFrom then eprintfn " No beatmap differences found." else if not (Set.isEmpty missingOnTo) then eprintfn "" eprintfn " Missing on %s (%d maps):" toLabel (Set.count missingOnTo)
for id in missingOnTo |> Set.toList |> List.truncate 20 do eprintfn " %s" (mapUrl id)
if Set.count missingOnTo > 20 then eprintfn " ... and %d more" (Set.count missingOnTo - 20)
if not (Set.isEmpty missingOnFrom) then eprintfn "" eprintfn " Missing on %s (%d maps):" fromLabel (Set.count missingOnFrom)
for id in missingOnFrom |> Set.toList |> List.truncate 20 do eprintfn " %s" (mapUrl id)
if Set.count missingOnFrom > 20 then eprintfn " ... and %d more" (Set.count missingOnFrom - 20)
(missingOnFrom, missingOnTo)
let private printSkinDiffs (fromState: MachineState) (toState: MachineState) (fromLabel: string) (toLabel: string) = let fromHashes = fromState.SkinIdentifiers |> Map.keys |> Set.ofSeq let toHashes = toState.SkinIdentifiers |> Map.keys |> Set.ofSeq let missingOnTo = Set.difference fromHashes toHashes let missingOnFrom = Set.difference toHashes fromHashes
eprintfn "" eprintfn "=== Skin Differences ==="
if Set.isEmpty missingOnTo && Set.isEmpty missingOnFrom then eprintfn " No skin differences found." else if not (Set.isEmpty missingOnTo) then eprintfn "" eprintfn " Missing on %s (%d skins):" toLabel (Set.count missingOnTo)
for hash in missingOnTo |> Set.toList |> List.truncate 20 do let name = Map.find hash fromState.SkinIdentifiers eprintfn " %s" name
if Set.count missingOnTo > 20 then eprintfn " ... and %d more" (Set.count missingOnTo - 20)
if not (Set.isEmpty missingOnFrom) then eprintfn "" eprintfn " Missing on %s (%d skins):" fromLabel (Set.count missingOnFrom)
for hash in missingOnFrom |> Set.toList |> List.truncate 20 do let name = Map.find hash toState.SkinIdentifiers eprintfn " %s" name
if Set.count missingOnFrom > 20 then eprintfn " ... and %d more" (Set.count missingOnFrom - 20)
(missingOnFrom, missingOnTo)
let private printScoreDiffs (fromState: MachineState) (toState: MachineState) (fromLabel: string) (toLabel: string) = let missingOnTo = Set.difference fromState.ScoreHashes toState.ScoreHashes let missingOnFrom = Set.difference toState.ScoreHashes fromState.ScoreHashes
eprintfn "" eprintfn "=== Score Differences ==="
if Set.isEmpty missingOnTo && Set.isEmpty missingOnFrom then eprintfn " No score differences found." else if not (Set.isEmpty missingOnTo) then eprintfn " Missing on %s: %d score(s)" toLabel (Set.count missingOnTo)
if not (Set.isEmpty missingOnFrom) then eprintfn " Missing on %s: %d score(s)" fromLabel (Set.count missingOnFrom)
(missingOnFrom, missingOnTo)
let private updateAutoDownload (state: MachineState) : MachineState = let key = "AutomaticallyDownloadMissingBeatmaps"
{ state with Settings = Map.add key "True" state.Settings RawSettingsLines = Settings.patchLines state.RawSettingsLines (Map.add key "True" state.Settings) AutoDownload = true }
let private handleAutoDownload (config: RunConfig) (fromState: MachineState) (toState: MachineState) (missingOnFrom: Set<int>) (missingOnTo: Set<int>) : bool * MachineState * MachineState = let mutable hadError = false let mutable from = fromState let mutable ``to`` = toState
if not (Set.isEmpty missingOnTo) && not toState.AutoDownload then eprintfn ""
if promptYesNo $" AutomaticallyDownloadMissingBeatmaps is disabled on {config.ToLabel}. Enable it?" then ``to`` <- updateAutoDownload ``to``
match enableAutoDownload config.ToHost ``to`` with | Ok() -> eprintfn " Enabled auto-download on %s." config.ToLabel | Error e -> eprintfn " Error enabling auto-download on %s: %s" config.ToLabel e hadError <- true
if not (Set.isEmpty missingOnFrom) && not fromState.AutoDownload then eprintfn ""
if promptYesNo $" AutomaticallyDownloadMissingBeatmaps is disabled on {config.FromLabel}. Enable it?" then from <- updateAutoDownload from
match enableAutoDownload config.FromHost from with | Ok() -> eprintfn " Enabled auto-download on %s." config.FromLabel | Error e -> eprintfn " Error enabling auto-download on %s: %s" config.FromLabel e hadError <- true
(hadError, from, ``to``)
let private handleSettingsDiff (config: RunConfig) (fromState: MachineState) (toState: MachineState) : bool = let diffs = Settings.diff fromState.Settings toState.Settings let mutable hadError = false
eprintfn "" eprintfn "=== Settings Differences ==="
if List.isEmpty diffs then eprintfn " No settings differences found." else eprintfn " Found %d setting(s) that differ." (List.length diffs)
match config.Mode with | Diff -> for d in diffs do match d.LocalValue, d.RemoteValue with | Some lv, Some rv -> eprintfn " %s: %s=%s, %s=%s" d.Key config.FromLabel lv config.ToLabel rv | Some lv, None -> eprintfn " %s: %s=%s, %s=(missing)" d.Key config.FromLabel lv config.ToLabel | None, Some rv -> eprintfn " %s: %s=(missing), %s=%s" d.Key config.FromLabel config.ToLabel rv | None, None -> () | Sync -> let choices = diffs |> List.map (fun d -> let choice = promptSettingChoice d config.FromLabel config.ToLabel (d.Key, choice))
let activeChoices = choices |> List.filter (fun (_, c) -> c <> 'S')
if not (List.isEmpty activeChoices) then let (updatedFrom, updatedTo) = Settings.applyChoice fromState.Settings toState.Settings activeChoices
if updatedFrom <> fromState.Settings then eprintfn "" eprintfn " Writing updated settings to %s..." config.FromLabel
match writeSettings config.FromHost fromState.SettingsPath fromState.RawSettingsLines updatedFrom with | Ok() -> eprintfn " Done." | Error e -> eprintfn " Error: %s" e hadError <- true
if updatedTo <> toState.Settings then eprintfn "" eprintfn " Writing updated settings to %s..." config.ToLabel
match writeSettings config.ToHost toState.SettingsPath toState.RawSettingsLines updatedTo with | Ok() -> eprintfn " Done." | Error e -> eprintfn " Error: %s" e hadError <- true
hadError
let private hostOption (h: ResolvedHost) = match h with | Remote h -> Some h | Localhost -> None
let private readMissing (realm: Realms.Realm) (missingBeatmapIds: Set<int>) (missingSkinHashes: Set<string>) (missingScoreHashes: Set<string>) : Realm.BeatmapSetData list * Realm.SkinData list * Realm.ScoreData list = let beatmapSets = if Set.isEmpty missingBeatmapIds then [] else Realm.readBeatmapSets realm missingBeatmapIds
let skins = if Set.isEmpty missingSkinHashes then [] else Realm.readSkins realm missingSkinHashes
let scores = if Set.isEmpty missingScoreHashes then [] else Realm.readScores realm missingScoreHashes
(beatmapSets, skins, scores)
let private writeToRealm (realm: Realms.Realm) (beatmapSets: Realm.BeatmapSetData list) (skins: Realm.SkinData list) (scores: Realm.ScoreData list) = if not (List.isEmpty beatmapSets) then Realm.writeBeatmapSets realm beatmapSets
if not (List.isEmpty skins) then Realm.writeSkins realm skins
if not (List.isEmpty scores) then Realm.writeScores realm scores
let private writeToRemote (config: RunConfig) (toHostname: string) (tempRealmPath: string) : Result<unit, string> = let remoteTempRealm = $"/tmp/osync-import-{IO.Path.GetRandomFileName()}"
match Ssh.scpToRemote tempRealmPath toHostname remoteTempRealm with | Error e -> Error $"Error copying realm to {config.ToLabel}: {e}" | Ok _ -> let importCmd = let dirArg = match config.ToDir with | Some d -> $" --dir {Ssh.shellEscape d}" | None -> ""
$"{config.ToOsync} import --source-realm {Ssh.shellEscape remoteTempRealm}{dirArg}"
let result = match Ssh.runRemote toHostname importCmd with | Error e -> Error $"Error running import on {config.ToLabel}: {e}" | Ok output -> if output.Length > 0 then eprintf "%s" output
Ok()
Ssh.runRemote toHostname $"rm -f {Ssh.shellEscape remoteTempRealm}" |> ignore result
let private syncFiles (config: RunConfig) (fromState: MachineState) (toState: MachineState) (missingBeatmapIds: Set<int>) (missingSkinHashes: Set<string>) (missingScoreHashes: Set<string>) : bool = let totalMaps = Set.count missingBeatmapIds let totalSkins = Set.count missingSkinHashes let totalScores = Set.count missingScoreHashes
if totalMaps = 0 && totalSkins = 0 && totalScores = 0 then false else if not ( promptYesNo $" Sync %d{totalMaps} beatmap(s), %d{totalSkins} skin(s), and %d{totalScores} score(s) from %s{config.FromLabel} to %s{config.ToLabel}?" ) then false else eprintfn "" eprintfn " Copying realm database from %s..." config.FromLabel
match Ssh.copyRealmToTemp (hostOption config.FromHost) fromState.RealmPath with | Error e -> eprintfn " Error: %s" e true | Ok tempRealmPath -> try try use sourceRealm = Realm.openRealmAt tempRealmPath eprintfn " Reading missing data from %s..." config.FromLabel
let (beatmapSets, skins, scores) = readMissing sourceRealm missingBeatmapIds missingSkinHashes missingScoreHashes
let fileHashes = Realm.collectFileHashes beatmapSets skins scores
let rsyncResult = if Set.isEmpty fileHashes then Ok() else eprintfn " Syncing %d file(s)..." (Set.count fileHashes)
Ssh.rsyncFiles (hostOption config.FromHost) (hostOption config.ToHost) fromState.DataPath toState.DataPath fileHashes
match rsyncResult with | Error e -> eprintfn " Error syncing files: %s" e true | Ok() -> eprintfn " Writing to realm on %s..." config.ToLabel
let writeResult = match config.ToHost with | Localhost -> use destRealm = Realm.openRealm toState.DataPath writeToRealm destRealm beatmapSets skins scores Ok() | Remote h -> writeToRemote config h tempRealmPath
match writeResult with | Error e -> eprintfn " %s" e true | Ok() -> eprintfn " Synced %d beatmap(s), %d skin(s), and %d score(s)." (List.length beatmapSets) (List.length skins) (List.length scores)
false with ex -> eprintfn " Error during sync: %s" ex.Message true finally if File.Exists(tempRealmPath) then File.Delete(tempRealmPath)
let run (config: RunConfig) : int = eprintfn "Extracting state from %s..." config.FromLabel let fromResult = extractState config.FromHost config.FromDir config.FromOsync
eprintfn "Extracting state from %s..." config.ToLabel let toResult = extractState config.ToHost config.ToDir config.ToOsync
match fromResult, toResult with | Error e, _ -> eprintfn "Error extracting from %s: %s" config.FromLabel e 1 | _, Error e -> eprintfn "Error extracting from %s: %s" config.ToLabel e 1 | Ok fromState, Ok toState -> let (missingOnFrom, missingOnTo) = printBeatmapDiffs fromState toState config.FromLabel config.ToLabel
let (_skinsMissingOnFrom, skinsMissingOnTo) = printSkinDiffs fromState toState config.FromLabel config.ToLabel
let (_scoresMissingOnFrom, scoresMissingOnTo) = printScoreDiffs fromState toState config.FromLabel config.ToLabel
let mutable hadError = false let mutable from = fromState let mutable ``to`` = toState
match config.Mode with | Sync -> let (err, f, t) = handleAutoDownload config from ``to`` missingOnFrom missingOnTo hadError <- err from <- f ``to`` <- t
eprintfn ""
if syncFiles config from ``to`` missingOnTo skinsMissingOnTo scoresMissingOnTo then hadError <- true | Diff -> ()
if handleSettingsDiff config from ``to`` then hadError <- true
eprintfn ""
if hadError then eprintfn "Done with errors." 1 else eprintfn "Done." 0
let runImport (sourceRealmPath: string) (dirOverride: string option) : int = try let destDataPath = dirOverride |> Option.defaultWith Realm.getOsuDataPath use sourceRealm = Realm.openRealmAt sourceRealmPath use destRealm = Realm.openRealm destDataPath
let missingBeatmapIds = Set.difference (Realm.beatmapSetIdsFrom sourceRealm) (Realm.beatmapSetIdsFrom destRealm)
let missingSkinHashes = let sourceHashes = Realm.skinIdentifiersFrom sourceRealm |> Map.keys |> Set.ofSeq let destHashes = Realm.skinIdentifiersFrom destRealm |> Map.keys |> Set.ofSeq Set.difference sourceHashes destHashes
let missingScoreHashes = Set.difference (Realm.scoreHashesFrom sourceRealm) (Realm.scoreHashesFrom destRealm)
if Set.isEmpty missingBeatmapIds && Set.isEmpty missingSkinHashes && Set.isEmpty missingScoreHashes then eprintfn " Nothing to import." 0 else let (beatmapSets, skins, scores) = readMissing sourceRealm missingBeatmapIds missingSkinHashes missingScoreHashes
writeToRealm destRealm beatmapSets skins scores
eprintfn " Imported %d beatmap(s), %d skin(s), and %d score(s)." (List.length beatmapSets) (List.length skins) (List.length scores)
0 with ex -> eprintfn "Error: %s" ex.Message 1