Ejemplo n.º 1
0
        public static void Load(bool write = true)
        {
            if (commandersDict == null)
            {
                commandersDict = new Dictionary <int, EDCommander>();
            }

            lock (commandersDict)
            {
                commandersDict.Clear();

                var cmdrs = GetCommanders();
                int maxnr = cmdrs.Count == 0 ? 0 : cmdrs.Max(c => c.Nr);

                foreach (EDCommander cmdr in cmdrs)
                {
                    if (!cmdr.Deleted)
                    {
                        commandersDict[cmdr.Nr] = cmdr;
                    }
                }

                if (commandersDict.Count == 0)
                {
                    if (write)
                    {
                        Create("Jameson (Default)");
                    }
                    else
                    {
                        commandersDict[maxnr + 1] = new EDCommander(maxnr + 1, "Jameson (Default)");
                    }
                }

                EDCommander hidden = new EDCommander(-1, "Hidden Log"); // -1 is the hidden commander, add to list to make it
                commandersDict[-1] = hidden;                            // so we give back a valid entry when its selected
            }

            // For  some people sharing their user DB between different computers and having different paths to their journals on those computers.
            if (File.Exists(Path.Combine(EliteDangerousCore.EliteConfigInstance.InstanceOptions.AppDataDirectory, "CommanderPaths.json")))
            {
                JObject jo;

                using (Stream stream = File.OpenRead(Path.Combine(EliteDangerousCore.EliteConfigInstance.InstanceOptions.AppDataDirectory, "CommanderPaths.json")))
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        using (JsonTextReader jreader = new JsonTextReader(reader))
                        {
                            jo = JObject.Load(jreader);
                        }
                    }
                }

                foreach (var kvp in jo)
                {
                    string      name  = kvp.Key;
                    JObject     props = kvp.Value as JObject;
                    EDCommander cmdr  = GetCommander(name);
                    if (props != null && cmdr != null)
                    {
                        cmdr.JournalDir = props["JournalDir"].Str(cmdr.JournalDir);
                    }
                }
            }
        }
Ejemplo n.º 2
0
 public static void Delete(EDCommander cmdr)
 {
     Delete(cmdr.Nr);
 }
Ejemplo n.º 3
0
        public static EDCommander Create(string name       = null, string edsmName = null, string edsmApiKey = null, string journalpath = null,
                                         bool toedsm       = true, bool fromedsm   = false,
                                         bool toeddn       = true,
                                         bool toego        = false, string egoname   = null, string egoapi             = null,
                                         bool toinara      = false, string inaraname = null, string inaraapikey        = null,
                                         string homesystem = null, float mapzoom     = 1.0f, bool mapcentreonselection = true, int mapcolour = -1,
                                         bool toigau       = false)
        {
            EDCommander cmdr = UserDatabase.Instance.ExecuteWithDatabase <EDCommander>(cn =>
            {
                using (DbCommand cmd = cn.Connection.CreateCommand("INSERT INTO Commanders (Name,EdsmName,EdsmApiKey,JournalDir,Deleted, SyncToEdsm, SyncFromEdsm, SyncToEddn, NetLogDir, SyncToEGO, EGOName, EGOAPIKey, SyncToInara, InaraName, InaraAPIKey, HomeSystem, MapColour, MapCentreOnSelection, MapZoom, SyncToIGAU) " +
                                                                   "VALUES (@Name,@EdsmName,@EdsmApiKey,@JournalDir,@Deleted, @SyncToEdsm, @SyncFromEdsm, @SyncToEddn, @NetLogDir, @SyncToEGO, @EGOName, @EGOApiKey, @SyncToInara, @InaraName, @InaraAPIKey, @HomeSystem, @MapColour, @MapCentreOnSelection, @MapZoom, @SyncToIGAU)"))
                {
                    cmd.AddParameterWithValue("@Name", name ?? "");
                    cmd.AddParameterWithValue("@EdsmName", edsmName ?? name ?? "");
                    cmd.AddParameterWithValue("@EdsmApiKey", edsmApiKey ?? "");
                    cmd.AddParameterWithValue("@JournalDir", journalpath ?? "");
                    cmd.AddParameterWithValue("@Deleted", false);
                    cmd.AddParameterWithValue("@SyncToEdsm", toedsm);
                    cmd.AddParameterWithValue("@SyncFromEdsm", fromedsm);
                    cmd.AddParameterWithValue("@SyncToEddn", toeddn);
                    cmd.AddParameterWithValue("@NetLogDir", "");        // Unused field, null out
                    cmd.AddParameterWithValue("@SyncToEGO", toego);
                    cmd.AddParameterWithValue("@EGOName", egoname ?? "");
                    cmd.AddParameterWithValue("@EGOApiKey", egoapi ?? "");
                    cmd.AddParameterWithValue("@SyncToInara", toinara);
                    cmd.AddParameterWithValue("@InaraName", inaraname ?? "");
                    cmd.AddParameterWithValue("@InaraApiKey", inaraapikey ?? "");
                    cmd.AddParameterWithValue("@HomeSystem", homesystem ?? "");
                    cmd.AddParameterWithValue("@MapColour", mapcolour == -1 ? System.Drawing.Color.Red.ToArgb() : mapcolour);
                    cmd.AddParameterWithValue("@MapCentreOnSelection", mapcentreonselection);
                    cmd.AddParameterWithValue("@MapZoom", mapzoom);
                    cmd.AddParameterWithValue("@SyncToIGAU", toigau);
                    cmd.ExecuteNonQuery();
                }

                using (DbCommand cmd = cn.Connection.CreateCommand("SELECT Id FROM Commanders WHERE rowid = last_insert_rowid()"))
                {
                    int nr = Convert.ToInt32(cmd.ExecuteScalar());
                }

                using (DbCommand cmd = cn.Connection.CreateCommand("SELECT * FROM Commanders WHERE rowid = last_insert_rowid()"))
                {
                    using (DbDataReader reader = cmd.ExecuteReader())
                    {
                        reader.Read();
                        {
                            cmdr = new EDCommander(reader);
                        }
                    }
                }

                if (name == null)
                {
                    using (DbCommand cmd = cn.Connection.CreateCommand("UPDATE Commanders SET Name = @Name WHERE rowid = last_insert_rowid()"))
                    {
                        cmd.AddParameterWithValue("@Name", cmdr.Name);
                        cmd.ExecuteNonQuery();
                    }
                }

                return(cmdr);
            });

            commanders[cmdr.Nr] = cmdr;

            return(cmdr);
        }
