Exemplo n.º 1
0
        public static bool BuyUpgrade(Dictionary <string, object> userArgs)
        {
            try {
                string upgrade = "";

                if (userArgs.ContainsKey("upgrade"))
                {
                    upgrade = (string)userArgs["upgrade"];
                }
                else
                {
                    throw new Exception("You must specify a valid 'upgrade' value.");
                }

                foreach (var upg in Shiftorium.GetAvailable())
                {
                    if (upg.ID == upgrade)
                    {
                        Shiftorium.Buy(upgrade, upg.Cost);
                        return(true);
                    }
                }

                throw new Exception($"Couldn't find upgrade with ID: {upgrade}");
            } catch {
                return(false);
            }
        }
Exemplo n.º 2
0
        public static bool BuyUpgrade(Dictionary <string, object> userArgs)
        {
            try
            {
                string upgrade = "";

                upgrade = (string)userArgs["upgrade"];

                var upg = Shiftorium.GetAvailable().FirstOrDefault(x => x.ID == upgrade);
                if (upg != null)
                {
                    if (!Shiftorium.Buy(upg.ID, upg.Cost) == true)
                    {
                        Console.WriteLine("{ERR_NOTENOUGHCODEPOINTS}");
                    }
                }
                else
                {
                    Console.WriteLine("{ERR_NOUPGRADE}");
                }
            }
            catch
            {
                Console.WriteLine("{ERR_GENERAL}");
            }
            return(true);
        }
Exemplo n.º 3
0
        public static bool ViewInfo(Dictionary <string, object> userArgs)
        {
            try
            {
                string upgrade = "";

                upgrade = (string)userArgs["upgrade"];

                foreach (var upg in Shiftorium.GetDefaults())
                {
                    if (upg.ID == upgrade)
                    {
                        Console.WriteLine(Localization.Parse("{COM_UPGRADEINFO}", new Dictionary <string, string>
                        {
                            ["%id"]          = upg.ID,
                            ["%category"]    = upg.Category,
                            ["%name"]        = upg.Name,
                            ["%cost"]        = upg.Cost.ToString(),
                            ["%description"] = upg.Description
                        }));

                        return(true);
                    }
                }

                throw new Exception("{ERR_NOUPGRADE}");
            }
            catch
            {
                return(false);
            }
        }
Exemplo n.º 4
0
        public static bool Commands()
        {
            var sb = new StringBuilder();

            sb.AppendLine("{GEN_COMMANDS}");
            sb.AppendLine("=================");
            sb.AppendLine();
            //print all unique namespaces.
            foreach (var n in TerminalBackend.Commands.Where(x => !(x is TerminalBackend.WinOpenCommand) && Shiftorium.UpgradeInstalled(x.Dependencies) && x.CommandInfo.hide == false).OrderBy(x => x.CommandInfo.name))
            {
                sb.Append(" - " + n.CommandInfo.name);
                if (!string.IsNullOrWhiteSpace(n.CommandInfo.description))
                {
                    if (Shiftorium.UpgradeInstalled("help_description"))
                    {
                        sb.Append(" - " + n.CommandInfo.description);
                    }
                }
                sb.AppendLine();
            }

            Console.WriteLine(sb.ToString());

            return(true);
        }
Exemplo n.º 5
0
        public static bool ListAll()
        {
            try {
                Dictionary <string, int> upgrades = new Dictionary <string, int>();
                int maxLength = 5;

                foreach (var upg in Shiftorium.GetAvailable())
                {
                    if (upg.ID.Length > maxLength)
                    {
                        maxLength = upg.ID.Length;
                    }

                    upgrades.Add(upg.ID, upg.Cost);
                }

                Console.WriteLine("ID".PadRight((maxLength + 5) - 2) + "Cost (Codepoints)");

                foreach (var upg in upgrades)
                {
                    Console.WriteLine(upg.Key.PadRight((maxLength + 5) - upg.Key.Length) + "  " + upg.Value.ToString());
                }
                return(true);
            } catch (Exception e) {
                CrashHandler.Start(e);
                return(false);
            }
        }
Exemplo n.º 6
0
 public static bool GetAllUpgrades()
 {
     foreach (var upg in Shiftorium.GetDefaults())
     {
         Shiftorium.Buy(upg.ID, 0);
     }
     return(true);
 }
