Example #1
0
        public frmMain()
        {
            InitializeComponent();

            DirectEve          = new DirectEve();
            DirectEve.OnFrame += OnFrame;
        }
Example #2
0
        public Questor(frmMain form1)
        {
            m_Parent   = form1;
            _lastPulse = DateTime.MinValue;

            _random = new Random();

            _salvage          = new Salvage();
            _defense          = new Defense();
            _combat           = new Combat();
            _traveler         = new Traveler();
            _unloadLoot       = new UnloadLoot();
            _agentInteraction = new AgentInteraction();
            _arm = new Arm();
            _missionController = new MissionController();
            _drones            = new Drones();
            _panic             = new Panic();
            _storyline         = new Storyline();

            Settings.Instance.SettingsLoaded += SettingsLoaded;

            // State fixed on ExecuteMission
            State = QuestorState.Idle;

            _directEve = new DirectEve();
            Cache.Instance.DirectEve = _directEve;

            Cache.Instance.StopTimeSpecified = Program.stopTimeSpecified;

            _directEve.OnFrame += OnFrame;
        }
Example #3
0
        /// <summary>
        ///     Add a waypoint
        /// </summary>
        /// <param name="clearOtherWaypoints"></param>
        /// <param name="firstWaypoint"></param>
        /// <returns></returns>
        public bool AddWaypoint(bool clearOtherWaypoints, bool firstWaypoint)
        {
            if (SolarSystemId == null)
            {
                return(false);
            }

            return(DirectEve.ThreadedLocalSvcCall("starmap", "SetWaypoint", LocationId, clearOtherWaypoints, firstWaypoint));
        }
Example #4
0
        /// <summary>
        ///   Returns the entity that we're approaching
        /// </summary>
        /// <param name = "directEve"></param>
        /// <returns></returns>
        public static DirectEntity GetApproachingEntity(this DirectEve directEve)
        {
            if (directEve.ActiveShip.Entity == null)
            {
                return(null);
            }

            return(directEve.GetEntityById(directEve.ActiveShip.Entity.FollowId));
        }
Example #5
0
        internal static DirectOwner GetOwner(DirectEve directEve, long ownerId)
        {
            var pyOwner = directEve.PySharp.Import("__builtin__").Attribute("cfg").Attribute("eveowners").Call("GetIfExists", ownerId);

            var owner = new DirectOwner(directEve);
            owner.OwnerId = (long) pyOwner.Attribute("ownerID");
            owner.Name = (string) pyOwner.Attribute("ownerName");
            owner.TypeId = (int) pyOwner.Attribute("typeID");
            return owner;
        }
Example #6
0
        internal static DirectOwner GetOwner(DirectEve directEve, long ownerId)
        {
            var pyOwner = directEve.PySharp.Import("__builtin__").Attribute("cfg").Attribute("eveowners").Call("GetIfExists", ownerId);

            var owner = new DirectOwner(directEve);

            owner.OwnerId = (long)pyOwner.Attribute("ownerID");
            owner.Name    = (string)pyOwner.Attribute("ownerName");
            owner.TypeId  = (int)pyOwner.Attribute("typeID");
            return(owner);
        }
Example #7
0
 /// <summary>
 ///   Create a bookmark
 /// </summary>
 /// <param name = "label"></param>
 public void CreateBookmark(string label)
 {
     if (Settings.Instance.CreateSalvageBookmarksIn == "Corp")
     {
         DirectEve.CorpBookmarkCurrentLocation(label, "", null);
     }
     else
     {
         DirectEve.BookmarkCurrentLocation(label, "", null);
     }
 }
Example #8
0
        private static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Log("Syntax:");
                Log("DotNet BuyLPI BuyLPI <TypeName or TypeId> [Quantity]");
                Log("(Quantity is optional)");
                Log("");
                Log("Example:");
                Log("DotNet BuyLPI BuyLPI \"Caldari Navy Mjolnir Torpedo\" 10");
                Log("*OR*");
                Log("DotNet BuyLPI BuyLPI 27339 10");
                return;
            }

            if (args.Length >= 1)
            {
                _type = args[0];
            }

            if (args.Length >= 2)
            {
                int dummy;
                if (!int.TryParse(args[1], out dummy))
                {
                    Log("BuyLPI: Quantity must be an integer, 0 - {0}", int.MaxValue);
                    return;
                }

                if (dummy < 0)
                {
                    Log("BuyLPI: Quantity must be a positive number");
                    return;
                }

                _quantity = dummy;
                _totalquantityoforders = dummy;
            }

            Log("BuyLPI: Starting BuyLPI...");
            _directEve          = new DirectEve();
            _directEve.OnFrame += OnFrame;

            // Sleep until we're done
            while (!_done)
            {
                Thread.Sleep(50);
            }

            _directEve.Dispose();
            Log("BuyLPI: BuyLPI finished.");
        }
Example #9
0
        /// <summary>
        ///   Calculate distance from me
        /// </summary>
        /// <param name = "directEve"></param>
        /// <param name = "x"></param>
        /// <param name = "y"></param>
        /// <param name = "z"></param>
        /// <returns></returns>
        public static double DistanceFromMe(this DirectEve directEve, double x, double y, double z)
        {
            if (directEve.ActiveShip.Entity == null)
            {
                return(-1);
            }

            var curX = directEve.ActiveShip.Entity.X;
            var curY = directEve.ActiveShip.Entity.Y;
            var curZ = directEve.ActiveShip.Entity.Z;

            return(Math.Sqrt((curX - x) * (curX - x) + (curY - y) * (curY - y) + (curZ - z) * (curZ - z)));
        }
Example #10
0
        /// <summary>
        ///     Get a location based on locationId
        /// </summary>
        /// <param name="directEve"></param>
        /// <param name="locationId"></param>
        /// <returns></returns>
        public static DirectLocation GetLocation(DirectEve directEve, long locationId)
        {
            var                 isValid       = false;
            string              name          = null;
            DirectRegion        region        = null;
            DirectConstellation constellation = null;
            DirectSolarSystem   solarSystem   = null;
            DirectStation       station       = null;

            if (directEve.Regions.TryGetValue(locationId, out region))
            {
                isValid = true;
                name    = region.Name;
            }
            else if (directEve.Constellations.TryGetValue(locationId, out constellation))
            {
                isValid = true;
                name    = constellation.Name;

                region = constellation.Region;
            }
            else if (directEve.SolarSystems.TryGetValue((int)locationId, out solarSystem))
            {
                isValid = true;
                name    = solarSystem.Name;

                constellation = solarSystem.Constellation;
                region        = constellation.Region;
            }
            else if (directEve.Stations.TryGetValue((int)locationId, out station))
            {
                isValid = true;
                name    = station.Name;

                solarSystem   = station.SolarSystem;
                constellation = solarSystem.Constellation;
                region        = constellation.Region;
            }

            var result = new DirectLocation(directEve);

            result.IsValid         = isValid;
            result.Name            = name;
            result.LocationId      = locationId;
            result.RegionId        = region != null ? region.Id : (long?)null;
            result.ConstellationId = constellation != null ? constellation.Id : (long?)null;
            result.SolarSystemId   = solarSystem != null ? solarSystem.Id : (long?)null;
            result.ItemId          = station != null ? station.Id : (long?)null;
            return(result);
        }