Ejemplo n.º 4
0
        public static HistoryEntry FromJournalEntry(JournalEntry je, HistoryEntry prev, out bool journalupdate, SQLiteConnectionSystem conn = null, EDCommander cmdr = null)
        {
            ISystem isys    = prev == null ? new SystemClass("Unknown") : prev.System;
            int     indexno = prev == null ? 1 : prev.Indexno + 1;

            int mapcolour = 0;

            journalupdate = false;
            bool starposfromedsm = false;
            bool firstdiscover   = false;

            if (je.EventTypeID == JournalTypeEnum.Location || je.EventTypeID == JournalTypeEnum.FSDJump)
            {
                JournalLocOrJump jl = je as JournalLocOrJump;

                ISystem newsys;

                if (jl != null && jl.HasCoordinate)       // LAZY LOAD IF it has a co-ord.. the front end will when it needs it
                {
                    newsys = new SystemClass(jl.StarSystem, jl.StarPos.X, jl.StarPos.Y, jl.StarPos.Z)
                    {
                        EDSMID         = jl.EdsmID < 0 ? 0 : jl.EdsmID, // pass across the EDSMID for the lazy load process.
                        Faction        = jl.Faction,
                        Government     = jl.EDGovernment,
                        PrimaryEconomy = jl.EDEconomy,
                        Security       = jl.EDSecurity,
                        Population     = jl.Population ?? 0,
                        State          = jl.EDState,
                        Allegiance     = jl.EDAllegiance,
                        UpdateDate     = jl.EventTimeUTC,
                        status         = SystemStatusEnum.EDDiscovery,
                        SystemAddress  = jl.SystemAddress,
                    };

                    // If it was a new system, pass the coords back to the StartJump
                    if (prev != null && prev.journalEntry is JournalStartJump)
                    {
                        prev.System = newsys;       // give the previous startjump our system..
                    }
                }
                else
                {
                    // NOTE Rob: 09-JAN-2018 I've removed the Jumpstart looking up a system by name since they were using up lots of lookup time during history reading.
                    // This is used for pre 2.2 systems without co-ords, which now should be limited.
                    // JumpStart still gets the system when the FSD loc is processed, see above.
                    // Jumpstart was also screwing about with the EDSM ID fill in which was broken.  This is now working again.

                    // Default one
                    newsys        = new SystemClass(jl.StarSystem);
                    newsys.EDSMID = je.EdsmID;

                    ISystem s = SystemCache.FindSystem(newsys, conn); // has no co-ord, did we find it?

                    if (s != null)                                    // found a system..
                    {
                        if (jl != null && jl.HasCoordinate)           // if journal Loc, and journal has a star position, use that instead of EDSM..
                        {
                            s.X = Math.Round(jl.StarPos.X * 32.0) / 32.0;
                            s.Y = Math.Round(jl.StarPos.Y * 32.0) / 32.0;
                            s.Z = Math.Round(jl.StarPos.Z * 32.0) / 32.0;
                        }

                        //Debug.WriteLine("HistoryList found system {0} {1}", s.id_edsm, s.name);
                        newsys = s;

                        if (jl != null && je.EdsmID <= 0 && newsys.EDSMID > 0) // only update on a JL..
                        {
                            journalupdate = true;
                            Debug.WriteLine("HE EDSM ID update requested {0} {1}", newsys.EDSMID, newsys.Name);
                        }
                    }
                    else
                    {
                        newsys.EDSMID = -1;        // mark as checked but not found
                    }
                }

                JournalFSDJump jfsd = je as JournalFSDJump;

                if (jfsd != null)
                {
                    if (jfsd.JumpDist <= 0 && isys.HasCoordinate && newsys.HasCoordinate) // if no JDist, its a really old entry, and if previous has a co-ord
                    {
                        jfsd.JumpDist = isys.Distance(newsys);                            // fill it out here

                        if (jfsd.JumpDist > 0)
                        {
                            journalupdate = true;
                            Debug.WriteLine("Je Jump distance update(3) requested {0} {1} {2}", newsys.EDSMID, newsys.Name, jfsd.JumpDist);
                        }
                    }

                    mapcolour = jfsd.MapColor;
                }

                isys            = newsys;
                starposfromedsm = (jl != null && jl.HasCoordinate) ? jl.StarPosFromEDSM : newsys.HasCoordinate;
                firstdiscover   = jl == null ? false : jl.EDSMFirstDiscover;
            }

            string summary, info, detailed;

            je.FillInformation(out summary, out info, out detailed);

            HistoryEntry he = new HistoryEntry
            {
                Indexno             = indexno,
                EntryType           = je.EventTypeID,
                Journalid           = je.Id,
                journalEntry        = je,
                System              = isys,
                EventTimeUTC        = je.EventTimeUTC,
                MapColour           = mapcolour,
                EdsmSync            = je.SyncedEDSM,
                EDDNSync            = je.SyncedEDDN,
                EGOSync             = je.SyncedEGO,
                StartMarker         = je.StartMarker,
                StopMarker          = je.StopMarker,
                EventSummary        = summary,
                EventDescription    = info,
                EventDetailedInfo   = detailed,
                IsStarPosFromEDSM   = starposfromedsm,
                IsEDSMFirstDiscover = firstdiscover,
                Commander           = cmdr ?? EDCommander.GetCommander(je.CommanderId)
            };


            // WORK out docked/landed state

            if (prev != null)
            {
                if (prev.docked.HasValue)                   // copy docked..
                {
                    he.docked = prev.docked;
                }
                if (prev.landed.HasValue)
                {
                    he.landed = prev.landed;
                }
                if (prev.hyperspace.HasValue)
                {
                    he.hyperspace = prev.hyperspace;
                }
                if (prev.marketId != null)
                {
                    he.marketId = prev.marketId;
                }
                if (prev.wanted.HasValue)
                {
                    he.wanted = prev.wanted;
                }

                he.stationName       = prev.stationName;
                he.shiptype          = prev.shiptype;
                he.shipid            = prev.shipid;
                he.whereami          = prev.whereami;
                he.onCrewWithCaptain = prev.onCrewWithCaptain;
                he.gamemode          = prev.gamemode;
                he.group             = prev.group;
            }

            if (je.EventTypeID == JournalTypeEnum.Location)
            {
                JournalLocation jl = je as JournalLocation;
                he.docked     = jl.Docked;
                he.landed     = jl.Latitude.HasValue;
                he.whereami   = jl.Docked ? jl.StationName : jl.Body;
                he.hyperspace = false;
                he.wanted     = jl.Wanted;
            }
            else if (je.EventTypeID == JournalTypeEnum.Docked)
            {
                JournalDocked jl = je as JournalDocked;
                he.docked      = true;
                he.whereami    = jl.StationName;
                he.stationName = jl.StationName;
                he.marketId    = jl.MarketID;
            }
            else if (je.EventTypeID == JournalTypeEnum.Undocked)
            {
                he.docked      = false;
                he.stationName = null;
                he.marketId    = null;
            }
            else if (je.EventTypeID == JournalTypeEnum.Touchdown)
            {
                he.landed = true;
            }
            else if (je.EventTypeID == JournalTypeEnum.Liftoff)
            {
                he.landed = !(je as JournalLiftoff).PlayerControlled;
            }
            else if (je.EventTypeID == JournalTypeEnum.SupercruiseEntry)
            {
                he.whereami   = (je as JournalSupercruiseEntry).StarSystem;
                he.hyperspace = true;
            }
            else if (je.EventTypeID == JournalTypeEnum.SupercruiseExit)
            {
                he.whereami   = (je as JournalSupercruiseExit).Body;
                he.hyperspace = false;
            }
            else if (je.EventTypeID == JournalTypeEnum.FSDJump)
            {
                JournalFSDJump ju = (je as JournalFSDJump);
                he.whereami   = ju.StarSystem;
                he.hyperspace = true;
                he.wanted     = ju.Wanted;
            }
            else if (je.EventTypeID == JournalTypeEnum.StartJump)
            {
                he.hyperspace = true;   // some of these are just to make sure, as FSDJump will also set it
            }
            else if (je.EventTypeID == JournalTypeEnum.LoadGame)
            {
                JournalLoadGame jl = je as JournalLoadGame;

                he.onCrewWithCaptain = null;        // can't be in a crew at this point
                he.gamemode          = jl.GameMode; // set game mode
                he.group             = jl.Group;    // and group, may be empty
                he.landed            = jl.StartLanded;
                he.hyperspace        = false;

                if (jl.Ship.IndexOf("buggy", StringComparison.InvariantCultureIgnoreCase) == -1)        // load game with buggy, can't tell what ship we get back into, so ignore
                {
                    he.shiptype = (je as JournalLoadGame).Ship;
                    he.shipid   = (je as JournalLoadGame).ShipId;
                }
            }
            else if (je.EventTypeID == JournalTypeEnum.ShipyardBuy)         // BUY does not have ship id, but the new entry will that is written later - journals 8.34
            {
                he.shiptype = (je as JournalShipyardBuy).ShipType;
            }
            else if (je.EventTypeID == JournalTypeEnum.ShipyardNew)
            {
                he.shiptype = (je as JournalShipyardNew).ShipType;
                he.shipid   = (je as JournalShipyardNew).ShipId;
            }
            else if (je.EventTypeID == JournalTypeEnum.ShipyardSwap)
            {
                he.shiptype = (je as JournalShipyardSwap).ShipType;
                he.shipid   = (je as JournalShipyardSwap).ShipId;
            }
            else if (je.EventTypeID == JournalTypeEnum.JoinACrew)
            {
                he.onCrewWithCaptain = (je as JournalJoinACrew).Captain;
            }
            else if (je.EventTypeID == JournalTypeEnum.QuitACrew)
            {
                he.onCrewWithCaptain = null;
            }

            if (prev != null && prev.travelling)      // if we are travelling..
            {
                he.travelled_distance    = prev.travelled_distance;
                he.travelled_missingjump = prev.travelled_missingjump;
                he.travelled_jumps       = prev.travelled_jumps;

                if (he.IsFSDJump && !he.MultiPlayer)   // if jump, and not multiplayer..
                {
                    double dist = ((JournalFSDJump)je).JumpDist;
                    if (dist <= 0)
                    {
                        he.travelled_missingjump++;
                    }
                    else
                    {
                        he.travelled_distance += dist;
                        he.travelled_jumps++;
                    }
                }

                he.travelled_seconds = prev.travelled_seconds;
                TimeSpan diff = he.EventTimeUTC.Subtract(prev.EventTimeUTC);

                if (he.EntryType != JournalTypeEnum.LoadGame && diff < new TimeSpan(2, 0, 0))   // time between last entry and load game is not real time
                {
                    he.travelled_seconds += diff;
                }

                if (he.StopMarker || he.StartMarker)
                {
                    //Debug.WriteLine("Travelling stop at " + he.Indexno);
                    he.travelling         = false;
                    he.EventDetailedInfo += ((he.EventDetailedInfo.Length > 0) ? Environment.NewLine : "") + "Travelled " + he.travelled_distance.ToStringInvariant("0.0") + " LY"
                                            + ", " + he.travelled_jumps + " jumps"
                                            + ((he.travelled_missingjump > 0) ? ", " + he.travelled_missingjump + " unknown distance jumps" : "") +
                                            ", time " + he.travelled_seconds;

                    he.travelled_distance = 0;
                    he.travelled_seconds  = new TimeSpan(0);
                }
                else
                {
                    he.travelling = true;

                    if (he.IsFSDJump)
                    {
                        he.EventDetailedInfo += ((he.EventDetailedInfo.Length > 0) ? Environment.NewLine : "") + "Travelling" +
                                                " distance " + he.travelled_distance.ToString("0.0") + " LY"
                                                + ", " + he.travelled_jumps + " jumps"
                                                + ((he.travelled_missingjump > 0) ? ", " + he.travelled_missingjump + " unknown distance jumps" : "") +
                                                ", time " + he.travelled_seconds;
                    }
                }
            }

            if (he.StartMarker)
            {
                //Debug.WriteLine("Travelling start at " + he.Indexno);
                he.travelling = true;
            }

            return(he);
        }