Exemplo n.º 7
0
        public static bool Status()
        {
            Console.WriteLine($@"ShiftOS version {Assembly.GetExecutingAssembly().GetName().Version.ToString()}

Codepoints:       {SaveSystem.CurrentSave.Codepoints}
Upgrades:         {SaveSystem.CurrentSave.CountUpgrades()} installed,
                  {Shiftorium.GetAvailable().Length} available");
            return(true);
        }
Exemplo n.º 8
0
 /// <summary>
 /// Creates a new save, starting the Out Of Box Experience (OOBE).
 /// </summary>
 public static void NewSave()
 {
     AppearanceManager.Invoke(new Action(() =>
     {
         CurrentSave            = new Save();
         CurrentSave.Codepoints = 0;
         CurrentSave.Upgrades   = new Dictionary <string, bool>();
         Shiftorium.Init();
         oobe.Start(CurrentSave);
     }));
 }
Exemplo n.º 9
0
 public static bool ListCategories()
 {
     foreach (var cat in Shiftorium.GetCategories())
     {
         Console.WriteLine(Localization.Parse("{SHFM_CATEGORY}", new Dictionary <string, string>
         {
             ["%name"]      = cat,
             ["%available"] = Shiftorium.GetAvailable().Where(x => x.Category == cat).Count().ToString()
         }));
     }
     return(true);
 }
Exemplo n.º 10
0
 public static bool Programs()
 {
     Console.WriteLine("{GEN_PROGRAMS}");
     Console.WriteLine("===============");
     Console.WriteLine();
     foreach (var cmd in TerminalBackend.Commands.Where(x => x is TerminalBackend.WinOpenCommand && Shiftorium.UpgradeInstalled(x.Dependencies)).OrderBy(x => x.CommandInfo.name))
     {
         Console.Write(" - " + cmd.CommandInfo.name);
         if (!string.IsNullOrWhiteSpace(cmd.CommandInfo.description))
         {
             if (Shiftorium.UpgradeInstalled("help_description"))
             {
                 Console.Write(": " + cmd.CommandInfo.description);
             }
         }
         Console.WriteLine();
     }
     return(true);
 }
Exemplo n.º 11
0
        /// <summary>
        /// Runs a command on the client.
        /// </summary>
        /// <param name="text">The command text.</param>
        /// <param name="args">The command arguments.</param>
        /// <param name="isRemote">Whether the command should be run in RTS.</param>
        /// <returns>Whether the command ran successfully.</returns>
        public static bool RunClient(string text, Dictionary <string, object> args, bool isRemote = false)
        {
            latestCommmand = text;

            //Console.WriteLine(text + " " + "{" + string.Join(",", args.Select(kv => kv.Key + "=" + kv.Value).ToArray()) + "}" + " " + isRemote);


            var cmd = Commands.FirstOrDefault(x => Localization.Parse(x.CommandInfo.name) == text);

            if (cmd == null)
            {
                return(false);
            }
            if (!Shiftorium.UpgradeInstalled(cmd.Dependencies))
            {
                return(false);
            }
            bool res = false;

            foreach (var arg in cmd.RequiredArguments)
            {
                if (!args.ContainsKey(arg))
                {
                    res = true;
                    Console.WriteLine("You are missing an argument with the key \"" + arg + "\".");
                }
            }
            if (res == true)
            {
                return(true);
            }
            try
            {
                cmd.Invoke(args);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Command error: " + ex.Message);
            }

            return(true);
        }
Exemplo n.º 12
0
        public static bool Status()
        {
            string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();

            string cp        = SaveSystem.CurrentSave.Codepoints.ToString();
            string installed = SaveSystem.CurrentSave.CountUpgrades().ToString();
            string available = Shiftorium.GetAvailable().Length.ToString();

            Console.WriteLine(Localization.Parse("{COM_STATUS}", new Dictionary <string, string>
            {
                ["%cp"]        = cp,
                ["%version"]   = version,
                ["%installed"] = installed,
                ["%available"] = available
            }));
            Console.WriteLine("{GEN_OBJECTIVES}");
            try
            {
                if (Story.CurrentObjectives.Count > 0)
                {
                    foreach (var obj in Story.CurrentObjectives)
                    {
                        Console.WriteLine(obj.Name);
                        Console.WriteLine("-------------------------------");
                        Console.WriteLine();
                        Console.WriteLine(obj.Description);
                    }
                }
                else
                {
                    Console.WriteLine("{RES_NOOBJECTIVES}");
                }
            }
            catch
            {
                Console.WriteLine("{RES_NOOBJECTIVES}");
            }
            return(true);
        }
Exemplo n.º 13
0
        public static bool ViewInfo(Dictionary <string, object> userArgs)
        {
            try {
                string upgrade = "";

                if (userArgs.ContainsKey("upgrade"))
                {
                    upgrade = (string)userArgs["upgrade"];
                }
                else
                {
                    throw new Exception("You must specify a valid 'upgrade' value.");
                }

                foreach (var upg in Shiftorium.GetDefaults())
                {
                    if (upg.ID == upgrade)
                    {
                        Console.WriteLine($@"Information for {upgrade}:

{upg.Name} - {upg.Cost} Codepoints
------------------------------------------------------

{upg.Description}

To buy this upgrade, run:
shiftorium.buy{{upgrade:""{upg.ID}""}}");
                        return(true);
                    }
                }

                throw new Exception($"Couldn't find upgrade with ID: {upgrade}");
            } catch {
                return(false);
            }
        }
Exemplo n.º 14
0
        internal static IVirus CreateVirus(string id, int threatlevel)
        {
            if (threatlevel < 1)
            {
                throw new Exception("Threat level can't be below 1.");
            }
            if (threatlevel > 4)
            {
                throw new Exception("Threat level can't be above 4.");
            }

            foreach (var type in ReflectMan.Types.Where(x => x.GetInterfaces().Contains(typeof(IVirus)) && Shiftorium.UpgradeAttributesUnlocked(x)))
            {
                var attrib = type.GetCustomAttributes(false).FirstOrDefault(x => x is VirusAttribute) as VirusAttribute;
                if (attrib != null)
                {
                    if (attrib.ID == id)
                    {
                        IVirus virus = (IVirus)Activator.CreateInstance(type);
                        virus.Infect(threatlevel);
                        return(virus);
                    }
                }
            }

            throw new Exception("Cannot create virus.");
        }
Exemplo n.º 15
0
        public static bool ListAll(Dictionary <string, object> args)
        {
            try
            {
                bool showOnlyInCategory = false;

                string cat = "Other";

                if (args.ContainsKey("cat"))
                {
                    showOnlyInCategory = true;
                    cat = args["cat"].ToString();
                }

                Dictionary <string, ulong> upgrades = new Dictionary <string, ulong>();
                int maxLength = 5;

                IEnumerable <ShiftoriumUpgrade> upglist = Shiftorium.GetAvailable();
                if (showOnlyInCategory)
                {
                    if (Shiftorium.IsCategoryEmptied(cat))
                    {
                        ConsoleEx.Bold            = true;
                        ConsoleEx.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("{SHFM_QUERYERROR}");
                        Console.WriteLine();
                        ConsoleEx.Bold            = false;
                        ConsoleEx.ForegroundColor = ConsoleColor.Gray;
                        Console.WriteLine("{ERR_EMPTYCATEGORY}");
                        return(true);
                    }
                    upglist = Shiftorium.GetAvailable().Where(x => x.Category == cat);
                }


                if (upglist.Count() == 0)
                {
                    ConsoleEx.Bold            = true;
                    ConsoleEx.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("{SHFM_NOUPGRADES}");
                    Console.WriteLine();
                    ConsoleEx.Bold            = false;
                    ConsoleEx.ForegroundColor = ConsoleColor.Gray;
                    Console.WriteLine("{ERR_NOMOREUPGRADES}");
                    return(true);
                }
                foreach (var upg in upglist)
                {
                    if (upg.ID.Length > maxLength)
                    {
                        maxLength = upg.ID.Length;
                    }

                    upgrades.Add(upg.ID, upg.Cost);
                }

                foreach (var upg in upgrades)
                {
                    Console.WriteLine(Localization.Parse("{SHFM_UPGRADE}", new Dictionary <string, string>
                    {
                        ["%id"]   = upg.Key,
                        ["%cost"] = upg.Value.ToString()
                    }));
                }
                return(true);
            }
            catch (Exception e)
            {
                CrashHandler.Start(e);
                return(false);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Start the entire ShiftOS engine.
        /// </summary>
        /// <param name="useDefaultUI">Whether ShiftOS should initiate it's Windows Forms front-end.</param>
        public static void Begin(bool useDefaultUI = true)
        {
            if (!System.IO.File.Exists(Paths.SaveFile))
            {
                var root = new ShiftOS.Objects.ShiftFS.Directory();
                root.Name        = "System";
                root.permissions = Permissions.All;
                System.IO.File.WriteAllText(Paths.SaveFile, JsonConvert.SerializeObject(root));
            }


            if (Utils.Mounts.Count == 0)
            {
                Utils.Mount(System.IO.File.ReadAllText(Paths.SaveFile));
            }
            Paths.Init();

            Localization.SetupTHETRUEDefaultLocals();
            SkinEngine.Init();

            TerminalBackend.OpenTerminal();

            TerminalBackend.InStory = true;
            var thread = new Thread(new ThreadStart(() =>
            {
                //Do not uncomment until I sort out the copyright stuff... - Michael
                //AudioManager.Init();

                var defaultConf = new EngineConfig();
                if (System.IO.File.Exists("engineconfig.json"))
                {
                    defaultConf = JsonConvert.DeserializeObject <EngineConfig>(System.IO.File.ReadAllText("engineconfig.json"));
                }
                else
                {
                    System.IO.File.WriteAllText("engineconfig.json", JsonConvert.SerializeObject(defaultConf, Formatting.Indented));
                }

                Thread.Sleep(350);
                Console.WriteLine("Initiating kernel...");
                Thread.Sleep(250);
                Console.WriteLine("Reading filesystem...");
                Thread.Sleep(100);
                Console.WriteLine("Reading configuration...");

                Console.WriteLine("{CONNECTING_TO_MUD}");

                if (defaultConf.ConnectToMud == true)
                {
                    try
                    {
                        bool guidReceived           = false;
                        ServerManager.GUIDReceived += (str) =>
                        {
                            guidReceived = true;
                            Console.WriteLine("{CONNECTION_SUCCESSFUL}");
                        };

                        ServerManager.Initiate("secondary4162.cloudapp.net", 13370);
                        while (guidReceived == false)
                        {
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("{ERROR}: " + ex.Message);
                        Thread.Sleep(3000);
                        ServerManager.StartLANServer();
                    }
                }
                else
                {
                    ServerManager.StartLANServer();
                }

                ServerManager.MessageReceived += (msg) =>
                {
                    if (msg.Name == "mud_savefile")
                    {
                        CurrentSave = JsonConvert.DeserializeObject <Save>(msg.Contents);
                    }
                    else if (msg.Name == "mud_login_denied")
                    {
                        oobe.PromptForLogin();
                    }
                };

                ReadSave();

                while (CurrentSave == null)
                {
                }

                Shiftorium.Init();

                while (CurrentSave.StoryPosition < 5)
                {
                }

                Thread.Sleep(75);



                if (Shiftorium.UpgradeInstalled("desktop"))
                {
                    Console.Write("{START_DESKTOP}");

                    Thread.Sleep(50);
                    Console.WriteLine("   ...{DONE}.");
                }

                Story.Start();


                Thread.Sleep(50);
                Console.WriteLine("{SYSTEM_INITIATED}");

                TerminalBackend.InStory        = false;
                Shiftorium.LogOrphanedUpgrades = true;
                Desktop.InvokeOnWorkerThread(new Action(() => Desktop.PopulateAppLauncher()));
                GameReady?.Invoke();
            }));

            thread.IsBackground = true;
            thread.Start();
        }
Exemplo n.º 17
0
 /// <summary>
 /// Opens a file from the specified ShiftFS path.
 /// </summary>
 /// <param name="path">The path to open.</param>
 public static void OpenFile(string path)
 {
     if (!Objects.ShiftFS.Utils.FileExists(path))
     {
         throw new System.IO.FileNotFoundException("ShiftFS could not find the file specified.", path);
     }
     foreach (var type in ReflectMan.Types.Where(x => x.GetInterfaces().Contains(typeof(IFileHandler)) && Shiftorium.UpgradeAttributesUnlocked(x)))
     {
         foreach (FileHandlerAttribute attrib in type.GetCustomAttributes(false).Where(x => x is FileHandlerAttribute))
         {
             if (path.ToLower().EndsWith(attrib.Extension))
             {
                 var obj = (IFileHandler)Activator.CreateInstance(type);
                 obj.OpenFile(path);
             }
         }
     }
 }
Exemplo n.º 18
0
        /// <summary>
        /// Pulls a list of all available App Launcher items.
        /// </summary>
        /// <returns>A <see cref="List{LauncherItem}"/> containing all available App Launcher items.</returns>
        public static List <LauncherItem> Available()
        {
            List <LauncherItem> win = new List <LauncherItem>();

            foreach (var type in Array.FindAll(ReflectMan.Types, t => t.GetInterfaces().Contains(typeof(IShiftOSWindow)) && Shiftorium.UpgradeAttributesUnlocked(t)))
            {
                foreach (var attr in type.GetCustomAttributes(false))
                {
                    if (!(attr is MultiplayerOnlyAttribute && !KernelWatchdog.MudConnected))
                    {
                        if (attr is LauncherAttribute)
                        {
                            var launch = attr as LauncherAttribute;
                            if (launch.UpgradeInstalled)
                            {
                                var data = new LauncherItem {
                                    DisplayData = launch, LaunchType = type
                                };
                                data.DisplayData.Category = Localization.Parse(data.DisplayData.Category);
                                data.DisplayData.Name     = Localization.Parse(data.DisplayData.Name);
                                win.Add(data);
                            }
                        }
                    }
                }
            }

            foreach (var file in Utils.GetFiles(Paths.GetPath("applauncher")))
            {
                if (file.EndsWith(".al"))
                {
                    var item = JsonConvert.DeserializeObject <LuaLauncherItem>(Utils.ReadAllText(file));
                    win.Add(item);
                }
            }
            return(win);
        }
Exemplo n.º 19
0
        public static bool Help()
        {
            var asm = Assembly.GetExecutingAssembly();

            var types = asm.GetTypes();

            foreach (var type in types)
            {
                if (Shiftorium.UpgradeAttributesUnlocked(type))
                {
                    foreach (var a in type.GetCustomAttributes(false))
                    {
                        if (a is Namespace)
                        {
                            var ns = a as Namespace;

                            if (!ns.hide)
                            {
                                string descp = "{NAMESPACE_" + ns.name.ToUpper() + "_DESCRIPTION}";
                                if (descp == Localization.Parse(descp))
                                {
                                    descp = "";
                                }
                                else
                                {
                                    descp = Shiftorium.UpgradeInstalled("help_description") ? Localization.Parse("{SEPERATOR}" + descp) : "";
                                }

                                Console.WriteLine($"{{NAMESPACE}}{ns.name}" + descp);

                                foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static))
                                {
                                    if (Shiftorium.UpgradeAttributesUnlocked(method))
                                    {
                                        foreach (var ma in method.GetCustomAttributes(false))
                                        {
                                            if (ma is Command)
                                            {
                                                var cmd = ma as Command;

                                                if (!cmd.hide)
                                                {
                                                    string descriptionparse = "{COMMAND_" + ns.name.ToUpper() + "_" + cmd.name.ToUpper() + "_DESCRIPTION}";
                                                    string usageparse       = "{COMMAND_" + ns.name.ToUpper() + "_" + cmd.name.ToUpper() + "_USAGE}";
                                                    if (descriptionparse == Localization.Parse(descriptionparse))
                                                    {
                                                        descriptionparse = "";
                                                    }
                                                    else
                                                    {
                                                        descriptionparse = Shiftorium.UpgradeInstalled("help_description") ? Localization.Parse("{SEPERATOR}" + descriptionparse) : "";
                                                    }

                                                    if (usageparse == Localization.Parse(usageparse))
                                                    {
                                                        usageparse = "";
                                                    }
                                                    else
                                                    {
                                                        usageparse = Shiftorium.UpgradeInstalled("help_usage") ? Localization.Parse("{SEPERATOR}" + usageparse, new Dictionary <string, string>()
                                                        {
                                                            { "%ns", ns.name },
                                                            { "%cmd", cmd.name }
                                                        }) : "";
                                                    }

                                                    Console.WriteLine($"{{COMMAND}}{ns.name}.{cmd.name}" + usageparse + descriptionparse);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(true);
        }
Exemplo n.º 20
0
 /// <summary>
 /// Gets a list of all <see cref="IStatusIcon"/> objects that meet their Shiftorium dependencies.
 /// </summary>
 /// <returns>An array of <see cref="Type"/>s containing the found objects.</returns>
 public static Type[] GetAllStatusIcons()
 {
     return(Array.FindAll(ReflectMan.Types, x => x.GetInterfaces().Contains(typeof(IStatusIcon)) && Shiftorium.UpgradeAttributesUnlocked(x)));
 }
Exemplo n.º 21
0
        private static void delegateToServer(ServerMessage msg)
        {
            string[] split    = msg.GUID.Split('|');
            bool     finished = false;

            if (split[0] == SaveSystem.CurrentSave.SystemName)
            {
                foreach (var type in Array.FindAll(ReflectMan.Types, x => x.GetInterfaces().Contains(typeof(Server)) && Shiftorium.UpgradeAttributesUnlocked(x)))
                {
                    var attrib = type.GetCustomAttributes().FirstOrDefault(x => x is ServerAttribute) as ServerAttribute;
                    if (attrib != null)
                    {
                        if (split[1] == attrib.Port.ToString())
                        {
                            type.GetMethods(BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(x => x.Name == "MessageReceived")?.Invoke(Activator.CreateInstance(type), null);
                            finished = true;
                        }
                    }
                }
            }
            if (finished == false)
            {
                Forward(split[2], "Error", $"{split[0]}:{split[1]}: connection refused");
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Finish bootstrapping the engine.
        /// </summary>
        private static void FinishBootstrap()
        {
            ServerMessageReceived savehandshake = null;

            savehandshake = (msg) =>
            {
                if (msg.Name == "mud_savefile")
                {
                    ServerManager.MessageReceived -= savehandshake;
                    try
                    {
                        CurrentSave = JsonConvert.DeserializeObject <Save>(msg.Contents);
                    }
                    catch
                    {
                        Console.WriteLine("{ENGINE_CANNOTLOADSAVE}");
                        oobe.PromptForLogin();
                    }
                }
                else if (msg.Name == "mud_login_denied")
                {
                    ServerManager.MessageReceived -= savehandshake;
                    oobe.PromptForLogin();
                }
            };
            ServerManager.MessageReceived += savehandshake;


            ReadSave();

            while (CurrentSave == null)
            {
                Thread.Sleep(10);
            }

            Shiftorium.Init();

            while (CurrentSave.StoryPosition < 1)
            {
                Thread.Sleep(10);
            }

            Thread.Sleep(75);

            Thread.Sleep(50);
            Console.WriteLine("{MISC_ACCEPTINGLOGINS}");

Sysname:
            bool waitingForNewSysName = false;
            bool gobacktosysname = false;

            if (string.IsNullOrWhiteSpace(CurrentSave.SystemName))
            {
                Infobox.PromptText("{TITLE_ENTERSYSNAME}", "{PROMPT_ENTERSYSNAME}", (name) =>
                {
                    if (string.IsNullOrWhiteSpace(name))
                    {
                        Infobox.Show("{TITLE_INVALIDNAME}", "{PROMPT_INVALIDNAME}.", () =>
                        {
                            gobacktosysname      = true;
                            waitingForNewSysName = false;
                        });
                    }
                    else if (name.Length < 5)
                    {
                        Infobox.Show("{TITLE_VALUESMALL}", "{PROMPT_SMALLSYSNAME}", () =>
                        {
                            gobacktosysname      = true;
                            waitingForNewSysName = false;
                        });
                    }
                    else
                    {
                        CurrentSave.SystemName = name;
                        SaveSystem.SaveGame();
                        gobacktosysname      = false;
                        waitingForNewSysName = false;
                    }
                });
            }

            while (waitingForNewSysName)
            {
                Thread.Sleep(10);
            }

            if (gobacktosysname)
            {
                goto Sysname;
            }

            if (CurrentSave.Users == null)
            {
                CurrentSave.Users = new List <ClientSave>();
            }

            Console.WriteLine($@"
                   `-:/++++::.`                   
              .+ydNMMMMMNNMMMMMNhs/.              
           /yNMMmy+:-` `````.-/ohNMMms-           
        `oNMMh/.`:oydmNMMMMNmhs+- .+dMMm+`             {{GEN_WELCOME}}
      `oMMmo``+dMMMMMMMMMMMMMMMMMNh/`.sNMN+       
     :NMN+ -yMMMMMMMNdhyssyyhdmNMMMMNs``sMMd.          {{GEN_SYSTEMSTATUS}}
    oMMd.`sMMMMMMd+.            `/MMMMN+ -mMN:         ----------------------
   oMMh .mMMMMMM/     `-::::-.`  :MMMMMMh`.mMM:   
  :MMd .NMMMMMMs    .dMMMMMMMMMNddMMMMMMMd`.NMN.        {{GEN_CODEPOINTS}}:     {SaveSystem.CurrentSave.Codepoints}
  mMM. dMMMMMMMo    -mMMMMMMMMMMMMMMMMMMMMs /MMy        
 :MMh :MMMMMMMMm`     .+shmMMMMMMMMMMMMMMMN` NMN`                       
 oMM+ sMMMMMMMMMN+`        `-/smMMMMMMMMMMM: hMM:       
 sMM+ sMMMMMMMMMMMMds/-`        .sMMMMMMMMM/ yMM/ 
 +MMs +MMMMMMMMMMMMMMMMMmhs:`     +MMMMMMMM- dMM-       {{GEN_SYSTEMNAME}}:    {CurrentSave.SystemName.ToUpper()}
 .MMm `NMMMMMMMMMMMMMMMMMMMMMo    `NMMMMMMd .MMN        {{GEN_USERS}}:          {Users.Count()}.
  hMM+ +MMMMMMmsdNMMMMMMMMMMN/    -MMMMMMN- yMM+        
  `NMN- oMMMMMd   `-/+osso+-     .mMMMMMN: +MMd   
   -NMN: /NMMMm`               :yMMMMMMm- oMMd`   
    -mMMs``sMMMMNdhso++///+oydNMMMMMMNo .hMMh`    
     `yMMm/ .omMMMMMMMMMMMMMMMMMMMMd+``oNMNo      
       -hMMNo. -ohNMMMMMMMMMMMMmy+. -yNMNy`       
         .sNMMms/. `-/+++++/:-` ./yNMMmo`         
            :sdMMMNdyso+++ooshdNMMMdo-            
               `:+yhmNNMMMMNNdhs+-                
                       ````                       ");

            if (CurrentSave.Users.Count == 0)
            {
                CurrentSave.Users.Add(new ClientSave
                {
                    Username    = "******",
                    Password    = "",
                    Permissions = UserPermissions.Root
                });
                Console.WriteLine("{MISC_NOUSERS}");
            }
            TerminalBackend.InStory = false;

            TerminalBackend.PrefixEnabled = false;

            if (LoginManager.ShouldUseGUILogin)
            {
                Action <ClientSave> Completed = null;
                Completed += (user) =>
                {
                    CurrentUser = user;
                    LoginManager.LoginComplete -= Completed;
                };
                LoginManager.LoginComplete += Completed;
                Desktop.InvokeOnWorkerThread(() =>
                {
                    LoginManager.PromptForLogin();
                });
                while (CurrentUser == null)
                {
                    Thread.Sleep(10);
                }
            }
            else
            {
Login:
                string username = "";
                int  progress           = 0;
                bool goback             = false;
                TextSentEventHandler ev = null;
                string loginstr         = Localization.Parse("{GEN_LPROMPT}", new Dictionary <string, string>
                {
                    ["%sysname"] = CurrentSave.SystemName
                });
                ev = (text) =>
                {
                    if (progress == 0)
                    {
                        string getuser = text.Remove(0, loginstr.Length);
                        if (!string.IsNullOrWhiteSpace(getuser))
                        {
                            if (CurrentSave.Users.FirstOrDefault(x => x.Username == getuser) == null)
                            {
                                Console.WriteLine();
                                Console.WriteLine("{ERR_NOUSER}");
                                goback = true;
                                progress++;
                                TerminalBackend.TextSent -= ev;
                                return;
                            }
                            username = getuser;
                            progress++;
                        }
                        else
                        {
                            Console.WriteLine();
                            Console.WriteLine("{ERR_NOUSER}");
                            TerminalBackend.TextSent -= ev;
                            goback = true;
                            progress++;
                        }
                    }
                    else if (progress == 1)
                    {
                        string passwordstr = Localization.Parse("{GEN_PASSWORD}: ");
                        string getpass     = text.Remove(0, passwordstr.Length);
                        var    user        = CurrentSave.Users.FirstOrDefault(x => x.Username == username);
                        if (user.Password == getpass)
                        {
                            Console.WriteLine();
                            Console.WriteLine("{GEN_WELCOME}");
                            CurrentUser = user;
                            progress++;
                        }
                        else
                        {
                            Console.WriteLine();
                            Console.WriteLine("{RES_DENIED}");
                            goback = true;
                            progress++;
                        }
                        TerminalBackend.TextSent -= ev;
                    }
                };
                TerminalBackend.TextSent += ev;
                Console.WriteLine();
                Console.Write(loginstr);
                ConsoleEx.Flush();
                while (progress == 0)
                {
                    Thread.Sleep(10);
                }
                if (goback)
                {
                    goto Login;
                }
                Console.WriteLine();
                Console.Write("{GEN_PASSWORD}: ");
                ConsoleEx.Flush();
                while (progress == 1)
                {
                    Thread.Sleep(10);
                }
                if (goback)
                {
                    goto Login;
                }
            }
            TerminalBackend.PrefixEnabled  = true;
            Shiftorium.LogOrphanedUpgrades = true;
            Desktop.InvokeOnWorkerThread(new Action(() =>
            {
                ShiftOS.Engine.Scripting.LuaInterpreter.RunSft(Paths.GetPath("kernel.sft"));
            }));


            Desktop.InvokeOnWorkerThread(new Action(() => Desktop.PopulateAppLauncher()));
            GameReady?.Invoke();

            if (!string.IsNullOrWhiteSpace(CurrentSave.PickupPoint))
            {
                try
                {
                    if (Story.Context == null)
                    {
                        Story.Start(CurrentSave.PickupPoint);
                    }
                }
                catch { }
            }
        }
Exemplo n.º 23
0
        public static bool Open(Dictionary <string, object> args)
        {
            try
            {
                if (args.ContainsKey("app"))
                {
                    var app = args["app"] as string;
                    //ANNND now we start reflecting...
                    foreach (var asmExec in System.IO.Directory.GetFiles(Environment.CurrentDirectory))
                    {
                        if (asmExec.EndsWith(".exe") || asmExec.EndsWith(".dll"))
                        {
                            var asm = Assembly.LoadFile(asmExec);

                            foreach (var type in asm.GetTypes())
                            {
                                if (type.BaseType == typeof(UserControl))
                                {
                                    foreach (var attr in type.GetCustomAttributes(false))
                                    {
                                        if (attr is WinOpenAttribute)
                                        {
                                            if (app == (attr as WinOpenAttribute).ID)
                                            {
                                                if (SaveSystem.CurrentSave.Upgrades.ContainsKey(app))
                                                {
                                                    if (Shiftorium.UpgradeInstalled(app))
                                                    {
                                                        IShiftOSWindow frm = Activator.CreateInstance(type) as IShiftOSWindow;
                                                        AppearanceManager.SetupWindow(frm);
                                                        return(true);
                                                    }
                                                    else
                                                    {
                                                        throw new Exception($"{app} was not found on your system! Try looking in the shiftorium...");
                                                    }
                                                }
                                                else
                                                {
                                                    IShiftOSWindow frm = Activator.CreateInstance(type) as IShiftOSWindow;
                                                    AppearanceManager.SetupWindow(frm);
                                                    return(true);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Please specify a valid 'app' param.");
                    return(true);
                }
                Console.WriteLine("Couldn't find the specified app on your system.");
                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error running script:" + ex);
                return(false);
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Start the entire ShiftOS engine.
        /// </summary>
        /// <param name="useDefaultUI">Whether ShiftOS should initiate it's Windows Forms front-end.</param>
        public static void Begin(bool useDefaultUI = true)
        {
            AppDomain.CurrentDomain.UnhandledException += (o, a) =>
            {
                CrashHandler.Start((Exception)a.ExceptionObject);
            };

            if (!System.IO.File.Exists(Paths.SaveFile))
            {
                var root = new ShiftOS.Objects.ShiftFS.Directory();
                root.Name        = "System";
                root.permissions = UserPermissions.Guest;
                System.IO.File.WriteAllText(Paths.SaveFile, JsonConvert.SerializeObject(root));
            }

            if (Utils.Mounts.Count == 0)
            {
                Utils.Mount(System.IO.File.ReadAllText(Paths.SaveFile));
            }
            Paths.Init();

            Localization.SetupTHETRUEDefaultLocals();
            SkinEngine.Init();
            Random rnd          = new Random();
            int    loadingJoke1 = rnd.Next(10);
            int    loadingJoke2 = rnd.Next(11);

            TerminalBackend.OpenTerminal();

            TerminalBackend.InStory = true;
            var thread = new Thread(new ThreadStart(() =>
            {
                //Do not uncomment until I sort out the copyright stuff... - Michael
                //AudioManager.Init();

                var defaultConf = new EngineConfig();
                if (System.IO.File.Exists("engineconfig.json"))
                {
                    defaultConf = JsonConvert.DeserializeObject <EngineConfig>(System.IO.File.ReadAllText("engineconfig.json"));
                }
                else
                {
                    System.IO.File.WriteAllText("engineconfig.json", JsonConvert.SerializeObject(defaultConf, Formatting.Indented));
                }

                Thread.Sleep(350);
                Console.WriteLine("{MISC_KERNELVERSION}");
                Thread.Sleep(50);
                Console.WriteLine("Copyright (c) 2018 DevX. Licensed under MIT.");
                Console.WriteLine("");
                Console.WriteLine("THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR");
                Console.WriteLine("IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,");
                Console.WriteLine("FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE");
                Console.WriteLine("AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER");
                Console.WriteLine("LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,");
                Console.WriteLine("OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE");
                Console.WriteLine("SOFTWARE.");
                Console.WriteLine("");
                Thread.Sleep(250);
                Console.WriteLine("{MISC_KERNELBOOTED}");
                Console.WriteLine("{MISC_SHIFTFSDRV}");
                Thread.Sleep(350);
                Console.WriteLine("{MISC_SHIFTFSBLOCKSREAD}");
                Console.WriteLine("{LOADINGMSG1_" + loadingJoke1 + "}");
                Thread.Sleep(500);
                Console.WriteLine("{MISC_LOADINGCONFIG}");
                Thread.Sleep(30);
                Console.WriteLine("{MISC_BUILDINGCMDS}");
                TerminalBackend.PopulateTerminalCommands();

                if (IsSandbox == false)
                {
                    Console.WriteLine("{MISC_CONNECTINGTONETWORK}");

                    Ready.Reset();

                    if (PreDigitalSocietyConnection != null)
                    {
                        PreDigitalSocietyConnection?.Invoke();
                        Ready.WaitOne();
                    }

                    ServerManager.GUIDReceived += (str) =>
                    {
                        //Connection successful! Stop waiting!
                        Console.WriteLine("{MISC_CONNECTIONSUCCESSFUL}");
                        Thread.Sleep(100);
                        Console.WriteLine("{LOADINGMSG2_" + loadingJoke2 + "}");
                        Thread.Sleep(500);
                    };

                    try
                    {
                        if (ServerManager.ServerOnline)
                        {
                            ServerManager.Initiate(UserConfig.Get().DigitalSocietyAddress, UserConfig.Get().DigitalSocietyPort);
                            // This halts the client until the connection is successful.
                            ServerManager.guidReceiveARE.WaitOne();
                            Console.WriteLine("{MISC_DHCPHANDSHAKEFINISHED}");
                        }
                        else
                        {
                            Console.WriteLine("{MISC_NONETWORK}");
                            Console.WriteLine("{LOADINGMSG2_" + loadingJoke2 + "}");
                        }
                        FinishBootstrap();
                    }
                    catch (Exception ex)
                    {
                        // "No errors, this never gets called."
                        Console.WriteLine("[inetd] SEVERE: " + ex.Message);
                        string dest = "Startup Exception " + DateTime.Now.ToString().Replace("/", "-").Replace(":", "-") + ".txt";
                        System.IO.File.WriteAllText(dest, ex.ToString());
                        Console.WriteLine("[inetd] Full exception details have been saved to: " + dest);
                        Thread.Sleep(3000);
                        System.Diagnostics.Process.GetCurrentProcess().Kill();
                    }

                    //Nothing happens past this point - but the client IS connected! It shouldn't be stuck in that while loop above.
                }
                else
                {
                    Console.WriteLine("{MISC_SANDBOXMODE}");
                    CurrentSave = new Save
                    {
                        IsSandbox  = true,
                        Username   = "******",
                        Password   = "******",
                        SystemName = "shiftos",
                        Users      = new List <ClientSave>
                        {
                            new ClientSave
                            {
                                Username    = "******",
                                Password    = "",
                                Permissions = 0
                            }
                        },
                        Class                = 0,
                        ID                   = new Guid(),
                        Upgrades             = new Dictionary <string, bool>(),
                        CurrentLegions       = null,
                        IsMUDAdmin           = false,
                        IsPatreon            = false,
                        Language             = "english",
                        LastMonthPaid        = 0,
                        MajorVersion         = 1,
                        MinorVersion         = 0,
                        MusicEnabled         = false,
                        MusicVolume          = 100,
                        MyShop               = "",
                        PasswordHashed       = false,
                        PickupPoint          = "",
                        RawReputation        = 0.0f,
                        Revision             = 0,
                        ShiftnetSubscription = 0,
                        SoundEnabled         = true,
                        StoriesExperienced   = null,
                        StoryPosition        = 0,
                        UniteAuthToken       = "",
                    };

                    CurrentUser = CurrentSave.Users.First();

                    Localization.SetupTHETRUEDefaultLocals();

                    Shiftorium.Init();

                    TerminalBackend.InStory       = false;
                    TerminalBackend.PrefixEnabled = true;

                    Desktop.InvokeOnWorkerThread(new Action(() =>
                    {
                        ShiftOS.Engine.Scripting.LuaInterpreter.RunSft(Paths.GetPath("kernel.sft"));
                    }));


                    Desktop.InvokeOnWorkerThread(new Action(() => Desktop.PopulateAppLauncher()));
                    GameReady?.Invoke();
                }
            }));

            thread.IsBackground = true;
            thread.Start();
        }
Exemplo n.º 25
0
        public static bool RunClient(string text, Dictionary <string, object> args)
        {
            latestCommmand = text;

            foreach (var asmExec in System.IO.Directory.GetFiles(Environment.CurrentDirectory))
            {
                try
                {
                    var asm = Assembly.LoadFile(asmExec);

                    var types = asm.GetTypes();

                    foreach (var type in types)
                    {
                        if (Shiftorium.UpgradeAttributesUnlocked(type))
                        {
                            foreach (var a in type.GetCustomAttributes(false))
                            {
                                if (a is Namespace)
                                {
                                    var ns = a as Namespace;
                                    if (text.Split('.')[0] == ns.name)
                                    {
                                        foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.Static))
                                        {
                                            if (Shiftorium.UpgradeAttributesUnlocked(method))
                                            {
                                                foreach (var ma in method.GetCustomAttributes(false))
                                                {
                                                    if (ma is Command)
                                                    {
                                                        var cmd = ma as Command;
                                                        if (text.Split('.')[1] == cmd.name)
                                                        {
                                                            var attr = method.GetCustomAttribute <CommandObsolete>();

                                                            if (attr != null)
                                                            {
                                                                string newcommand = attr.newcommand;
                                                                if (attr.warn)
                                                                {
                                                                    Console.WriteLine(Localization.Parse((newcommand == "" ? "{ERROR}" : "{WARN}") + attr.reason, new Dictionary <string, string>()
                                                                    {
                                                                        { "%newcommand", newcommand }
                                                                    }));
                                                                }
                                                                if (newcommand != "")
                                                                {
                                                                    // redo the entire process running newcommand

                                                                    return(RunClient(newcommand, args));
                                                                }
                                                            }

                                                            var requiresArgs = method.GetCustomAttributes <RequiresArgument>();

                                                            bool error         = false;
                                                            bool providedusage = false;

                                                            foreach (RequiresArgument argument in requiresArgs)
                                                            {
                                                                if (!args.ContainsKey(argument.argument))
                                                                {
                                                                    if (!providedusage)
                                                                    {
                                                                        string usageparse = "{COMMAND_" + ns.name.ToUpper() + "_" + cmd.name.ToUpper() + "_USAGE}";
                                                                        if (usageparse == Localization.Parse(usageparse))
                                                                        {
                                                                            usageparse = "";
                                                                        }
                                                                        else
                                                                        {
                                                                            usageparse = Shiftorium.UpgradeInstalled("help_usage") ? Localization.Parse("{ERROR}{USAGE}" + usageparse, new Dictionary <string, string>()
                                                                            {
                                                                                { "%ns", ns.name },
                                                                                { "%cmd", cmd.name }
                                                                            }) : "";
                                                                        }

                                                                        Console.WriteLine(usageparse);

                                                                        providedusage = true;
                                                                    }

                                                                    if (Shiftorium.UpgradeInstalled("help_usage"))
                                                                    {
                                                                        Console.WriteLine(Localization.Parse("{ERROR_ARGUMENT_REQUIRED}", new Dictionary <string, string>()
                                                                        {
                                                                            { "%argument", argument.argument }
                                                                        }));
                                                                    }
                                                                    else
                                                                    {
                                                                        Console.WriteLine(Localization.Parse("{ERROR_ARGUMENT_REQUIRED_NO_USAGE}"));
                                                                    }

                                                                    error = true;
                                                                }
                                                            }

                                                            if (error)
                                                            {
                                                                throw new Exception("{ERROR_COMMAND_WRONG}");
                                                            }

                                                            try
                                                            {
                                                                return((bool)method.Invoke(null, new[] { args }));
                                                            }
                                                            catch
                                                            {
                                                                return((bool)method.Invoke(null, new object[] { }));
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch { }
            }
            return(false);
        }