Example #11
0
        private static void Main(string[] args)
        {
            Log("Starting GridMon...");
            _directEve          = new DirectEve();
            _directEve.OnFrame += OnFrame;

            // Sleep until we're done
            while (!_done)
            {
                Thread.Sleep(50);
            }

            _directEve.Dispose();
            Log("GridMon finished.");
        }
Example #12
0
        private static void Main()
        {
            Log("Starting test...");
            _directEve          = new DirectEve();
            _directEve.OnFrame += OnFrame;

            // Sleep until we're done
            while (!_done)
            {
                Thread.Sleep(50);
            }

            _directEve.Dispose();
            Log("Test finished.");
        }
Example #13
0
        public frmMain()
        {
            InitializeComponent();

            InvTypesById = new Dictionary <int, InvType>();
            var invTypes = XDocument.Load(InvTypesPath);

            foreach (var element in invTypes.Root.Elements("invtype"))
            {
                InvTypesById.Add((int)element.Attribute("id"), new InvType(element));
            }

            Items       = new List <ItemCache>();
            ItemsToSell = new List <ItemCache>();

            DirectEve          = new DirectEve();
            DirectEve.OnFrame += OnFrame;
        }
Example #14
0
        public MainForm()
        {
            InitializeComponent();

            var t = typeof(MainForm);

            foreach (var mi in t.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance))
            {
                var attrs = mi.GetCustomAttributes(typeof(Test), false);
                foreach (var attr in attrs)
                {
                    TestStatesComboBox.Items.Add(mi.Name);
                }
            }
            _activeTest = "";
            TestStatesComboBox.SelectedIndex = 0;

            _directEve          = new DirectEve();
            _directEve.OnFrame += OnFrame;
        }