Ejemplo n.º 5
0
        public static HistoryList LoadHistory(EDJournalClass journalmonitor, Func <bool> cancelRequested, Action <int, string> reportProgress,
                                              string NetLogPath       = null,
                                              bool ForceNetLogReload  = false,
                                              bool ForceJournalReload = false,
                                              bool CheckEdsm          = false,
                                              int CurrentCommander    = Int32.MinValue,
                                              bool Keepuievents       = true)
        {
            HistoryList hist = new HistoryList();
            EDCommander cmdr = null;

            if (CurrentCommander >= 0)
            {
                cmdr = EDCommander.GetCommander(CurrentCommander);
                journalmonitor.ParseJournalFiles(() => cancelRequested(), (p, s) => reportProgress(p, s), forceReload: ForceJournalReload);   // Parse files stop monitor..

                if (NetLogPath != null)
                {
                    string errstr = null;
                    NetLogClass.ParseFiles(NetLogPath, out errstr, EliteConfigInstance.InstanceConfig.DefaultMapColour, () => cancelRequested(), (p, s) => reportProgress(p, s), ForceNetLogReload, currentcmdrid: CurrentCommander);
                }
            }

            reportProgress(-1, "Resolving systems");

            List <JournalEntry> jlist = JournalEntry.GetAll(CurrentCommander).OrderBy(x => x.EventTimeUTC).ThenBy(x => x.Id).ToList();
            List <Tuple <JournalEntry, HistoryEntry> > jlistUpdated = new List <Tuple <JournalEntry, HistoryEntry> >();

            using (SQLiteConnectionSystem conn = new SQLiteConnectionSystem())
            {
                HistoryEntry prev = null;
                foreach (JournalEntry inje in jlist)
                {
                    foreach (JournalEntry je in hist.ProcessJournalEntry(inje)) // pass thru the repeat remover..
                    {
                        if (je.IsUIEvent && !Keepuievents)                      // filter out any UI events
                        {
                            System.Diagnostics.Debug.WriteLine("**** Filter out " + je.EventTypeStr + " on " + je.EventTimeLocal.ToString());
                            continue;
                        }

                        bool         journalupdate = false;
                        HistoryEntry he            = HistoryEntry.FromJournalEntry(je, prev, CheckEdsm, out journalupdate, conn, cmdr);

                        prev = he;

                        hist.historylist.Add(he);

                        if (journalupdate)
                        {
                            jlistUpdated.Add(new Tuple <JournalEntry, HistoryEntry>(je, he));
                        }
                    }
                }
            }

            if (jlistUpdated.Count > 0)
            {
                reportProgress(-1, "Updating journal entries");

                using (SQLiteConnectionUser conn = new SQLiteConnectionUser(utc: true))
                {
                    using (DbTransaction txn = conn.BeginTransaction())
                    {
                        foreach (Tuple <JournalEntry, HistoryEntry> jehe in jlistUpdated)
                        {
                            JournalEntry   je   = jehe.Item1;
                            HistoryEntry   he   = jehe.Item2;
                            JournalFSDJump jfsd = je as JournalFSDJump;
                            if (jfsd != null)
                            {
                                JournalEntry.UpdateEDSMIDPosJump(jfsd.Id, he.System, !jfsd.HasCoordinate && he.System.HasCoordinate, jfsd.JumpDist, conn, txn);
                            }
                        }

                        txn.Commit();
                    }
                }
            }

            // now database has been updated due to initial fill, now fill in stuff which needs the user database

            hist.CommanderId = CurrentCommander;

            hist.ProcessUserHistoryListEntries(h => h.ToList());      // here, we update the DBs in HistoryEntry and any global DBs in historylist

            hist.SendEDSMStatusInfo(hist.GetLast, true);

            return(hist);
        }
