using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using Steamworks; // Creates or updates a RimWorld Steam Workshop item through the running, logged-in Steam client. // No password: SteamAPI attaches to the client as RimWorld (app 294100), like the game does. // Without --publish it never calls a Steam write API: it checks the login and the RimWorld license, for an // existing item reads it and checks that this Steam account owns it, and for a new one checks that no earlier, // cut-off create left an item behind. internal static class Program { private const uint RimWorldAppId = 294100; private const int MaxTextBytes = 8000; // Steam's limit for a description and a change note (k_cchPublishedDocumentDescriptionMax) private const int MaxTitleBytes = 128; // k_cchPublishedDocumentTitleMax without the terminating zero private const long MaxPreviewBytes = 1024 * 1024; // Steam refuses a preview over 1 MB private const string LegalAgreementHint = "Steam hides the item until you accept the Workshop legal agreement: https://steamcommunity.com/sharedfiles/workshoplegalagreement"; private static int Main(string[] args) { Options o; try { o = Options.Parse(args); } catch (ArgumentException e) { Console.Error.WriteLine(e.Message); Console.Error.WriteLine(Options.Usage); return 64; } // Everything that can be checked without Steam comes first. if (o.Content != null && !CheckContent(o.Content)) return 65; if (o.Preview != null && !CheckPreview(o.Preview)) return 65; if (o.Title != null && Encoding.UTF8.GetByteCount(o.Title) > MaxTitleBytes) { Console.Error.WriteLine($"The title is over Steam's {MaxTitleBytes}-byte limit."); return 65; } string note = o.NoteFile != null ? File.ReadAllText(o.NoteFile, Encoding.UTF8).Trim() : null; string description = o.DescriptionFile != null ? File.ReadAllText(o.DescriptionFile, Encoding.UTF8).Trim() : null; if (description != null && Encoding.UTF8.GetByteCount(description) > MaxTextBytes) { Console.Error.WriteLine($"The description is over Steam's {MaxTextBytes}-byte limit."); return 65; } if (note != null && Encoding.UTF8.GetByteCount(note) > MaxTextBytes) { Console.Error.WriteLine($"The change note is over Steam's {MaxTextBytes}-byte limit."); return 65; } if (o.Create && File.Exists(o.IdFile)) { Console.Error.WriteLine($"{o.IdFile} already exists ({File.ReadAllText(o.IdFile).Trim()}): the item was created before. Update it with --item."); return 65; } // SteamAPI.Init looks for steam_appid.txt in the working directory; the env var covers other callers. Directory.SetCurrentDirectory(AppContext.BaseDirectory); Environment.SetEnvironmentVariable("SteamAppId", RimWorldAppId.ToString()); if (!Packsize.Test() || !DllCheck.Test()) { Console.Error.WriteLine("Steamworks.NET and steam_api64.dll don't match. Rebuild the tool against the current RimWorld install."); return 2; } // Never call SteamAPI.RestartAppIfNecessary here: it would make Steam launch RimWorld. if (!SteamAPI.Init()) { Console.Error.WriteLine("SteamAPI.Init failed. Is Steam running and logged in, under the same Windows user, not as administrator?"); return 2; } try { return Run(o, note, description); } finally { SteamAPI.Shutdown(); } } private static int Run(Options o, string note, string description) { Console.WriteLine($"Steam account: {SteamFriends.GetPersonaName()}"); if (!SteamUser.BLoggedOn()) { Console.Error.WriteLine("Steam is not logged on (offline mode?). Go online in Steam and try again."); return 3; } if (!SteamApps.BIsSubscribedApp(new AppId_t(RimWorldAppId))) { Console.Error.WriteLine("This Steam account has no RimWorld license, so it can't publish RimWorld Workshop items."); return 3; } return o.Create ? RunCreate(o, note, description) : RunUpdate(o, note, description); } private static int RunUpdate(Options o, string note, string description) { var item = new PublishedFileId_t(o.Item); if (!QueryDetails(item, o.Timeout, out SteamUGCDetails_t d, out string[] descriptors)) return 3; Console.WriteLine($"Item {o.Item}: \"{d.m_rgchTitle}\""); Console.WriteLine($" updated {DateTimeOffset.FromUnixTimeSeconds(d.m_rtimeUpdated).ToLocalTime():yyyy-MM-dd HH:mm}"); Console.WriteLine($" tags {d.m_rgchTags}"); Console.WriteLine($" size {d.m_nFileSize / 1024.0:N0} KB"); Console.WriteLine($" visible {VisibilityName(d.m_eVisibility)}"); if (d.m_bBanned) Console.WriteLine(" BANNED on Steam"); // Mature-content descriptors hide the item page from logged-out visitors and from players who didn't opt in. Console.WriteLine($" content {(descriptors.Length > 0 ? string.Join(", ", descriptors) : "no mature-content descriptors")}"); if (d.m_nConsumerAppID.m_AppId != RimWorldAppId) { Console.Error.WriteLine($"The item belongs to app {d.m_nConsumerAppID.m_AppId}, not RimWorld."); return 3; } if (d.m_ulSteamIDOwner != SteamUser.GetSteamID().m_SteamID) { Console.Error.WriteLine("This Steam account doesn't own the item."); return 3; } Console.WriteLine(" owner this account"); if (!o.Publish) { Console.WriteLine(); Console.WriteLine("Dry run: nothing was uploaded."); if (o.Title != null) Console.WriteLine($" would set the title \"{o.Title}\"" + (o.Title == d.m_rgchTitle ? " (unchanged)" : $" (now \"{d.m_rgchTitle}\")")); PrintPlan(o, note, description); return 0; } bool descriptionOnly = o.Content == null && note == null && description != null; if (!descriptionOnly && (o.Content == null || note == null)) { Console.Error.WriteLine("--publish needs --content and --note-file, or only --description-file."); return 64; } return Submit(item, o, note, description, false); } private static int RunCreate(Options o, string note, string description) { Console.WriteLine(" logged on, owns RimWorld"); int found = CheckNoEarlierItem(o); if (found != 0) return found; if (!o.Publish) { Console.WriteLine(); Console.WriteLine("Dry run: nothing was created or uploaded."); Console.WriteLine($" would create a new RimWorld Workshop item \"{o.Title}\""); Console.WriteLine($" would write its id to {o.IdFile}"); PrintPlan(o, note, description); if (o.Visibility == null) Console.WriteLine(" visibility Steam's default for a new item, as with the in-game uploader"); return 0; } Console.WriteLine("Creating the Workshop item..."); bool got = false, ioFailure = false; CreateItemResult_t created = default; var call = CallResult.Create((r, io) => { created = r; ioFailure = io; got = true; }); call.Set(SteamUGC.CreateItem(new AppId_t(RimWorldAppId), EWorkshopFileType.k_EWorkshopFileTypeFirst)); bool finished = Pump(() => got, o.Timeout); GC.KeepAlive(call); string myItems = $"https://steamcommunity.com/profiles/{SteamUser.GetSteamID().m_SteamID}/myworkshopfiles/?appid={RimWorldAppId}"; if (!finished) { Console.Error.WriteLine($"No answer from Steam in time. Steam may still create the item: check {myItems} before retrying."); return 5; } if (ioFailure) return Fail($"Steam reported an IO failure while creating the item. Check {myItems} before retrying."); if (created.m_eResult != EResult.k_EResultOK) return Fail($"Steam refused to create the item: {created.m_eResult}. {Hint(created.m_eResult)}"); // Write the id before anything else: a failed upload must lead to an update on retry, never to a second item. PublishedFileId_t item = created.m_nPublishedFileId; string id = item.m_PublishedFileId.ToString(); try { File.WriteAllText(o.IdFile, id); // The game copies the id into the uploaded folder too, so the uploaded About folder matches the repo. if (o.Content != null) File.WriteAllText(Path.Combine(o.Content, "About", "PublishedFileId.txt"), id); } catch (Exception e) { Console.Error.WriteLine($"Created item {id}, but couldn't write {o.IdFile}: {e.Message}"); Console.Error.WriteLine($"Write {id} into that file by hand before retrying, or the next run creates a second item."); return 4; } Console.WriteLine($"Created item {id}: https://steamcommunity.com/sharedfiles/filedetails/?id={id}"); Console.WriteLine($" wrote {o.IdFile}"); int code = Submit(item, o, note, description, created.m_bUserNeedsToAcceptWorkshopLegalAgreement); if (code != 0) Console.Error.WriteLine($"Item {id} exists, but the upload didn't finish. Run the upload again: with {Path.GetFileName(o.IdFile)} in place it updates this item instead of creating another."); return code; } // A create that was cut off (no answer in time, an IO failure, the process killed or Ctrl+C between Steam // creating the item and the answer) can leave an item on Steam with no id file, and the next run would create // a second one. Such an item has no title yet: the title only comes with the first SubmitItemUpdate. So before // creating, look at this account's newest RimWorld items for one with this title or none. private static int CheckNoEarlierItem(Options o) { var appId = new AppId_t(RimWorldAppId); UGCQueryHandle_t q = SteamUGC.CreateQueryUserUGCRequest(SteamUser.GetSteamID().GetAccountID(), EUserUGCList.k_EUserUGCList_Published, EUGCMatchingUGCType.k_EUGCMatchingUGCType_Items, EUserUGCListSortOrder.k_EUserUGCListSortOrder_CreationOrderDesc, appId, appId, 1); bool got = false, ioFailure = false; SteamUGCQueryCompleted_t done = default; var call = CallResult.Create((r, io) => { done = r; ioFailure = io; got = true; }); call.Set(SteamUGC.SendQueryUGCRequest(q)); try { if (!Pump(() => got, o.Timeout)) { Console.Error.WriteLine("No answer from Steam for this account's Workshop items, so it is unclear whether an earlier create left an item. Try again."); return 3; } if (ioFailure || done.m_eResult != EResult.k_EResultOK) { Console.Error.WriteLine($"The query for this account's Workshop items failed: {(ioFailure ? "IO failure" : done.m_eResult.ToString())}. Try again."); return 3; } var earlier = new List(); for (uint i = 0; i < done.m_unNumResultsReturned; i++) { if (!SteamUGC.GetQueryUGCResult(q, i, out SteamUGCDetails_t d) || d.m_eResult != EResult.k_EResultOK) continue; string title = (d.m_rgchTitle ?? "").Trim(); if (title.Length == 0 || string.Equals(title, o.Title, StringComparison.OrdinalIgnoreCase)) earlier.Add($"{d.m_nPublishedFileId.m_PublishedFileId} ({(title.Length == 0 ? "no title" : $"\"{title}\"")})"); } if (earlier.Count > 0) { Console.Error.WriteLine("This Steam account already has a RimWorld Workshop item with this title or with no title: " + string.Join(", ", earlier) + "."); Console.Error.WriteLine($"If it is this mod (an untitled one is an earlier create that was cut off), write its id to {o.IdFile} and run again to update it."); Console.Error.WriteLine($"If it is not, rename or delete it on Steam first: https://steamcommunity.com/profiles/{SteamUser.GetSteamID().m_SteamID}/myworkshopfiles/?appid={RimWorldAppId}"); return 65; } Console.WriteLine($" no earlier item with this title or without a title ({done.m_unNumResultsReturned} newest checked)"); return 0; } finally { GC.KeepAlive(call); SteamUGC.ReleaseQueryUGCRequest(q); } } private static void PrintPlan(Options o, string note, string description) { if (o.Content != null) Console.WriteLine($" would upload {o.Content}"); if (o.Tags != null) Console.WriteLine($" would tag {string.Join(", ", o.Tags)}"); if (o.Preview != null) Console.WriteLine($" would set the preview {o.Preview} ({new FileInfo(o.Preview).Length / 1024.0:N0} KB)"); if (description != null) Console.WriteLine($" would {(o.Create ? "set" : "replace")} the description ({Encoding.UTF8.GetByteCount(description)} bytes)"); if (o.Visibility != null) Console.WriteLine($" would set the visibility to {VisibilityName(o.Visibility.Value)}"); if (note != null) Console.WriteLine(" change note:\n" + Indent(note)); } private static int Submit(PublishedFileId_t item, Options o, string note, string description, bool legalAgreementPending) { UGCUpdateHandle_t h = SteamUGC.StartItemUpdate(new AppId_t(RimWorldAppId), item); // Same fields as the game's uploader: title, description, preview, tags, content. if (o.Title != null && !SteamUGC.SetItemTitle(h, o.Title)) return Fail("SetItemTitle refused the title."); // Description-only updates send no content and no change note (null), so Steam lists no new change note. if (description != null && !SteamUGC.SetItemDescription(h, description)) return Fail("SetItemDescription refused the text."); if (o.Preview != null && !SteamUGC.SetItemPreview(h, o.Preview)) return Fail("SetItemPreview refused the preview image."); if (o.Tags != null && !SteamUGC.SetItemTags(h, o.Tags)) return Fail("SetItemTags refused the tags."); if (o.Content != null && !SteamUGC.SetItemContent(h, o.Content)) return Fail("SetItemContent refused the content folder."); if (o.Visibility != null && !SteamUGC.SetItemVisibility(h, o.Visibility.Value)) return Fail("SetItemVisibility refused the visibility."); bool got = false, ioFailure = false; SubmitItemUpdateResult_t result = default; var call = CallResult.Create((r, io) => { result = r; ioFailure = io; got = true; }); call.Set(SteamUGC.SubmitItemUpdate(h, note)); Console.WriteLine("Uploading..."); EItemUpdateStatus last = EItemUpdateStatus.k_EItemUpdateStatusInvalid; bool finished = Pump(() => got, o.Timeout, () => { EItemUpdateStatus s = SteamUGC.GetItemUpdateProgress(h, out ulong done, out ulong total); if (s != last && s != EItemUpdateStatus.k_EItemUpdateStatusInvalid) { Console.WriteLine($" {s.ToString().Replace("k_EItemUpdateStatus", "")}" + (total > 0 ? $" {done / 1024}/{total / 1024} KB" : "")); last = s; } }); GC.KeepAlive(call); if (!finished) { Console.Error.WriteLine("No answer from Steam in time. Steam may still finish the upload; check the item page before retrying."); return 5; } if (ioFailure) return Fail("Steam reported an IO failure."); if (result.m_eResult != EResult.k_EResultOK) return Fail($"Steam refused the update: {result.m_eResult}. {Hint(result.m_eResult)}"); Console.WriteLine($"Done: https://steamcommunity.com/sharedfiles/filedetails/?id={item.m_PublishedFileId}"); if (legalAgreementPending || result.m_bUserNeedsToAcceptWorkshopLegalAgreement) Console.WriteLine(LegalAgreementHint); return 0; } private static bool QueryDetails(PublishedFileId_t item, TimeSpan timeout, out SteamUGCDetails_t details, out string[] descriptors) { details = default; descriptors = Array.Empty(); UGCQueryHandle_t q = SteamUGC.CreateQueryUGCDetailsRequest(new[] { item }, 1); bool got = false, ioFailure = false; SteamUGCQueryCompleted_t done = default; var call = CallResult.Create((r, io) => { done = r; ioFailure = io; got = true; }); call.Set(SteamUGC.SendQueryUGCRequest(q)); try { if (!Pump(() => got, timeout)) { Console.Error.WriteLine("No answer from Steam for the item query."); return false; } if (ioFailure || done.m_eResult != EResult.k_EResultOK || done.m_unNumResultsReturned < 1) { Console.Error.WriteLine($"The item query failed: {(ioFailure ? "IO failure" : done.m_eResult.ToString())}."); return false; } if (!SteamUGC.GetQueryUGCResult(q, 0, out details) || details.m_eResult != EResult.k_EResultOK) { Console.Error.WriteLine($"Steam has no item {item}: {details.m_eResult}."); return false; } var ids = new EUGCContentDescriptorID[8]; uint count = SteamUGC.GetQueryUGCContentDescriptors(q, 0, ids, (uint)ids.Length); descriptors = ids.Take((int)Math.Min(count, (uint)ids.Length)) .Select(id => id.ToString().Replace("k_EUGCContentDescriptor_", "")).ToArray(); return true; } finally { GC.KeepAlive(call); SteamUGC.ReleaseQueryUGCRequest(q); } } private static bool Pump(Func done, TimeSpan timeout, Action eachTick = null) { var sw = Stopwatch.StartNew(); while (!done()) { SteamAPI.RunCallbacks(); eachTick?.Invoke(); if (sw.Elapsed > timeout) return false; Thread.Sleep(100); } return true; } private static bool CheckContent(string dir) { if (!Directory.Exists(dir)) { Console.Error.WriteLine($"No content folder at {dir}."); return false; } if (!File.Exists(Path.Combine(dir, "About", "About.xml"))) { Console.Error.WriteLine($"{dir} has no About\\About.xml."); return false; } string[] devOnly = { ".git", "Source", "Tests", "obj", "bin" }; var found = Directory.GetDirectories(dir, "*", SearchOption.AllDirectories) .Where(p => devOnly.Contains(Path.GetFileName(p), StringComparer.OrdinalIgnoreCase)).ToList(); if (found.Count > 0) { Console.Error.WriteLine("The content folder holds development folders that players don't need:\n" + Indent(string.Join("\n", found))); return false; } var files = Directory.GetFiles(dir, "*", SearchOption.AllDirectories); Console.WriteLine($"Content: {dir} ({files.Length} files, {files.Sum(f => new FileInfo(f).Length) / 1024.0:N0} KB)"); return true; } private static bool CheckPreview(string file) { if (!File.Exists(file)) { Console.Error.WriteLine($"No preview image at {file}."); return false; } long size = new FileInfo(file).Length; if (size > MaxPreviewBytes) { Console.Error.WriteLine($"The preview {file} is {size / 1024.0:N0} KB; Steam takes at most 1 MB."); return false; } return true; } private static string VisibilityName(ERemoteStoragePublishedFileVisibility v) => v.ToString().Replace("k_ERemoteStoragePublishedFileVisibility", ""); private static string Hint(EResult r) => r switch { EResult.k_EResultAccessDenied => "The account needs a RimWorld license.", EResult.k_EResultFileNotFound => "Steam couldn't read the content folder or the preview.", EResult.k_EResultLimitExceeded => "The preview is over 1 MB, or the Steam Cloud quota is full.", EResult.k_EResultLockingFailed => "Steam couldn't lock the item; try again in a minute.", EResult.k_EResultInvalidParam => "Steam rejected a field; check the title, the tags and the content path.", EResult.k_EResultInsufficientPrivilege => "Steam restricts this account from uploading (a ban, an account lock or a limited account).", EResult.k_EResultBanned => "Steam restricts this account from uploading (a ban, an account lock or a limited account).", EResult.k_EResultNotLoggedOn => "Steam is not logged on.", EResult.k_EResultTimeout or EResult.k_EResultServiceUnavailable => "The Workshop didn't answer; try again later.", _ => "", }; private static int Fail(string message) { Console.Error.WriteLine(message); return 4; } private static string Indent(string text) => string.Join("\n", text.Split('\n').Select(l => " " + l.TrimEnd('\r'))); private sealed class Options { public const string Usage = "Usage: WorkshopUpload (--item | --create --id-file ) [--content ] [--note-file ]\n" + " [--tags Mod,1.7] [--title ] [--preview ] [--description-file ]\n" + " [--visibility public|friends|private|unlisted] [--timeout ] [--publish]\n" + "Without --publish it calls no Steam write API: it checks the login and the RimWorld license, and with --item\n" + "reads the item and checks ownership. With --item and only --description-file (title, preview and visibility\n" + "optional) --publish replaces the description and nothing else. --create --publish creates a new item, writes\n" + "its id to --id-file at once, then uploads; it needs --title, --content, --note-file, --description-file and\n" + "--preview. --create, also without --publish, first refuses if this account has an item with the same title\n" + "or with no title (an earlier create that was cut off). Without --visibility the item keeps its visibility\n" + "(a new item gets Steam's default)."; public ulong Item; public bool Create; public string Content, NoteFile, DescriptionFile, Title, Preview, IdFile; public List Tags; public ERemoteStoragePublishedFileVisibility? Visibility; public TimeSpan Timeout = TimeSpan.FromMinutes(15); public bool Publish; public static Options Parse(string[] args) { var o = new Options(); for (int i = 0; i < args.Length; i++) { string Next() => i + 1 < args.Length ? args[++i] : throw new ArgumentException($"{args[i]} needs a value."); switch (args[i]) { case "--item": if (!ulong.TryParse(Next(), out o.Item)) throw new ArgumentException("--item must be a number."); break; case "--create": o.Create = true; break; case "--id-file": o.IdFile = Path.GetFullPath(Next()); break; case "--content": o.Content = Path.GetFullPath(Next()); break; case "--note-file": o.NoteFile = ExistingFile(Next()); break; case "--description-file": o.DescriptionFile = ExistingFile(Next()); break; case "--tags": o.Tags = Next().Split(',').Select(t => t.Trim()).Where(t => t.Length > 0).ToList(); break; case "--title": o.Title = Next().Trim(); if (o.Title.Length == 0) throw new ArgumentException("--title is empty."); break; case "--preview": o.Preview = Path.GetFullPath(Next()); break; case "--visibility": o.Visibility = ParseVisibility(Next()); break; case "--timeout": o.Timeout = TimeSpan.FromSeconds(int.Parse(Next())); break; case "--publish": o.Publish = true; break; default: throw new ArgumentException($"Unknown argument {args[i]}."); } } if (o.Create && o.Item != 0) throw new ArgumentException("--item and --create don't go together."); if (!o.Create && o.Item == 0) throw new ArgumentException("--item or --create is required."); if (o.Create) { if (o.IdFile == null) throw new ArgumentException("--create needs --id-file, where the new item's id goes."); if (!Directory.Exists(Path.GetDirectoryName(o.IdFile))) throw new ArgumentException($"No folder for --id-file {o.IdFile}."); if (o.Title == null) throw new ArgumentException("--create needs --title."); if (o.Publish && (o.Content == null || o.NoteFile == null || o.DescriptionFile == null || o.Preview == null)) throw new ArgumentException("--create --publish needs --content, --note-file, --description-file and --preview."); } else if (o.IdFile != null) throw new ArgumentException("--id-file goes with --create."); return o; } private static ERemoteStoragePublishedFileVisibility ParseVisibility(string value) => value.ToLowerInvariant() switch { "public" => ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityPublic, "friends" => ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityFriendsOnly, "private" => ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityPrivate, "unlisted" => ERemoteStoragePublishedFileVisibility.k_ERemoteStoragePublishedFileVisibilityUnlisted, _ => throw new ArgumentException($"--visibility must be public, friends, private or unlisted, not {value}."), }; private static string ExistingFile(string path) { string full = Path.GetFullPath(path); if (!File.Exists(full)) throw new ArgumentException($"No file at {full}."); return full; } } }