Example #15
0
        static void Main(string[] args)
        {
            if (args.Length == 3 || args.Length == 4)
            {
                _username  = args[0];
                _password  = args[1];
                _character = args[2];

                _directEve          = new DirectEve();
                _directEve.OnFrame += OnFrame;

                var started = DateTime.Now;

                // Sleep until we're done
                while (!_done)
                {
                    System.Threading.Thread.Sleep(50);

                    if (DateTime.Now.Subtract(started).TotalSeconds > 180)
                    {
                        Logging.Log("auto login timed out after 3 minutes");
                        break;
                    }
                }

                _directEve.Dispose();

                // If the last parameter is false, then we only auto-login
                if (args.Length == 4 && string.Compare(args[3], "false", true) == 0)
                {
                    return;
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMain());
        }
Example #16
0
        static void Main(string[] args)
        {
            Logging.Log("GoToBM: Started");
            if (args.Length == 0 || args[0].Length < 1)
            {
                Logging.Log("GoToBM: You need to supply a bookmark name");
                Logging.Log("GoToBM: Ended");
                return;
            }
            _BM = args[0];
            _BM = _BM.ToLower();

            _directEve = new DirectEve();
            Cache.Instance.DirectEve = _directEve;
            _directEve.OnFrame      += OnFrame;
            _traveler = new Traveler();

            while (!_done)
            {
                System.Threading.Thread.Sleep(50);
            }
            Logging.Log("GoToBM: Exiting");
            return;
        }
Example #17
0
 internal DirectMe(DirectEve directEve) : base(directEve)
 {
     _attributes = new DirectItemAttributes(directEve, directEve.Session.CharacterId ?? -1);
 }
Example #18
0
 internal DirectMe(DirectEve directEve)
     : base(directEve)
 {
     _attributes = new DirectItemAttributes(directEve, directEve.Session.CharacterId ?? -1);
 }
Example #19
0
 /// <summary>
 ///   Create a bookmark
 /// </summary>
 /// <param name = "label"></param>
 public void CreateBookmark(string label)
 {
     DirectEve.BookmarkCurrentLocation(label, "", null);
 }
Example #20
0
        private void OnFrame(object sender, EventArgs e)
        {
            if (State == ValueDumpState.Idle)
            {
                return;
            }

            var marketWindow        = DirectEve.Windows.OfType <DirectMarketWindow>().FirstOrDefault();
            var hangar              = DirectEve.GetItemHangar();
            var sellWindow          = DirectEve.Windows.OfType <DirectMarketActionWindow>().FirstOrDefault(w => w.IsSellAction);
            var reprorcessingWindow = DirectEve.Windows.OfType <DirectReprocessingWindow>().FirstOrDefault();

            switch (State)
            {
            case ValueDumpState.CheckMineralPrices:
                if (RefineCheckBox.Checked)
                {
                    _currentMineral = InvTypesById.Values.FirstOrDefault(i => i.ReprocessValue.HasValue && i.LastUpdate < DateTime.Now.AddDays(-7));
                }
                else
                {
                    _currentMineral = InvTypesById.Values.FirstOrDefault(i => i.Id != 27029 && i.GroupId == 18 && i.LastUpdate < DateTime.Now.AddHours(-4));
                }
                //_currentMineral = InvTypesById.Values.FirstOrDefault(i => i.Id != 27029 && i.GroupId == 18 && i.LastUpdate < DateTime.Now.AddMinutes(-1));
                //_currentMineral = InvTypesById.Values.FirstOrDefault(i => i.Id == 20236 && i.LastUpdate < DateTime.Now.AddMinutes(-1));
                if (_currentMineral == null)
                {
                    if (DateTime.Now.Subtract(_lastExecute).TotalSeconds > _delay)
                    {
                        State = ValueDumpState.SaveMineralPrices;
                        if (marketWindow != null)
                        {
                            marketWindow.Close();
                        }
                    }
                }
                else
                {
                    //State = ValueDumpState.GetMineralPrice;
                    if (marketWindow == null)
                    {
                        if (DateTime.Now.Subtract(_lastExecute).TotalSeconds > _delay)
                        {
                            DirectEve.ExecuteCommand(DirectCmd.OpenMarket);
                            _lastExecute = DateTime.Now;
                        }
                        return;
                    }

                    if (!marketWindow.IsReady)
                    {
                        return;
                    }

                    if (marketWindow.DetailTypeId != _currentMineral.Id)
                    {
                        if (DateTime.Now.Subtract(_lastExecute).TotalSeconds < _delay)
                        {
                            return;
                        }

                        Log("Loading orders for " + _currentMineral.Name);

                        marketWindow.LoadTypeId(_currentMineral.Id);
                        _lastExecute = DateTime.Now;
                        return;
                    }

                    if (!marketWindow.BuyOrders.Any(o => o.StationId == DirectEve.Session.StationId))
                    {
                        _currentMineral.LastUpdate = DateTime.Now;

                        Log("No buy orders found for " + _currentMineral.Name);
                        State = ValueDumpState.CheckMineralPrices;
                    }

                    // Take top 5 orders, average the buy price and consider that median-buy (it's not really median buy but its what we want)
                    //_currentMineral.MedianBuy = marketWindow.BuyOrders.Where(o => o.StationId == DirectEve.Session.StationId).OrderByDescending(o => o.Price).Take(5).Average(o => o.Price);

                    // Take top 1% orders and count median-buy price (no botter covers more than 1% Jita orders anyway)
                    var    orders = marketWindow.BuyOrders.Where(o => o.StationId == DirectEve.Session.StationId && o.MinimumVolume == 1).OrderByDescending(o => o.Price).ToList();
                    var    totalAmount = orders.Sum(o => (double)o.VolumeRemaining);
                    double amount = 0, value = 0, count = 0;
                    for (var i = 0; i < orders.Count(); i++)
                    {
                        amount += orders[i].VolumeRemaining;
                        value  += orders[i].VolumeRemaining * orders[i].Price;
                        count++;
                        //Log(_currentMineral.Name + " " + count + ": " + orders[i].VolumeRemaining.ToString("#,##0") + " items @ " + orders[i].Price);
                        if (amount / totalAmount > 0.01)
                        {
                            break;
                        }
                    }
                    _currentMineral.MedianBuy = value / amount;
                    Log("Average buy price for " + _currentMineral.Name + " is " + _currentMineral.MedianBuy.Value.ToString("#,##0.00") + " (" + count + " / " + orders.Count() + " orders, " + amount.ToString("#,##0") + " / " + totalAmount.ToString("#,##0") + " items)");

                    if (!marketWindow.SellOrders.Any(o => o.StationId == DirectEve.Session.StationId))
                    {
                        _currentMineral.LastUpdate = DateTime.Now;

                        Log("No sell orders found for " + _currentMineral.Name);
                        State = ValueDumpState.CheckMineralPrices;
                    }

                    // Take top 1% orders and count median-sell price
                    orders      = marketWindow.SellOrders.Where(o => o.StationId == DirectEve.Session.StationId).OrderBy(o => o.Price).ToList();
                    totalAmount = orders.Sum(o => (double)o.VolumeRemaining);
                    amount      = 0; value = 0; count = 0;
                    for (var i = 0; i < orders.Count(); i++)
                    {
                        amount += orders[i].VolumeRemaining;
                        value  += orders[i].VolumeRemaining * orders[i].Price;
                        count++;
                        //Log(_currentMineral.Name + " " + count + ": " + orders[i].VolumeRemaining.ToString("#,##0") + " items @ " + orders[i].Price);
                        if (amount / totalAmount > 0.01)
                        {
                            break;
                        }
                    }
                    _currentMineral.MedianSell = value / amount - 0.01;
                    Log("Average sell price for " + _currentMineral.Name + " is " + _currentMineral.MedianSell.Value.ToString("#,##0.00") + " (" + count + " / " + orders.Count() + " orders, " + amount.ToString("#,##0") + " / " + totalAmount.ToString("#,##0") + " items)");

                    if (_currentMineral.MedianSell.HasValue && !double.IsNaN(_currentMineral.MedianSell.Value))
                    {
                        _currentMineral.MedianAll = _currentMineral.MedianSell;
                    }
                    else if (_currentMineral.MedianBuy.HasValue && !double.IsNaN(_currentMineral.MedianBuy.Value))
                    {
                        _currentMineral.MedianAll = _currentMineral.MedianBuy;
                    }
                    _currentMineral.LastUpdate = DateTime.Now;
                    //State = ValueDumpState.CheckMineralPrices;
                }
                break;

            case ValueDumpState.GetMineralPrice:
                break;

            case ValueDumpState.SaveMineralPrices:
                Log("Updating reprocess prices");

                // a quick price check table
                var MineralPrices = new Dictionary <string, double>();
                foreach (var i in InvTypesById.Values)
                {
                    if (InvType.Minerals.Contains(i.Name))
#if manual
                    { MineralPrices.Add(i.Name, i.MedianSell ?? 0); }
                }
#else
                    { MineralPrices.Add(i.Name, i.MedianBuy ?? 0); }
#endif

                double temp;
                foreach (var i in InvTypesById.Values)
                {
                    temp = 0;
                    foreach (var m in InvType.Minerals)
                    {
                        if (i.Reprocess[m].HasValue && i.Reprocess[m] > 0)
                        {
                            temp += i.Reprocess[m].Value * MineralPrices[m];
                        }
                    }
                    if (temp > 0)
                    {
                        i.ReprocessValue = temp;
                    }
                    else
                    {
                        i.ReprocessValue = null;
                    }
                }

                Log("Saving InvTypes.xml");

                var xdoc = new XDocument(new XElement("invtypes"));
                foreach (var type in InvTypesById.Values.OrderBy(i => i.Id))
                {
                    xdoc.Root.Add(type.Save());
                }
                xdoc.Save(InvTypesPath);

                State = ValueDumpState.Idle;
                break;

            case ValueDumpState.GetItems:
                if (hangar.Window == null)
                {
                    // No, command it to open
                    if (DateTime.Now.Subtract(_lastExecute).TotalSeconds > _delay)
                    {
                        Log("Opening hangar");
                        DirectEve.ExecuteCommand(DirectCmd.OpenHangarFloor);
                        _lastExecute = DateTime.Now;
                    }

                    return;
                }

                if (!hangar.IsReady)
                {
                    return;
                }

                Log("Loading hangar items");

                // Clear out the old
                Items.Clear();
                var hangarItems = hangar.Items;
                if (hangarItems != null)
                {
                    Items.AddRange(hangarItems.Where(i => i.ItemId > 0 && i.Quantity > 0).Select(i => new ItemCache(i, RefineCheckBox.Checked)));
                }

                State = ValueDumpState.UpdatePrices;
                break;

            case ValueDumpState.UpdatePrices:
                bool updated = false;

                foreach (var item in Items)
                {
                    InvType invType;
                    if (!InvTypesById.TryGetValue(item.TypeId, out invType))
                    {
                        Log("Unknown TypeId " + item.TypeId + " for " + item.Name + ", adding to the list");
                        invType = new InvType(item);
                        InvTypesById.Add(item.TypeId, invType);
                        updated = true;
                        continue;
                    }
                    item.InvType = invType;

                    bool updItem = false;
                    foreach (var material in item.RefineOutput)
                    {
                        if (!InvTypesById.TryGetValue(material.TypeId, out invType))
                        {
                            Log("Unknown TypeId " + material.TypeId + " for " + material.Name);
                            continue;
                        }
                        material.InvType = invType;

                        var matsPerItem = (double)material.Quantity / item.PortionSize;
                        var exists      = InvTypesById[(int)item.TypeId].Reprocess[material.Name].HasValue;
                        if ((!exists && matsPerItem > 0) || (exists && InvTypesById[(int)item.TypeId].Reprocess[material.Name] != matsPerItem))
                        {
                            if (exists)
                            {
                                Log("[" + item.Name + "][" + material.Name + "] old value: [" + InvTypesById[(int)item.TypeId].Reprocess[material.Name] + ", new value: [" + matsPerItem + "]");
                            }
                            InvTypesById[(int)item.TypeId].Reprocess[material.Name] = matsPerItem;
                            updItem = true;
                        }
                    }

                    if (updItem)
                    {
                        Log("Updated [" + item.Name + "] refine materials");
                    }
                    updated |= updItem;
                }

                if (updated)
                {
                    State = ValueDumpState.SaveMineralPrices;
                }
                else
                {
                    State = ValueDumpState.Idle;
                }

                if (cbxSell.Checked)
                {
                    // Copy the items to sell list
                    ItemsToSell.Clear();
                    ItemsToRefine.Clear();
                    if (cbxUndersell.Checked)
#if manual
                    { ItemsToSell.AddRange(Items.Where(i => i.InvType != null && i.MarketGroupId > 0)); }
#else
                    { ItemsToSell.AddRange(Items.Where(i => i.InvType != null && i.MarketGroupId > 0)); }
#endif
                    else
#if manual
                    { ItemsToSell.AddRange(Items.Where(i => i.InvType != null && i.MarketGroupId > 0 && i.InvType.MedianBuy.HasValue)); }
#else
                    { ItemsToSell.AddRange(Items.Where(i => i.InvType != null && i.MarketGroupId > 0 && i.InvType.MedianBuy.HasValue)); }
#endif
                    State = ValueDumpState.NextItem;
                }
                break;
Example #21
0
        static void Main(string[] args)
        {
            _maxRuntime = Int32.MaxValue;
            var p = new OptionSet()
            {
                "Usage: questor [OPTIONS]",
                "Run missions and make uber ISK.",
                "",
                "Options:",
                { "u|user="******"the {USER} we are logging in as.",
                  v => _username = v },
                { "p|password="******"the user's {PASSWORD}.",
                  v => _password = v },
                { "c|character=", "the {CHARACTER} to use.",
                  v => _character = v },
                { "s|script=", "a {SCRIPT} file to execute before login.",
                  v => _scriptFile = v },
                { "l|login", "login only and exit.",
                  v => _loginOnly = v != null },
                { "r|runtime=", "Quit Questor after {RUNTIME} minutes.",
                  v => _maxRuntime = Int32.Parse(v) },
                { "h|help", "show this message and exit",
                  v => _showHelp = v != null },
            };

            List <string> extra;

            try
            {
                extra = p.Parse(args);
                //Logging.Log(string.Format("questor: extra = {0}", string.Join(" ", extra.ToArray())));
            }
            catch (OptionException e)
            {
                Logging.Log("questor: ");
                Logging.Log(e.Message);
                Logging.Log("Try `questor --help' for more information.");
                return;
            }

            if (_showHelp)
            {
                System.IO.StringWriter sw = new System.IO.StringWriter();
                p.WriteOptionDescriptions(sw);
                Logging.Log(sw.ToString());
                return;
            }

            if (!string.IsNullOrEmpty(_username) && !string.IsNullOrEmpty(_password) && !string.IsNullOrEmpty(_character))
            {
                _directEve          = new DirectEve();
                _directEve.OnFrame += OnFrame;

                var started = DateTime.Now;

                // Sleep until we're done
                while (!_done)
                {
                    System.Threading.Thread.Sleep(50);

                    if (DateTime.Now.Subtract(started).TotalSeconds > 180)
                    {
                        Logging.Log("auto login timed out after 3 minutes");
                        break;
                    }
                }

                _directEve.Dispose();

                // If the last parameter is false, then we only auto-login
                if (_loginOnly)
                {
                    return;
                }
            }

            _startTime = DateTime.Now;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMain());
        }
Example #22
0
 private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     _directEve.Dispose();
     _directEve = null;
 }
Example #23
0
        static void Main(string[] args)
        {
            if (args.Length == 1)
            {
                _character = args[0];

                var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

                CharSchedules = new List <CharSchedule>();
                var values = XDocument.Load(Path.Combine(path, "Schedules.xml"));
                foreach (var value in values.Root.Elements("char"))
                {
                    CharSchedules.Add(new CharSchedule(value));
                }

                var _schedule = CharSchedules.FirstOrDefault(v => v.Name == _character);
                if (_schedule == null)
                {
                    Logging.Log("[Startup] Error - character not found!");
                    return;
                }
                else
                {
                    Logging.Log("[Startup] User: "******" PW: " + _schedule.PW + " Name: " + _schedule.Name + " Start: " + _schedule.Start + " Stop: " +
                                _schedule.Stop + " RunTime: " + _schedule.RunTime);
                    if (_schedule.User == null || _schedule.PW == null)
                    {
                        Logging.Log("[Startup] Error - Login details not specified in Schedules.xml!");
                        return;
                    }
                    else
                    {
                        _username = _schedule.User;
                        _password = _schedule.PW;
                    }
                    _startTime = _schedule.Start;
                    if (_schedule.startTimeSpecified)
                    {
                        _startTime = _startTime.AddSeconds((double)(_r.Next(0, (_randStartDelay * 60))));
                    }
                    _stopTime = _schedule.Stop;

                    if ((DateTime.Now > _startTime))
                    {
                        if ((DateTime.Now.Subtract(_startTime).TotalMinutes < 720))   //if we're less than 12 hours past start time, start now
                        {
                            _startTime     = DateTime.Now;
                            _readyToStarta = true;
                        }
                        else
                        {
                            _startTime = _startTime.AddDays(1); //otherwise, start tomorrow at start time
                        }
                    }
                    else
                    if ((_startTime.Subtract(DateTime.Now).TotalMinutes > 720))     //if we're more than 12 hours shy of start time, start now
                    {
                        _startTime     = DateTime.Now;
                        _readyToStarta = true;
                    }

                    if (_stopTime < _startTime)
                    {
                        _stopTime = _stopTime.AddDays(1);
                    }

                    if (_schedule.RunTime > 0) //if runtime is specified, overrides stop time
                    {
                        _stopTime = _startTime.AddHours(_schedule.RunTime);
                    }

                    string _stopTimeText = "No stop time specified";
                    stopTimeSpecified = _schedule.stopTimeSpecified;
                    if (stopTimeSpecified)
                    {
                        _stopTimeText = _stopTime.ToString();
                    }

                    Logging.Log("[Startup] Start Time: " + _startTime + " - Stop Time: " + _stopTimeText);

                    if (!_readyToStarta)
                    {
                        minutesToStart = _startTime.Subtract(DateTime.Now).TotalMinutes;
                        Logging.Log("[Startup] Starting at " + _startTime + ". " + String.Format("{0:0.##}", minutesToStart) + " minutes to go.");
                        _timer.Elapsed += new ElapsedEventHandler(TimerEventProcessor);
                        if (minutesToStart > 0)
                        {
                            _timer.Interval = (int)(minutesToStart * 60000);
                        }
                        else
                        {
                            _timer.Interval = 1000;
                        }
                        _timer.Enabled = true;
                        _timer.Start();
                    }
                    else
                    {
                        _readyToStart = true;
                        Logging.Log("[Startup] Already passed start time.  Starting now.");
                    }
                }

                _directEve          = new DirectEve();
                _directEve.OnFrame += OnFrame;

                while (!_done)
                {
                    System.Threading.Thread.Sleep(50);
                }

                _directEve.Dispose();
            }
            else if (args.Length == 3 || args.Length == 4)
            {
                _username     = args[0];
                _password     = args[1];
                _character    = args[2];
                _readyToStart = true;

                _directEve          = new DirectEve();
                _directEve.OnFrame += OnFrame;

                var started = DateTime.Now;

                // Sleep until we're done
                while (!_done)
                {
                    System.Threading.Thread.Sleep(50);
                }

                _directEve.Dispose();

                // If the last parameter is false, then we only auto-login
                if (args.Length == 4 && string.Compare(args[3], "false", true) == 0)
                {
                    return;
                }
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMain());
        }
Example #24
0
        private void OnFrame(object sender, EventArgs e)
        {
            if (State == ValueDumpState.Idle)
            {
                return;
            }

            var marketWindow        = DirectEve.Windows.OfType <DirectMarketWindow>().FirstOrDefault();
            var hangar              = DirectEve.GetItemHangar();
            var sellWindow          = DirectEve.Windows.OfType <DirectMarketActionWindow>().FirstOrDefault(w => w.IsSellAction);
            var reprorcessingWindow = DirectEve.Windows.OfType <DirectReprocessingWindow>().FirstOrDefault();

            switch (State)
            {
            case ValueDumpState.CheckMineralPrices:
                _currentMineral = InvTypesById.Values.FirstOrDefault(i => i.Id != 27029 && i.GroupId == 18 && i.LastUpdate < DateTime.Now.AddHours(-4));
                if (_currentMineral == null)
                {
                    if (DateTime.Now.Subtract(_lastExecute).TotalSeconds > 5)
                    {
                        State = ValueDumpState.SaveMineralPrices;
                        if (marketWindow != null)
                        {
                            marketWindow.Close();
                        }
                    }
                }
                else
                {
                    State = ValueDumpState.GetMineralPrice;
                }
                break;

            case ValueDumpState.GetMineralPrice:
                if (marketWindow == null)
                {
                    if (DateTime.Now.Subtract(_lastExecute).TotalSeconds > 5)
                    {
                        DirectEve.ExecuteCommand(DirectCmd.OpenMarket);
                        _lastExecute = DateTime.Now;
                    }

                    return;
                }

                if (marketWindow.DetailTypeId != _currentMineral.Id)
                {
                    if (DateTime.Now.Subtract(_lastExecute).TotalSeconds < 5)
                    {
                        return;
                    }

                    Log("Loading orders for " + _currentMineral.Name);

                    marketWindow.LoadTypeId(_currentMineral.Id);
                    _lastExecute = DateTime.Now;
                    return;
                }

                if (!marketWindow.BuyOrders.Any(o => o.StationId == DirectEve.Session.StationId))
                {
                    _currentMineral.LastUpdate = DateTime.Now;

                    Log("No orders found for " + _currentMineral.Name);
                    State = ValueDumpState.CheckMineralPrices;
                }

                // Take top 5 orders, average the buy price and consider that median-buy (it's not really median buy but its what we want)
                _currentMineral.MedianBuy  = marketWindow.BuyOrders.Where(o => o.StationId == DirectEve.Session.StationId).OrderByDescending(o => o.Price).Take(5).Average(o => o.Price);
                _currentMineral.LastUpdate = DateTime.Now;
                State = ValueDumpState.CheckMineralPrices;

                Log("Average price for " + _currentMineral.Name + " is " + _currentMineral.MedianBuy.Value.ToString("#,##0.00"));
                break;

            case ValueDumpState.SaveMineralPrices:
                Log("Saving InvItems.xml");

                var xdoc = new XDocument(new XElement("invtypes"));
                foreach (var type in InvTypesById.Values.OrderBy(i => i.Id))
                {
                    xdoc.Root.Add(type.Save());
                }
                xdoc.Save(InvTypesPath);

                State = ValueDumpState.Idle;
                break;

            case ValueDumpState.GetItems:
                if (hangar.Window == null)
                {
                    // No, command it to open
                    if (DateTime.Now.Subtract(_lastExecute).TotalSeconds > 5)
                    {
                        Log("Opening hangar");
                        DirectEve.ExecuteCommand(DirectCmd.OpenHangarFloor);
                        _lastExecute = DateTime.Now;
                    }

                    return;
                }

                if (!hangar.IsReady)
                {
                    return;
                }

                Log("Loading hangar items");

                // Clear out the old
                Items.Clear();
                var hangarItems = hangar.Items;
                if (hangarItems != null)
                {
                    Items.AddRange(hangarItems.Where(i => i.ItemId > 0 && i.MarketGroupId > 0 && i.Quantity > 0).Select(i => new ItemCache(i, RefineCheckBox.Checked)));
                }

                State = ValueDumpState.UpdatePrices;
                break;

            case ValueDumpState.UpdatePrices:
                foreach (var item in Items)
                {
                    InvType invType;
                    if (!InvTypesById.TryGetValue(item.TypeId, out invType))
                    {
                        Log("Unknown TypeId " + item.TypeId + " for " + item.Name);
                        continue;
                    }

                    item.InvType = invType;
                    foreach (var material in item.RefineOutput)
                    {
                        if (!InvTypesById.TryGetValue(material.TypeId, out invType))
                        {
                            Log("Unknown TypeId " + material.TypeId + " for " + material.Name);
                            continue;
                        }

                        material.InvType = invType;
                    }
                }

                State = ValueDumpState.Idle;
                if (cbxSell.Checked)
                {
                    // Copy the items to sell list
                    ItemsToSell.Clear();
                    ItemsToRefine.Clear();
                    if (cbxUndersell.Checked)
                    {
                        ItemsToSell.AddRange(Items.Where(i => i.InvType != null));
                    }
                    else
                    {
                        ItemsToSell.AddRange(Items.Where(i => i.InvType != null && i.InvType.MedianBuy.HasValue));
                    }

                    State = ValueDumpState.NextItem;
                }
                break;

            case ValueDumpState.NextItem:
                if (ItemsToSell.Count == 0)
                {
                    if (ItemsToRefine.Count != 0)
                    {
                        State = ValueDumpState.RefineItems;
                    }
                    else
                    {
                        State = ValueDumpState.Idle;
                    }
                    break;
                }

                Log(ItemsToSell.Count + " items left to sell");

                _currentItem = ItemsToSell[0];
                ItemsToSell.RemoveAt(0);

                // Dont sell containers
                if (_currentItem.GroupId == 448)
                {
                    Log("Skipping " + _currentItem.Name);
                    break;
                }

                State = ValueDumpState.StartQuickSell;
                break;

            case ValueDumpState.StartQuickSell:
                if (DateTime.Now.Subtract(_lastExecute).TotalSeconds < 1)
                {
                    break;
                }
                _lastExecute = DateTime.Now;

                var directItem = hangar.Items.FirstOrDefault(i => i.ItemId == _currentItem.Id);
                if (directItem == null)
                {
                    Log("Item " + _currentItem.Name + " no longer exists in the hanger");
                    break;
                }

                // Update Quantity
                _currentItem.QuantitySold = _currentItem.Quantity - directItem.Quantity;

                Log("Starting QuickSell for " + _currentItem.Name);
                if (!directItem.QuickSell())
                {
                    _lastExecute = DateTime.Now.AddSeconds(-5);

                    Log("QuickSell failed for " + _currentItem.Name + ", retrying in 5 seconds");
                    break;
                }

                State = ValueDumpState.WaitForSellWindow;
                break;

            case ValueDumpState.WaitForSellWindow:
                if (sellWindow == null || !sellWindow.IsReady || sellWindow.Item.ItemId != _currentItem.Id)
                {
                    break;
                }

                // Mark as new execution
                _lastExecute = DateTime.Now;

                Log("Inspecting sell order for " + _currentItem.Name);
                State = ValueDumpState.InspectOrder;
                break;

            case ValueDumpState.InspectOrder:
                // Let the order window stay open for 2 seconds
                if (DateTime.Now.Subtract(_lastExecute).TotalSeconds < 2)
                {
                    break;
                }

                if (!sellWindow.OrderId.HasValue || !sellWindow.Price.HasValue || !sellWindow.RemainingVolume.HasValue)
                {
                    Log("No order available for " + _currentItem.Name);

                    sellWindow.Cancel();
                    State = ValueDumpState.WaitingToFinishQuickSell;
                    break;
                }

                var price      = sellWindow.Price.Value;
                var quantity   = (int)Math.Min(_currentItem.Quantity - _currentItem.QuantitySold, sellWindow.RemainingVolume.Value);
                var totalPrice = quantity * price;

                string otherPrices = " ";
                if (_currentItem.InvType.MedianBuy.HasValue)
                {
                    otherPrices += "[Median buy price: " + (_currentItem.InvType.MedianBuy.Value * quantity).ToString("#,##0.00") + "]";
                }
                else
                {
                    otherPrices += "[No median buy price]";
                }

                if (RefineCheckBox.Checked)
                {
                    var portions    = quantity / _currentItem.PortionSize;
                    var refinePrice = _currentItem.RefineOutput.Any() ? _currentItem.RefineOutput.Sum(m => m.Quantity * m.InvType.MedianBuy ?? 0) * portions : 0;
                    refinePrice *= (double)RefineEfficiencyInput.Value / 100;

                    otherPrices += "[Refine price: " + refinePrice.ToString("#,##0.00") + "]";

                    if (refinePrice > totalPrice)
                    {
                        Log("Refining gives a better price for item " + _currentItem.Name + " [Refine price: " + refinePrice.ToString("#,##0.00") + "][Sell price: " + totalPrice.ToString("#,##0.00") + "]");

                        // Add it to the refine list
                        ItemsToRefine.Add(_currentItem);

                        sellWindow.Cancel();
                        State = ValueDumpState.WaitingToFinishQuickSell;
                        break;
                    }
                }

                if (!cbxUndersell.Checked)
                {
                    if (!_currentItem.InvType.MedianBuy.HasValue)
                    {
                        Log("No historical price available for " + _currentItem.Name);

                        sellWindow.Cancel();
                        State = ValueDumpState.WaitingToFinishQuickSell;
                        break;
                    }

                    var perc  = price / _currentItem.InvType.MedianBuy.Value;
                    var total = _currentItem.InvType.MedianBuy.Value * _currentItem.Quantity;
                    // If percentage < 85% and total price > 1m isk then skip this item (we don't undersell)
                    if (perc < 0.85 && total > 1000000)
                    {
                        Log("Not underselling item " + _currentItem.Name + " [Median buy price: " + _currentItem.InvType.MedianBuy.Value.ToString("#,##0.00") + "][Sell price: " + price.ToString("#,##0.00") + "][" + perc.ToString("0%") + "]");

                        sellWindow.Cancel();
                        State = ValueDumpState.WaitingToFinishQuickSell;
                        break;
                    }
                }

                // Update quantity sold
                _currentItem.QuantitySold += quantity;

                // Update station price
                if (!_currentItem.StationBuy.HasValue)
                {
                    _currentItem.StationBuy = price;
                }
                _currentItem.StationBuy = (_currentItem.StationBuy + price) / 2;

                Log("Selling " + quantity + " of " + _currentItem.Name + " [Sell price: " + (price * quantity).ToString("#,##0.00") + "]" + otherPrices);
                sellWindow.Accept();

                // Requeue to check again
                if (_currentItem.QuantitySold < _currentItem.Quantity)
                {
                    ItemsToSell.Add(_currentItem);
                }

                _lastExecute = DateTime.Now;
                State        = ValueDumpState.WaitingToFinishQuickSell;
                break;

            case ValueDumpState.WaitingToFinishQuickSell:
                if (sellWindow == null || !sellWindow.IsReady || sellWindow.Item.ItemId != _currentItem.Id)
                {
                    var modal = DirectEve.Windows.FirstOrDefault(w => w.IsModal);
                    if (modal != null)
                    {
                        modal.Close();
                    }

                    State = ValueDumpState.NextItem;
                    break;
                }
                break;

            case ValueDumpState.RefineItems:
                if (reprorcessingWindow == null)
                {
                    if (DateTime.Now.Subtract(_lastExecute).TotalSeconds > 5)
                    {
                        var refineItems = hangar.Items.Where(i => ItemsToRefine.Any(r => r.Id == i.ItemId));
                        DirectEve.ReprocessStationItems(refineItems);

                        _lastExecute = DateTime.Now;
                    }
                    return;
                }

                if (reprorcessingWindow.NeedsQuote)
                {
                    if (DateTime.Now.Subtract(_lastExecute).TotalSeconds > 5)
                    {
                        reprorcessingWindow.GetQuotes();
                        _lastExecute = DateTime.Now;
                    }

                    return;
                }

                // Wait till we have a quote
                if (reprorcessingWindow.Quotes.Count == 0)
                {
                    _lastExecute = DateTime.Now;
                    return;
                }

                // Wait another 5 seconds to view the quote and then reprocess the stuff
                if (DateTime.Now.Subtract(_lastExecute).TotalSeconds > 5)
                {
                    // TODO: We should wait for the items to appear in our hangar and then sell them...
                    reprorcessingWindow.Reprocess();
                    State = ValueDumpState.Idle;
                }
                break;
            }
        }
Example #25
0
 internal DirectOwner(DirectEve directEve) : base(directEve)
 {
 }
Example #26
0
        private void OnFrame(object sender, EventArgs e)
        {
            if (State == ValueDumpState.Idle)
            {
                return;
            }

            var hangar     = DirectEve.GetItemHangar();
            var sellWindow = DirectEve.Windows.OfType <DirectMarketActionWindow>().FirstOrDefault(w => w.IsSellAction);

            switch (State)
            {
            case ValueDumpState.GetItems:
                if (hangar.Window == null)
                {
                    // No, command it to open
                    if (DateTime.Now.Subtract(_lastExecute).TotalSeconds > 5)
                    {
                        Log("Opening hangar");
                        DirectEve.ExecuteCommand(DirectCmd.OpenHangarFloor);
                        _lastExecute = DateTime.Now;
                    }

                    return;
                }

                if (!hangar.IsReady)
                {
                    return;
                }

                Log("Loading hangar items");

                // Clear out the old
                Items.Clear();
                var hangarItems = hangar.Items;
                if (hangarItems != null)
                {
                    Items.AddRange(hangarItems.Where(i => i.ItemId > 0 && i.MarketGroupId.HasValue && i.Quantity > 0).Select(i => new ItemCache(i)));
                }

                State = ValueDumpState.UpdatePrices;
                break;

            case ValueDumpState.UpdatePrices:
                foreach (var item in Items)
                {
                    InvType invType;
                    if (!InvTypesById.TryGetValue(item.TypeId, out invType))
                    {
                        Log("Unknown TypeId " + _currentItem.TypeId + " for " + _currentItem.Name);
                        continue;
                    }

                    item.InvType = invType;
                }

                State = ValueDumpState.Idle;
                if (cbxSell.Checked)
                {
                    // Copy the items to sell list
                    ItemsToSell.Clear();
                    if (cbxUndersell.Checked)
                    {
                        ItemsToSell.AddRange(Items.Where(i => i.InvType != null));
                    }
                    else
                    {
                        ItemsToSell.AddRange(Items.Where(i => i.InvType != null && i.InvType.MedianBuy.HasValue));
                    }

                    State = ValueDumpState.NextItem;
                }
                break;

            case ValueDumpState.NextItem:
                if (ItemsToSell.Count == 0)
                {
                    State = ValueDumpState.Idle;
                    break;
                }

                Log(ItemsToSell.Count + " items left to sell");

                _currentItem = ItemsToSell[0];
                ItemsToSell.RemoveAt(0);

                // Dont sell containers
                if (_currentItem.GroupId == 448)
                {
                    Log("Skipping " + _currentItem.Name);
                    break;
                }

                State = ValueDumpState.StartQuickSell;
                break;

            case ValueDumpState.StartQuickSell:
                if (DateTime.Now.Subtract(_lastExecute).TotalSeconds < 1)
                {
                    break;
                }
                _lastExecute = DateTime.Now;

                var directItem = hangar.Items.FirstOrDefault(i => i.ItemId == _currentItem.Id);
                if (directItem == null)
                {
                    Log("Item " + _currentItem.Name + " no longer exists in the hanger");
                    break;
                }

                // Update Quantity
                _currentItem.QuantitySold = _currentItem.Quantity - (directItem.Quantity ?? _currentItem.Quantity);

                Log("Starting QuickSell for " + _currentItem.Name);
                if (!directItem.QuickSell())
                {
                    _lastExecute = DateTime.Now.AddSeconds(-5);

                    Log("QuickSell failed for " + _currentItem.Name + ", retrying in 5 seconds");
                    break;
                }

                State = ValueDumpState.WaitForSellWindow;
                break;

            case ValueDumpState.WaitForSellWindow:
                if (sellWindow == null || !sellWindow.IsReady || sellWindow.Item.ItemId != _currentItem.Id)
                {
                    break;
                }

                // Mark as new execution
                _lastExecute = DateTime.Now;

                Log("Inspecting sell order for " + _currentItem.Name);
                State = ValueDumpState.InspectOrder;
                break;

            case ValueDumpState.InspectOrder:
                // Let the order window stay open for 2 seconds
                if (DateTime.Now.Subtract(_lastExecute).TotalSeconds < 2)
                {
                    break;
                }

                if (!sellWindow.OrderId.HasValue || !sellWindow.Price.HasValue || !sellWindow.RemainingVolume.HasValue)
                {
                    Log("No order available for " + _currentItem.Name);

                    sellWindow.Cancel();
                    State = ValueDumpState.WaitingToFinishQuickSell;
                    break;
                }

                var price = sellWindow.Price.Value;
                if (!cbxUndersell.Checked)
                {
                    if (!_currentItem.InvType.MedianBuy.HasValue)
                    {
                        Log("No historical price available for " + _currentItem.Name);

                        sellWindow.Cancel();
                        State = ValueDumpState.WaitingToFinishQuickSell;
                        break;
                    }

                    var perc  = price / _currentItem.InvType.MedianBuy.Value;
                    var total = _currentItem.InvType.MedianBuy.Value * _currentItem.Quantity;
                    // If percentage < 85% and total price > 1m isk then skip this item (we don't undersell)
                    if (perc < 0.85 && total > 1000000)
                    {
                        Log("Not underselling item " + _currentItem.Name + " [" + _currentItem.InvType.MedianBuy.Value.ToString("#,##0.00") + "][" + price.ToString("#,##0.00") + "][" + perc.ToString("0%") + "]");

                        sellWindow.Cancel();
                        State = ValueDumpState.WaitingToFinishQuickSell;
                        break;
                    }
                }

                var quantity = (int)Math.Min(_currentItem.Quantity - _currentItem.QuantitySold, sellWindow.RemainingVolume.Value);

                // Update quantity sold
                _currentItem.QuantitySold += quantity;

                // Update station price
                if (!_currentItem.StationBuy.HasValue)
                {
                    _currentItem.StationBuy = price;
                }
                _currentItem.StationBuy = (_currentItem.StationBuy + price) / 2;

                Log("Selling " + quantity + " of " + _currentItem.Name + " for " + (price * quantity).ToString("#,##0.00"));
                sellWindow.Accept();

                // Requeue to check again
                if (_currentItem.QuantitySold < _currentItem.Quantity)
                {
                    ItemsToSell.Add(_currentItem);
                }

                _lastExecute = DateTime.Now;
                State        = ValueDumpState.WaitingToFinishQuickSell;
                break;

            case ValueDumpState.WaitingToFinishQuickSell:
                if (sellWindow == null || !sellWindow.IsReady || sellWindow.Item.ItemId != _currentItem.Id)
                {
                    var modal = DirectEve.Windows.FirstOrDefault(w => w.IsModal);
                    if (modal != null)
                    {
                        modal.Close();
                    }

                    State = ValueDumpState.NextItem;
                    break;
                }
                break;
            }
        }
Example #27
0
 /// <summary>
 ///   Get the first entity with a certain name
 /// </summary>
 /// <param name = "directEve"></param>
 /// <param name = "name"></param>
 /// <returns></returns>
 public static DirectEntity GetEntityByName(this DirectEve directEve, string name)
 {
     return(directEve.Entities.FirstOrDefault(e => string.Compare(e.Name, name, true) == 0));
 }
Example #28
0
 internal DirectObject(DirectEve directEve)
 {
     DirectEve = directEve;
 }
Example #29
0
 internal DirectOwner(DirectEve directEve)
     : base(directEve)
 {
 }
Example #30
0
 private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
 {
     DirectEve.Dispose();
     DirectEve = null;
 }
Example #31
0
 /// <summary>
 ///   Get all entities with the name
 /// </summary>
 /// <param name = "directEve"></param>
 /// <param name = "name"></param>
 /// <returns></returns>
 public static IEnumerable <DirectEntity> GetEntitiesByName(this DirectEve directEve, string name)
 {
     return(directEve.Entities.Where(e => string.Compare(e.Name, name, true) == 0));
 }
Example #32
0
 internal DirectObject(DirectEve directEve)
 {
     DirectEve = directEve;
 }
Example #33
0
 /// <summary>
 ///   return a bookmark by it's id
 /// </summary>
 /// <param name = "directEve"></param>
 /// <param name = "bookmarkId"></param>
 /// <returns></returns>
 /// <remarks>
 ///   Return's null if no bookmark was found
 /// </remarks>
 public static DirectBookmark GetBookmarkById(this DirectEve directEve, long bookmarkId)
 {
     return(directEve.Bookmarks.FirstOrDefault(b => b.BookmarkId == bookmarkId));
 }
Example #34
0
        static void Main(string[] args)
        {
            _maxRuntime = Int32.MaxValue;
            var p = new OptionSet()
            {
                "Usage: questor [OPTIONS]",
                "Run missions and make uber ISK.",
                "",
                "Options:",
                { "u|user="******"the {USER} we are logging in as.",
                  v => _username = v },
                { "p|password="******"the user's {PASSWORD}.",
                  v => _password = v },
                { "c|character=", "the {CHARACTER} to use.",
                  v => _character = v },
                { "s|script=", "a {SCRIPT} file to execute before login.",
                  v => _scriptFile = v },
                { "l|login", "login only and exit.",
                  v => _loginOnly = v != null },
                { "r|runtime=", "Quit Questor after {RUNTIME} minutes.",
                  v => _maxRuntime = Int32.Parse(v) },
                { "x|chantling", "use chantling's scheduler",
                  v => _chantlingScheduler = v != null },
                { "h|help", "show this message and exit",
                  v => _showHelp = v != null },
            };

            List <string> extra;

            try
            {
                extra = p.Parse(args);
                //Logging.Log(string.Format("questor: extra = {0}", string.Join(" ", extra.ToArray())));
            }
            catch (OptionException e)
            {
                Logging.Log("questor: ");
                Logging.Log(e.Message);
                Logging.Log("Try `questor --help' for more information.");
                return;
            }
            _readyToStart = true;

            if (_showHelp)
            {
                System.IO.StringWriter sw = new System.IO.StringWriter();
                p.WriteOptionDescriptions(sw);
                Logging.Log(sw.ToString());
                return;
            }

            if (_chantlingScheduler && string.IsNullOrEmpty(_character))
            {
                Logging.Log("Error: to use chantling's scheduler, you also need to provide a character name!");
                return;
            }

            if (_chantlingScheduler && !string.IsNullOrEmpty(_character))
            {
                var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                _character = _character.Replace("\"", "");  // strip quotation marks if any are present

                CharSchedules = new List <CharSchedule>();
                var values = XDocument.Load(Path.Combine(path, "Schedules.xml"));
                foreach (var value in values.Root.Elements("char"))
                {
                    CharSchedules.Add(new CharSchedule(value));
                }

                var _schedule = CharSchedules.FirstOrDefault(v => v.Name == _character);
                if (_schedule == null)
                {
                    Logging.Log("[Startup] Error - character not found!");
                    return;
                }
                else
                {
                    Logging.Log("[Startup] User: "******" PW: " + _schedule.PW + " Name: " + _schedule.Name + " Start: " + _schedule.Start + " Stop: " +
                                _schedule.Stop + " RunTime: " + _schedule.RunTime);
                    if (_schedule.User == null || _schedule.PW == null)
                    {
                        Logging.Log("[Startup] Error - Login details not specified in Schedules.xml!");
                        return;
                    }
                    else
                    {
                        _username = _schedule.User;
                        _password = _schedule.PW;
                    }
                    _startTime = _schedule.Start;

                    if (_schedule.startTimeSpecified)
                    {
                        _startTime = _startTime.AddSeconds((double)(_r.Next(0, (_randStartDelay * 60))));
                    }
                    _scheduledstartTime = _schedule.Start;
                    _scheduledstopTime  = _schedule.Stop;
                    _stopTime           = _schedule.Stop;

                    //if ((DateTime.Now > _scheduledstopTime))
                    //{
                    //	_startTime = _startTime.AddDays(1); //otherwise, start tomorrow at start time
                    //	_readyToStarta = false;
                    //}
                    if ((DateTime.Now > _startTime))
                    {
                        if ((DateTime.Now.Subtract(_startTime).TotalMinutes < 1200))                                   //if we're less than x hours past start time, start now
                        {
                            _startTime     = DateTime.Now;
                            _readyToStarta = true;
                        }
                        else
                        {
                            _startTime = _startTime.AddDays(1);                                     //otherwise, start tomorrow at start time
                        }
                    }
                    else
                    if ((_startTime.Subtract(DateTime.Now).TotalMinutes > 1200))                                     //if we're more than x hours shy of start time, start now
                    {
                        _startTime     = DateTime.Now;
                        _readyToStarta = true;
                    }

                    if (_stopTime < _startTime)
                    {
                        _stopTime = _stopTime.AddDays(1);
                    }

                    if (_schedule.RunTime > 0)                             //if runtime is specified, overrides stop time
                    {
                        _stopTime = _startTime.AddHours(_schedule.RunTime);
                    }

                    string _stopTimeText = "No stop time specified";
                    stopTimeSpecified = _schedule.stopTimeSpecified;
                    if (stopTimeSpecified)
                    {
                        _stopTimeText = _stopTime.ToString();
                    }

                    Logging.Log("[Startup] Start Time: " + _startTime + " - Stop Time: " + _stopTimeText);

                    if (!_readyToStarta)
                    {
                        minutesToStart = _startTime.Subtract(DateTime.Now).TotalMinutes;
                        Logging.Log("[Startup] Starting at " + _startTime + ". " + String.Format("{0:0.##}", minutesToStart) + " minutes to go.");
                        _timer.Elapsed += new ElapsedEventHandler(TimerEventProcessor);
                        if (minutesToStart > 0)
                        {
                            _timer.Interval = (int)(minutesToStart * 60000);
                        }
                        else
                        {
                            _timer.Interval = 1000;
                        }
                        _timer.Enabled = true;
                        _timer.Start();
                    }
                    else
                    {
                        _readyToStart = true;
                        Logging.Log("[Startup] Already passed start time.  Starting in 15 seconds.");
                        System.Threading.Thread.Sleep(15000);
                    }
                }

                _directEve          = new DirectEve();
                _directEve.OnFrame += OnFrame;

                while (!_done)
                {
                    System.Threading.Thread.Sleep(50);
                }

                _directEve.Dispose();
            }

            if (!string.IsNullOrEmpty(_username) && !string.IsNullOrEmpty(_password) && !string.IsNullOrEmpty(_character))
            {
                _readyToStart = true;

                _directEve          = new DirectEve();
                _directEve.OnFrame += OnFrame;

                var started = DateTime.Now;

                // Sleep until we're done
                while (!_done)
                {
                    System.Threading.Thread.Sleep(50);
                }

                _directEve.Dispose();

                // If the last parameter is false, then we only auto-login
                if (_loginOnly)
                {
                    return;
                }
            }

            _startTime = DateTime.Now;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmMain());
        }