Ejemplo n.º 6
0
        // inhistoryrefreshparse = means reading history in batch mode
        // returns null if journal line is bad or its a repeat.. It does not throw
        private JournalEntry ProcessLine(string line, bool inhistoryrefreshparse)
        {
            //   System.Diagnostics.Debug.WriteLine("Line in '" + line + "'");
            int cmdrid = TravelLogUnit.CommanderId.HasValue  ? TravelLogUnit.CommanderId.Value  : -2; //-1 is hidden, -2 is never shown

            if (line.Length == 0)
            {
                return(null);
            }

            JObject jo = JObject.Parse(line, JToken.ParseOptions.AllowTrailingCommas | JToken.ParseOptions.CheckEOL); // parse, null if failed

            if (jo == null)                                                                                           // decode failed, gently return null
            {
                System.Diagnostics.Trace.WriteLine($"{TravelLogUnit.FullName} Bad journal line: {line}");
                return(null);
            }

            JournalEntry je = null;

            try
            {           // use a try block in case anything in the creation goes t**s up
                je = JournalEntry.CreateJournalEntry(jo, true);
            }
            catch
            {
                je = null;
            }

            if (je == null)
            {
                System.Diagnostics.Trace.WriteLine($"{TravelLogUnit.FullName} Bad journal creation: {line}");
                return(null);
            }

            bool toosoon = false;

            if (je.EventTypeID == JournalTypeEnum.Fileheader)
            {
                JournalEvents.JournalFileheader header = (JournalEvents.JournalFileheader)je;

                if ((header.Beta && !EliteConfigInstance.InstanceOptions.DisableBetaCommanderCheck) || EliteConfigInstance.InstanceOptions.ForceBetaOnCommander) // if beta, and not disabled, or force beta
                {
                    TravelLogUnit.Type |= TravelLogUnit.BetaMarker;
                }

                if (header.Part > 1)
                {
                    // if we have a last continued, and its header parts match, and it has a commander, and its not too different in time..
                    if (lastcontinued != null && lastcontinued.Part == header.Part && lastcontinued.CommanderId >= 0 &&
                        Math.Abs(header.EventTimeUTC.Subtract(lastcontinued.EventTimeUTC).TotalSeconds) < 5)
                    {
                        cmdrid = lastcontinued.CommanderId;
                        TravelLogUnit.CommanderId = lastcontinued.CommanderId;      // copy commander across.
                    }
                    else
                    {           // this only works if you have a history... EDD does.
                        JournalEvents.JournalContinued contd = JournalEntry.GetLast <JournalEvents.JournalContinued>(je.EventTimeUTC.AddSeconds(1), e => e.Part == header.Part);

                        // Carry commander over from previous log if it ends with a Continued event.
                        if (contd != null && Math.Abs(header.EventTimeUTC.Subtract(contd.EventTimeUTC).TotalSeconds) < 5 && contd.CommanderId >= 0)
                        {
                            cmdrid = lastcontinued.CommanderId;
                            TravelLogUnit.CommanderId = contd.CommanderId;
                        }
                    }
                }
            }
            else if (je.EventTypeID == JournalTypeEnum.Continued)
            {
                lastcontinued = je as JournalEvents.JournalContinued;       // save.. we are getting a new file soon
            }
            else if (je.EventTypeID == JournalTypeEnum.LoadGame)
            {
                var    jlg     = je as JournalEvents.JournalLoadGame;
                string newname = jlg.LoadGameCommander;

                if ((TravelLogUnit.Type & TravelLogUnit.BetaMarker) == TravelLogUnit.BetaMarker)
                {
                    newname = "[BETA] " + newname;
                }

                EDCommander commander = EDCommander.GetCommander(newname);

                if (commander == null)
                {
                    // in the default condition, we have a hidden commander, and first Cmdr. Jameson.
                    commander = EDCommander.GetListCommanders().FirstOrDefault();
                    if (EDCommander.NumberOfCommanders == 2 && commander != null && commander.Name == "Jameson (Default)")
                    {
                        commander.Name     = newname;
                        commander.EdsmName = newname;
                        EDCommander.Update(new List <EDCommander> {
                            commander
                        }, false);
                    }
                    else
                    {
                        commander = EDCommander.Create(name: newname, journalpath: EDJournalUIScanner.GetDefaultJournalDir().Equals(TravelLogUnit.Path) ? "" : TravelLogUnit.Path);
                    }
                }

                commander.FID = jlg.FID;

                cmdrid = commander.Nr;

                if (!TravelLogUnit.CommanderId.HasValue)        // we do not need to write to DB the TLU at this point, since we read something the upper layers will do that
                {
                    TravelLogUnit.CommanderId = cmdrid;
                    //System.Diagnostics.Trace.WriteLine(string.Format("TLU {0} updated with commander {1} at {2}", TravelLogUnit.Path, cmdrid, TravelLogUnit.Size));
                }
            }
            else if (je is ISystemStationEntry && ((ISystemStationEntry)je).IsTrainingEvent)
            {
                //System.Diagnostics.Trace.WriteLine($"{filename} Training detected:\n{line}");
                return(null);
            }

            if (je is IAdditionalFiles)
            {
                if ((je as IAdditionalFiles).ReadAdditionalFiles(TravelLogUnit.Path, inhistoryrefreshparse, ref jo) == false)     // if failed
                {
                    return(null);
                }
            }

            if (je is JournalEvents.JournalShipyard)                // when going into shipyard
            {
                toosoon      = lastshipyard != null && lastshipyard.Yard.Equals((je as JournalEvents.JournalShipyard).Yard);
                lastshipyard = je as JournalEvents.JournalShipyard;
            }
            else if (je is JournalEvents.JournalStoredShips)        // when going into shipyard
            {
                toosoon = laststoredships != null && CollectionStaticHelpers.Equals(laststoredships.ShipsHere, (je as JournalEvents.JournalStoredShips).ShipsHere) &&
                          CollectionStaticHelpers.Equals(laststoredships.ShipsRemote, (je as JournalEvents.JournalStoredShips).ShipsRemote);
                laststoredships = je as JournalEvents.JournalStoredShips;
            }
            else if (je is JournalEvents.JournalStoredModules)      // when going into outfitting
            {
                toosoon           = laststoredmodules != null && CollectionStaticHelpers.Equals(laststoredmodules.ModuleItems, (je as JournalEvents.JournalStoredModules).ModuleItems);
                laststoredmodules = je as JournalEvents.JournalStoredModules;
            }
            else if (je is JournalEvents.JournalOutfitting)         // when doing into outfitting
            {
                toosoon        = lastoutfitting != null && lastoutfitting.ItemList.Equals((je as JournalEvents.JournalOutfitting).ItemList);
                lastoutfitting = je as JournalEvents.JournalOutfitting;
            }
            else if (je is JournalEvents.JournalMarket)
            {
                toosoon    = lastmarket != null && lastmarket.Equals(je as JournalEvents.JournalMarket);
                lastmarket = je as JournalEvents.JournalMarket;
            }
            else if (je is JournalEvents.JournalCargo)
            {
                var cargo = je as JournalEvents.JournalCargo;
                if (lastcargo != null)
                {
                    toosoon = lastcargo.SameAs(cargo);     // if exactly the same, swallow.
                    System.Diagnostics.Debug.WriteLine("Cargo vs last " + toosoon);
                }
                lastcargo = cargo;
            }
            else if (je is JournalEvents.JournalUndocked || je is JournalEvents.JournalLoadGame)             // undocked, Load Game, repeats are cleared
            {
                lastshipyard      = null;
                laststoredmodules = null;
                lastoutfitting    = null;
                laststoredmodules = null;
                laststoredships   = null;
                lastcargo         = null;
                cqc = (je is JournalEvents.JournalLoadGame) && ((JournalEvents.JournalLoadGame)je).GameMode == null;
            }
            else if (je is JournalEvents.JournalMusic)
            {
                var music = je as JournalEvents.JournalMusic;

                if (music.MusicTrackID == JournalEvents.EDMusicTrackEnum.CQC || music.MusicTrackID == JournalEvents.EDMusicTrackEnum.CQCMenu)
                {
                    cqc = true;
                }
            }
            else if (je is JournalEvents.JournalNavRoute)
            {
                var route = je as JournalEvents.JournalNavRoute;

                if (lastnavroute != null && (route.EventTimeUTC == lastnavroute.EventTimeUTC || route.EventTimeUTC == lastnavroute.EventTimeUTC.AddSeconds(1)))
                {
                    toosoon = true;
                }

                lastnavroute = route;
            }

            if (toosoon)                                                // if seeing repeats, remove
            {
                // System.Diagnostics.Debug.WriteLine("**** Remove as dup " + je.EventTypeStr);
                return(null);
            }

            if (cqc)  // Ignore events if in CQC
            {
                return(null);
            }

            je.SetTLUCommander(TravelLogUnit.ID, cmdrid);

            return(je);
        }
Ejemplo n.º 7
0
        // inhistoryrefreshparse = means reading history in batch mode
        private JournalReaderEntry ProcessLine(string line, bool inhistoryrefreshparse, bool resetOnError)
        {
            int cmdrid = -2;        //-1 is hidden, -2 is never shown

            if (TravelLogUnit.CommanderId.HasValue)
            {
                cmdrid = TravelLogUnit.CommanderId.Value;
                // System.Diagnostics.Trace.WriteLine(string.Format("TLU says commander {0} at {1}", cmdrid, TravelLogUnit.Name));
            }

            if (line.Length == 0)
            {
                return(null);
            }

            JObject      jo = null;
            JournalEntry je = null;

            try
            {
                jo = JObject.Parse(line);
                je = JournalEntry.CreateJournalEntry(jo);
            }
            catch
            {
                System.Diagnostics.Trace.WriteLine($"Bad journal line:\n{line}");

                if (resetOnError)
                {
                    throw;
                }
                else
                {
                    return(null);
                }
            }

            if (je == null)
            {
                System.Diagnostics.Trace.WriteLine($"Bad journal line:\n{line}");
                return(null);
            }

            bool toosoon = false;

            if (je.EventTypeID == JournalTypeEnum.Fileheader)
            {
                JournalEvents.JournalFileheader header = (JournalEvents.JournalFileheader)je;

                if ((header.Beta && !EliteConfigInstance.InstanceOptions.DisableBetaCommanderCheck) || EliteConfigInstance.InstanceOptions.ForceBetaOnCommander) // if beta, and not disabled, or force beta
                {
                    TravelLogUnit.type |= TravelLogUnit.BetaMarker;
                }

                if (header.Part > 1)
                {
                    JournalEvents.JournalContinued contd = JournalEntry.GetLast <JournalEvents.JournalContinued>(je.EventTimeUTC.AddSeconds(1), e => e.Part == header.Part);

                    // Carry commander over from previous log if it ends with a Continued event.
                    if (contd != null && Math.Abs(header.EventTimeUTC.Subtract(contd.EventTimeUTC).TotalSeconds) < 5 && contd.CommanderId >= 0)
                    {
                        TravelLogUnit.CommanderId = contd.CommanderId;
                    }
                }
            }
            else if (je.EventTypeID == JournalTypeEnum.LoadGame)
            {
                string newname = (je as JournalEvents.JournalLoadGame).LoadGameCommander;

                if ((TravelLogUnit.type & TravelLogUnit.BetaMarker) == TravelLogUnit.BetaMarker)
                {
                    newname = "[BETA] " + newname;
                }

                EDCommander commander = EDCommander.GetCommander(newname);

                if (commander == null)
                {
                    // in the default condition, we have a hidden commander, and first Cmdr. Jameson.
                    commander = EDCommander.GetListCommanders().FirstOrDefault();
                    if (EDCommander.NumberOfCommanders == 2 && commander != null && commander.Name == "Jameson (Default)")
                    {
                        commander.Name     = newname;
                        commander.EdsmName = newname;
                        EDCommander.Update(new List <EDCommander> {
                            commander
                        }, false);
                    }
                    else
                    {
                        commander = EDCommander.Create(newname, null, EDJournalClass.GetDefaultJournalDir().Equals(TravelLogUnit.Path) ? "" : TravelLogUnit.Path);
                    }
                }

                cmdrid = commander.Nr;

                if (!TravelLogUnit.CommanderId.HasValue)
                {
                    TravelLogUnit.CommanderId = cmdrid;
                    TravelLogUnit.Update();
//                    System.Diagnostics.Trace.WriteLine(string.Format("TLU {0} updated with commander {1}", TravelLogUnit.Path, cmdrid));
                }
            }
            else if (je is ISystemStationEntry && ((ISystemStationEntry)je).IsTrainingEvent)
            {
                System.Diagnostics.Trace.WriteLine($"Training detected:\n{line}");
                return(null);
            }

            if (je is IAdditionalFiles)
            {
                if ((je as IAdditionalFiles).ReadAdditionalFiles(Path.GetDirectoryName(FileName), inhistoryrefreshparse, ref jo) == false)     // if failed
                {
                    return(null);
                }
            }

            if (je is JournalEvents.JournalShipyard)                // when going into shipyard
            {
                toosoon      = lastshipyard != null && lastshipyard.Yard.Equals((je as JournalEvents.JournalShipyard).Yard);
                lastshipyard = je as JournalEvents.JournalShipyard;
            }
            else if (je is JournalEvents.JournalStoredShips)        // when going into shipyard
            {
                toosoon = laststoredships != null && CollectionStaticHelpers.Equals(laststoredships.ShipsHere, (je as JournalEvents.JournalStoredShips).ShipsHere) &&
                          CollectionStaticHelpers.Equals(laststoredships.ShipsRemote, (je as JournalEvents.JournalStoredShips).ShipsRemote);
                laststoredships = je as JournalEvents.JournalStoredShips;
            }
            else if (je is JournalEvents.JournalStoredModules)      // when going into outfitting
            {
                toosoon           = laststoredmodules != null && CollectionStaticHelpers.Equals(laststoredmodules.ModuleItems, (je as JournalEvents.JournalStoredModules).ModuleItems);
                laststoredmodules = je as JournalEvents.JournalStoredModules;
            }
            else if (je is JournalEvents.JournalOutfitting)         // when doing into outfitting
            {
                toosoon        = lastoutfitting != null && lastoutfitting.ItemList.Equals((je as JournalEvents.JournalOutfitting).ItemList);
                lastoutfitting = je as JournalEvents.JournalOutfitting;
            }
            else if (je is JournalEvents.JournalMarket)
            {
                toosoon    = lastmarket != null && lastmarket.Equals(je as JournalEvents.JournalMarket);
                lastmarket = je as JournalEvents.JournalMarket;
            }
            else if (je is JournalEvents.JournalUndocked || je is JournalEvents.JournalLoadGame)             // undocked, Load Game, repeats are cleared
            {
                lastshipyard      = null;
                laststoredmodules = null;
                lastoutfitting    = null;
                laststoredmodules = null;
                laststoredships   = null;
            }

            if (toosoon)                                                // if seeing repeats, remove
            {
                // System.Diagnostics.Debug.WriteLine("**** Remove as dup " + je.EventTypeStr);
                return(null);
            }

            je.SetTLUCommander(TravelLogUnit.id, cmdrid);

            return(new JournalReaderEntry {
                JournalEntry = je, Json = jo
            });
        }
Ejemplo n.º 8
0
        public void ParseJournalFiles(Func <bool> cancelRequested, Action <int, string> updateProgress, bool forceReload = false)
        {
            List <EDCommander> listCommanders = EDCommander.GetList();

            if (frontierfolder != null && frontierfolder.Length != 0 && Directory.Exists(frontierfolder))
            {
                if (watchers.FindIndex(x => x.m_watcherfolder.Equals(frontierfolder)) < 0)
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("New watch on {0}", frontierfolder));
                    MonitorWatcher mw = new MonitorWatcher(frontierfolder);
                    watchers.Add(mw);
                }
            }

            for (int i = 0; i < listCommanders.Count; i++)             // see if new watchers are needed
            {
                string datapath = GetWatchFolder(listCommanders[i].JournalDir);

                if (datapath == null || datapath.Length == 0 || !Directory.Exists(datapath))
                {
                    continue;
                }

                if (watchers.FindIndex(x => x.m_watcherfolder.Equals(datapath)) >= 0) // if we already have a watch on this folder..
                {
                    continue;                                                         // already done
                }
                System.Diagnostics.Trace.WriteLine(string.Format("New watch on {0}", datapath));
                MonitorWatcher mw = new MonitorWatcher(datapath);
                watchers.Add(mw);
            }

            List <int> tobedeleted = new List <int>();

            for (int i = 0; i < watchers.Count; i++)
            {
                bool found = false;
                for (int j = 0; j < listCommanders.Count; j++)          // all commanders, see if this watch folder is present
                {
                    found |= watchers[i].m_watcherfolder.Equals(GetWatchFolder(listCommanders[j].JournalDir));
                }

                if (!found)
                {
                    tobedeleted.Add(i);
                }
            }

            foreach (int i in tobedeleted)
            {
                System.Diagnostics.Trace.WriteLine(string.Format("Delete watch on {0}", watchers[i].m_watcherfolder));
                MonitorWatcher mw = watchers[i];
                mw.StopMonitor();          // just in case
                watchers.Remove(mw);
            }

            for (int i = 0; i < watchers.Count; i++)                                         // parse files of all folders being watched
            {
                watchers[i].ParseJournalFiles(cancelRequested, updateProgress, forceReload); // may create new commanders at the end, but won't need any new watchers, because they will obv be in the same folder
            }
        }
Ejemplo n.º 9
0
        public void SetupWatchers(bool storejsoninje = false)
        {
            List <EDCommander> listCommanders = EDCommander.GetListCommanders();

            // add the default frontier folder in

            if (!string.IsNullOrEmpty(frontierfolder) && Directory.Exists(frontierfolder)) // if it exists..
            {
                if (watchers.FindIndex(x => x.WatcherFolder.Equals(frontierfolder)) < 0)   // and we are not watching it..
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("New watch on {0}", frontierfolder));
                    JournalMonitorWatcher mw = new JournalMonitorWatcher(frontierfolder, storejsoninje);
                    watchers.Add(mw);

                    StatusMonitorWatcher sw = new StatusMonitorWatcher(frontierfolder, ScanTick);
                    sw.UIEventCallBack += UIEvent;
                    statuswatchers.Add(sw);
                }
            }

            for (int i = 0; i < listCommanders.Count; i++)             // see if new watchers are needed
            {
                string datapath = GetWatchFolder(listCommanders[i].JournalDir);

                if (string.IsNullOrEmpty(datapath) || !Directory.Exists(datapath))  // not exist, ignore
                {
                    continue;
                }

                if (watchers.FindIndex(x => x.WatcherFolder.Equals(datapath)) >= 0) // if we already have a watch on this folder..
                {
                    continue;                                                       // already done
                }
                System.Diagnostics.Trace.WriteLine(string.Format("New watch on {0}", datapath));
                JournalMonitorWatcher mw = new JournalMonitorWatcher(datapath, storejsoninje);
                watchers.Add(mw);

                StatusMonitorWatcher sw = new StatusMonitorWatcher(datapath, ScanTick);
                sw.UIEventCallBack += UIEvent;
                statuswatchers.Add(sw);
            }

            // clean up monitors on journals
            {
                List <int> tobedeleted = new List <int>();
                for (int i = 0; i < watchers.Count; i++)
                {
                    bool found = false;

                    if (frontierfolder != null && watchers[i].WatcherFolder.Equals(frontierfolder))
                    {
                        found = true;
                    }

                    for (int j = 0; j < listCommanders.Count; j++)          // all commanders, see if this watch folder is present
                    {
                        found |= watchers[i].WatcherFolder.Equals(GetWatchFolder(listCommanders[j].JournalDir));
                    }

                    if (!found)
                    {
                        tobedeleted.Add(i);
                    }
                }

                foreach (int i in tobedeleted)
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("Delete watch on {0}", watchers[i].WatcherFolder));
                    JournalMonitorWatcher mw = watchers[i];
                    mw.StopMonitor();          // just in case
                    watchers.Remove(mw);
                }
            }

            // and on status files
            {
                List <int> statustobedeleted = new List <int>();
                for (int i = 0; i < statuswatchers.Count; i++)
                {
                    bool found = false;

                    if (frontierfolder != null && statuswatchers[i].WatcherFolder.Equals(frontierfolder))
                    {
                        found = true;
                    }

                    for (int j = 0; j < listCommanders.Count; j++)          // all commanders, see if this watch folder is present
                    {
                        found |= statuswatchers[i].WatcherFolder.Equals(GetWatchFolder(listCommanders[j].JournalDir));
                    }

                    if (!found)
                    {
                        statustobedeleted.Add(i);
                    }
                }

                foreach (int i in statustobedeleted)
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("Delete status watch on {0}", statuswatchers[i].WatcherFolder));
                    StatusMonitorWatcher mw = statuswatchers[i];
                    mw.StopMonitor();          // just in case
                    statuswatchers.Remove(mw);
                }
            }
        }
Ejemplo n.º 10
0
        public void ParseJournalFiles(Func <bool> cancelRequested, Action <int, string> updateProgress, bool forceReload = false)
        {
            List <EDCommander> listCommanders = EDCommander.GetListCommanders();

            // add the default frontier folder in

            if (!string.IsNullOrEmpty(frontierfolder) && Directory.Exists(frontierfolder)) // if it exists..
            {
                if (watchers.FindIndex(x => x.WatcherFolder.Equals(frontierfolder)) < 0)   // and we are not watching it..
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("New watch on {0}", frontierfolder));
                    JournalMonitorWatcher mw = new JournalMonitorWatcher(frontierfolder);
                    watchers.Add(mw);

                    StatusMonitorWatcher sw = new StatusMonitorWatcher(frontierfolder, ScanTick);
                    sw.UIEventCallBack += UIEvent;
                    statuswatchers.Add(sw);
                }
            }

            for (int i = 0; i < listCommanders.Count; i++)             // see if new watchers are needed
            {
                string datapath = GetWatchFolder(listCommanders[i].JournalDir);

                if (string.IsNullOrEmpty(datapath) || !Directory.Exists(datapath))  // not exist, ignore
                {
                    continue;
                }

                if (watchers.FindIndex(x => x.WatcherFolder.Equals(datapath)) >= 0) // if we already have a watch on this folder..
                {
                    continue;                                                       // already done
                }
                System.Diagnostics.Trace.WriteLine(string.Format("New watch on {0}", datapath));
                JournalMonitorWatcher mw = new JournalMonitorWatcher(datapath);
                watchers.Add(mw);

                StatusMonitorWatcher sw = new StatusMonitorWatcher(datapath, ScanTick);
                sw.UIEventCallBack += UIEvent;
                statuswatchers.Add(sw);
            }

            // clean up monitors on journals
            {
                List <int> tobedeleted = new List <int>();
                for (int i = 0; i < watchers.Count; i++)
                {
                    bool found = false;
                    for (int j = 0; j < listCommanders.Count; j++)          // all commanders, see if this watch folder is present
                    {
                        found |= watchers[i].WatcherFolder.Equals(GetWatchFolder(listCommanders[j].JournalDir));
                    }

                    if (!found)
                    {
                        tobedeleted.Add(i);
                    }
                }

                foreach (int i in tobedeleted)
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("Delete watch on {0}", watchers[i].WatcherFolder));
                    JournalMonitorWatcher mw = watchers[i];
                    mw.StopMonitor();          // just in case
                    watchers.Remove(mw);
                }
            }

            // and on status files
            {
                List <int> statustobedeleted = new List <int>();
                for (int i = 0; i < statuswatchers.Count; i++)
                {
                    bool found = false;
                    for (int j = 0; j < listCommanders.Count; j++)          // all commanders, see if this watch folder is present
                    {
                        found |= statuswatchers[i].WatcherFolder.Equals(GetWatchFolder(listCommanders[j].JournalDir));
                    }

                    if (!found)
                    {
                        statustobedeleted.Add(i);
                    }
                }

                foreach (int i in statustobedeleted)
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("Delete status watch on {0}", statuswatchers[i].WatcherFolder));
                    StatusMonitorWatcher mw = statuswatchers[i];
                    mw.StopMonitor();          // just in case
                    statuswatchers.Remove(mw);
                }
            }

            for (int i = 0; i < watchers.Count; i++)                                         // parse files of all folders being watched
            {
                watchers[i].ParseJournalFiles(cancelRequested, updateProgress, forceReload); // may create new commanders at the end, but won't need any new watchers, because they will obv be in the same folder
            }
        }
Ejemplo n.º 11
0
        public static HistoryEntry FromJournalEntry(JournalEntry je, HistoryEntry prev, bool checkedsm, out bool journalupdate, SQLiteConnectionSystem conn = null, EDCommander cmdr = null)
        {
            ISystem isys    = prev == null ? new SystemClassDB("Unknown") : prev.System;
            int     indexno = prev == null ? 1 : prev.Indexno + 1;

            int mapcolour = 0;

            journalupdate = false;
            bool starposfromedsm = false;
            bool firstdiscover   = false;


            if (je.EventTypeID == JournalTypeEnum.Location || je.EventTypeID == JournalTypeEnum.FSDJump)
            {
                JournalLocOrJump jl   = je as JournalLocOrJump;
                JournalFSDJump   jfsd = je as JournalFSDJump;

                ISystem newsys;

                if (jl.HasCoordinate)       // LAZY LOAD IF it has a co-ord.. the front end will when it needs it
                {
                    newsys         = new SystemClassDB(jl.StarSystem, jl.StarPos.X, jl.StarPos.Y, jl.StarPos.Z);
                    newsys.id_edsm = jl.EdsmID < 0 ? 0 : jl.EdsmID;               // pass across the EDSMID for the lazy load process.

                    if (jfsd != null && jfsd.JumpDist <= 0 && isys.HasCoordinate) // if we don't have a jump distance (pre 2.2) but the last sys does have pos, we can compute distance and update entry
                    {
                        jfsd.JumpDist = SystemClassDB.Distance(isys, newsys);     // fill it out here
                        journalupdate = true;
                    }
                }
                else
                {                           // Default one
                    newsys         = new SystemClassDB(jl.StarSystem);
                    newsys.id_edsm = jl.EdsmID;

                    if (checkedsm)                                              // see if we can find the right system
                    {
                        SystemClassDB s = SystemClassDB.FindEDSM(newsys, conn); // has no co-ord, did we find it?

                        if (s != null)                                          // yes, use, and update the journal with the esdmid, and also the position if we have a co-ord
                        {                                                       // so next time we don't have to do this again..
                            if (jl.HasCoordinate)
                            {
                                s.x = Math.Round(jl.StarPos.X * 32.0) / 32.0;
                                s.y = Math.Round(jl.StarPos.Y * 32.0) / 32.0;
                                s.z = Math.Round(jl.StarPos.Z * 32.0) / 32.0;
                            }

                            newsys = s;

                            if (jfsd != null && jfsd.JumpDist <= 0 && newsys.HasCoordinate && isys.HasCoordinate) // if we don't have a jump distance (pre 2.2) but the last sys does, we can compute
                            {
                                jfsd.JumpDist = SystemClassDB.Distance(isys, newsys);                             // fill it out here.  EDSM systems always have co-ords, but we should check anyway
                                journalupdate = true;
                            }

                            if (jl.EdsmID <= 0 && newsys.id_edsm > 0)
                            {
                                journalupdate = true;
                            }
                        }
                    }
                }

                if (jfsd != null)
                {
                    if (jfsd.JumpDist <= 0 && isys.HasCoordinate && newsys.HasCoordinate) // if no JDist, its a really old entry, and if previous has a co-ord
                    {
                        jfsd.JumpDist = SystemClassDB.Distance(isys, newsys);             // fill it out here
                        journalupdate = true;
                    }

                    mapcolour = jfsd.MapColor;
                }

                isys            = newsys;
                starposfromedsm = jl.HasCoordinate ? jl.StarPosFromEDSM : newsys.HasCoordinate;
                firstdiscover   = jl.EDSMFirstDiscover;
            }

            string summary, info, detailed;

            je.FillInformation(out summary, out info, out detailed);

            HistoryEntry he = new HistoryEntry
            {
                Indexno             = indexno,
                EntryType           = je.EventTypeID,
                Journalid           = je.Id,
                journalEntry        = je,
                System              = isys,
                EventTimeUTC        = je.EventTimeUTC,
                MapColour           = mapcolour,
                EdsmSync            = je.SyncedEDSM,
                EDDNSync            = je.SyncedEDDN,
                EGOSync             = je.SyncedEGO,
                StartMarker         = je.StartMarker,
                StopMarker          = je.StopMarker,
                EventSummary        = summary,
                EventDescription    = info,
                EventDetailedInfo   = detailed,
                IsStarPosFromEDSM   = starposfromedsm,
                IsEDSMFirstDiscover = firstdiscover,
                Commander           = cmdr ?? EDCommander.GetCommander(je.CommanderId)
            };


            // WORK out docked/landed state

            if (prev != null)
            {
                if (prev.docked.HasValue)                   // copy docked..
                {
                    he.docked = prev.docked;
                }
                if (prev.landed.HasValue)
                {
                    he.landed = prev.landed;
                }

                he.shiptype          = prev.shiptype;
                he.shipid            = prev.shipid;
                he.whereami          = prev.whereami;
                he.onCrewWithCaptain = prev.onCrewWithCaptain;
                he.gamemode          = prev.gamemode;
                he.group             = prev.group;
            }

            if (je.EventTypeID == JournalTypeEnum.Location)
            {
                JournalLocation jl = je as JournalLocation;
                he.docked   = jl.Docked;
                he.whereami = jl.Docked ? jl.StationName : jl.Body;
            }
            else if (je.EventTypeID == JournalTypeEnum.Docked)
            {
                JournalDocked jl = je as JournalDocked;
                he.docked   = true;
                he.whereami = jl.StationName;
            }
            else if (je.EventTypeID == JournalTypeEnum.Undocked)
            {
                he.docked = false;
            }
            else if (je.EventTypeID == JournalTypeEnum.Touchdown)
            {
                he.landed = true;
            }
            else if (je.EventTypeID == JournalTypeEnum.Liftoff)
            {
                he.landed = false;
            }
            else if (je.EventTypeID == JournalTypeEnum.SupercruiseEntry)
            {
                he.whereami = (je as JournalSupercruiseEntry).StarSystem;
            }
            else if (je.EventTypeID == JournalTypeEnum.SupercruiseExit)
            {
                he.whereami = (je as JournalSupercruiseExit).Body;
            }
            else if (je.EventTypeID == JournalTypeEnum.FSDJump)
            {
                he.whereami = (je as JournalFSDJump).StarSystem;
            }
            else if (je.EventTypeID == JournalTypeEnum.LoadGame)
            {
                JournalLoadGame jl = je as JournalLoadGame;

                he.onCrewWithCaptain = null;        // can't be in a crew at this point
                he.gamemode          = jl.GameMode; // set game mode
                he.group             = jl.Group;    // and group, may be empty
                he.landed            = jl.StartLanded;

                if (jl.Ship.IndexOf("buggy", StringComparison.InvariantCultureIgnoreCase) == -1)        // load game with buggy, can't tell what ship we get back into, so ignore
                {
                    he.shiptype = (je as JournalLoadGame).Ship;
                    he.shipid   = (je as JournalLoadGame).ShipId;
                }
            }
            else if (je.EventTypeID == JournalTypeEnum.ShipyardBuy)         // BUY does not have ship id, but the new entry will that is written later - journals 8.34
            {
                he.shiptype = (je as JournalShipyardBuy).ShipType;
            }
            else if (je.EventTypeID == JournalTypeEnum.ShipyardNew)
            {
                he.shiptype = (je as JournalShipyardNew).ShipType;
                he.shipid   = (je as JournalShipyardNew).ShipId;
            }
            else if (je.EventTypeID == JournalTypeEnum.ShipyardSwap)
            {
                he.shiptype = (je as JournalShipyardSwap).ShipType;
                he.shipid   = (je as JournalShipyardSwap).ShipId;
            }
            else if (je.EventTypeID == JournalTypeEnum.JoinACrew)
            {
                he.onCrewWithCaptain = (je as JournalJoinACrew).Captain;
            }
            else if (je.EventTypeID == JournalTypeEnum.QuitACrew)
            {
                he.onCrewWithCaptain = null;
            }

            if (prev != null && prev.travelling)      // if we are travelling..
            {
                he.travelled_distance    = prev.travelled_distance;
                he.travelled_missingjump = prev.travelled_missingjump;
                he.travelled_jumps       = prev.travelled_jumps;

                if (he.IsFSDJump && !he.MultiPlayer)   // if jump, and not multiplayer..
                {
                    double dist = ((JournalFSDJump)je).JumpDist;
                    if (dist <= 0)
                    {
                        he.travelled_missingjump++;
                    }
                    else
                    {
                        he.travelled_distance += dist;
                        he.travelled_jumps++;
                    }
                }

                he.travelled_seconds = prev.travelled_seconds;
                TimeSpan diff = he.EventTimeUTC.Subtract(prev.EventTimeUTC);

                if (he.EntryType != JournalTypeEnum.LoadGame && diff < new TimeSpan(2, 0, 0))   // time between last entry and load game is not real time
                {
                    he.travelled_seconds += diff;
                }

                if (he.StopMarker || he.StartMarker)
                {
                    //Debug.WriteLine("Travelling stop at " + he.Indexno);
                    he.travelling         = false;
                    he.EventDetailedInfo += ((he.EventDetailedInfo.Length > 0) ? Environment.NewLine : "") + "Travelled " + he.travelled_distance.ToStringInvariant("0.0") + " LY"
                                            + ", " + he.travelled_jumps + " jumps"
                                            + ((he.travelled_missingjump > 0) ? ", " + he.travelled_missingjump + " unknown distance jumps" : "") +
                                            ", time " + he.travelled_seconds;

                    he.travelled_distance = 0;
                    he.travelled_seconds  = new TimeSpan(0);
                }
                else
                {
                    he.travelling = true;

                    if (he.IsFSDJump)
                    {
                        he.EventDetailedInfo += ((he.EventDetailedInfo.Length > 0) ? Environment.NewLine : "") + "Travelling" +
                                                " distance " + he.travelled_distance.ToString("0.0") + " LY"
                                                + ", " + he.travelled_jumps + " jumps"
                                                + ((he.travelled_missingjump > 0) ? ", " + he.travelled_missingjump + " unknown distance jumps" : "") +
                                                ", time " + he.travelled_seconds;
                    }
                }
            }

            if (he.StartMarker)
            {
                //Debug.WriteLine("Travelling start at " + he.Indexno);
                he.travelling = true;
            }

            return(he);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Constructs a new CurrentCommanderChangedEventArgs class in preparation to send it off in an event.
 /// </summary>
 /// <param name="index">The index of the commander in the list.</param>
 public CurrentCommanderChangedEventArgs(int index)
 {
     Index     = index;
     Commander = EDCommander.GetCommander(index);
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Generate a new commander with the specified parameters, save it to backing storage, and refresh the instantiated list.
        /// </summary>
        /// <param name="name">The in-game name for this commander.</param>
        /// <param name="edsmName">The name for this commander as shown on EDSM.</param>
        /// <param name="edsmApiKey">The API key to interface with EDSM.</param>
        /// <param name="journalpath">Where EDD should monitor for this commander's logs.</param>
        /// <returns>The newly-generated commander.</returns>

        public static EDCommander Create(EDCommander other)
        {
            return(Create(other.name, other.EdsmName, other.APIKey, other.JournalDir, other.syncToEdsm, other.SyncFromEdsm, other.SyncToEddn, other.SyncToEGO, other.EGOName, other.EGOAPIKey));
        }
Ejemplo n.º 14
0
        protected JournalReaderEntry ProcessLine(string line, bool resetOnError)
        {
            int cmdrid = -2;        //-1 is hidden, -2 is never shown

            if (TravelLogUnit.CommanderId.HasValue)
            {
                cmdrid = TravelLogUnit.CommanderId.Value;
                // System.Diagnostics.Trace.WriteLine(string.Format("TLU says commander {0} at {1}", cmdrid, TravelLogUnit.Name));
            }

            if (line.Length == 0)
            {
                return(null);
            }

            JObject      jo = null;
            JournalEntry je = null;

            try
            {
                jo = JObject.Parse(line);
                je = JournalEntry.CreateJournalEntry(jo);
            }
            catch
            {
                System.Diagnostics.Trace.WriteLine($"Bad journal line:\n{line}");

                if (resetOnError)
                {
                    throw;
                }
                else
                {
                    return(null);
                }
            }

            if (je == null)
            {
                System.Diagnostics.Trace.WriteLine($"Bad journal line:\n{line}");
                return(null);
            }

            if (je.EventTypeID == JournalTypeEnum.Fileheader)
            {
                JournalEvents.JournalFileheader header = (JournalEvents.JournalFileheader)je;

                if (header.Beta && !disable_beta_commander_check)
                {
                    TravelLogUnit.type |= 0x8000;
                }

                if (header.Part > 1)
                {
                    JournalEvents.JournalContinued contd = JournalEntry.GetLast <JournalEvents.JournalContinued>(je.EventTimeUTC.AddSeconds(1), e => e.Part == header.Part);

                    // Carry commander over from previous log if it ends with a Continued event.
                    if (contd != null && Math.Abs(header.EventTimeUTC.Subtract(contd.EventTimeUTC).TotalSeconds) < 5 && contd.CommanderId >= 0)
                    {
                        TravelLogUnit.CommanderId = contd.CommanderId;
                    }
                }
            }
            else if (je.EventTypeID == JournalTypeEnum.LoadGame)
            {
                string newname = (je as JournalEvents.JournalLoadGame).LoadGameCommander;

                if ((TravelLogUnit.type & 0x8000) == 0x8000)
                {
                    newname = "[BETA] " + newname;
                }

                EDCommander _commander = EDCommander.GetCommander(newname);

                if (_commander == null)
                {
                    EDCommander onlyc = EDCommander.GetAll().FirstOrDefault();
                    if (EDCommander.NumberOfCommanders == 1 && onlyc != null && onlyc.Name == "Jameson (Default)")
                    {
                        onlyc.Name     = newname;
                        onlyc.EdsmName = newname;
                        EDCommander.Update(new List <EDCommander> {
                            onlyc
                        }, false);
                    }
                    else
                    {
                        _commander = EDCommander.Create(newname, null, EDJournalClass.GetDefaultJournalDir().Equals(TravelLogUnit.Path) ? "" : TravelLogUnit.Path);
                    }
                }

                cmdrid = _commander.Nr;

                if (!TravelLogUnit.CommanderId.HasValue)
                {
                    TravelLogUnit.CommanderId = cmdrid;
                    TravelLogUnit.Update();
                    System.Diagnostics.Trace.WriteLine(string.Format("TLU {0} updated with commander {1}", TravelLogUnit.Path, cmdrid));
                }
            }

            je.TLUId       = (int)TravelLogUnit.id;
            je.CommanderId = cmdrid;

            return(new JournalReaderEntry {
                JournalEntry = je, Json = jo
            });
        }