예제 #1
0
        public void Update(string name, string note, string bookmarknote, string tme, bool regionmark, bool istarget)
        {
            this.Text              = "Update Bookmark";
            buttonOK.Text          = "Update";
            textBoxName.Text       = name;
            textBoxName.ReadOnly   = !regionmark;
            textBoxNotes.Text      = bookmarknote;
            textBoxTravelNote.Text = note;
            textBoxTime.Text       = tme;
            checkBoxTarget.Checked = istarget;

            if (regionmark)
            {
                buttonEDSM.Hide();
                labelTravelNote.Hide();
                labelTravelNoteEdit.Hide();
                textBoxTravelNote.Hide();
                int delta = buttonOK.Location.Y - labelTravelNote.Location.Y;
                ShiftLocationY(buttonOK, delta);
                ShiftLocationY(buttonCancel, delta);
                ShiftLocationY(buttonDelete, delta);
                this.Height -= delta;
            }
            else
            {
                var edsm = new EDSM.EDSMClass();
                edsmurl = edsm.GetUrlToEDSMSystem(name);
            }
        }
예제 #2
0
        public void NotedSystem(string name, string note, bool target)
        {
            this.Text = "System Information";
            buttonCancel.Hide();
            buttonDelete.Hide();
            textBoxNotes.Hide();
            textBoxTime.Hide();
            labelTimeMade.Hide();
            labelBookmarkNotes.Hide();
            textBoxName.Text       = name;
            textBoxTravelNote.Text = (note != null) ? note : "";

            int delta = textBoxTravelNote.Location.Y - checkBoxTarget.Location.Y;       // before we move it

            checkBoxTarget.Location = new Point(checkBoxTarget.Location.X, labelTimeMade.Location.Y);
            buttonEDSM.Location     = new Point(buttonEDSM.Location.X, labelTimeMade.Location.Y);

            ShiftLocationY(buttonOK, delta);
            ShiftLocationY(labelTravelNote, delta);
            ShiftLocationY(labelTravelNoteEdit, delta);
            ShiftLocationY(textBoxTravelNote, delta);
            this.Height           -= delta;
            checkBoxTarget.Checked = target;

            var edsm = new EDSM.EDSMClass();

            edsmurl = edsm.GetUrlToEDSMSystem(name);
        }
 public void TriggerEDSMRefresh()
 {
     SQLiteDBClass db = new SQLiteDBClass();
     EDSMClass edsm = new EDSMClass();
     edsm.GetNewSystems(db);
     db.GetAllSystems();
 }
예제 #4
0
        public void NewSystemBookmark(string name, string note, string tme)
        {
            this.Text              = "New System Bookmark";
            textBoxName.Text       = name;
            textBoxTravelNote.Text = note;
            textBoxTime.Text       = tme;
            buttonDelete.Hide();
            var edsm = new EDSM.EDSMClass();

            edsmurl = edsm.GetUrlToEDSMSystem(name);
        }
예제 #5
0
        // (verified with EDSM 29/9/2016)
        public static void SendComments(string star , string note)
        {
            if (!EDDConfig.Instance.CheckCommanderEDSMAPI)
                return;

            EDSMClass edsm = new EDSMClass();

            Task taskEDSM = Task.Factory.StartNew(() =>
            {
                edsm.SetComment(star, note);
            });
        }
예제 #6
0
        // (verified with EDSM 29/9/2016)
        public static void SendComments(string star , string note, long edsmid = 0)
        {
            EDSMClass edsm = new EDSMClass();

            if (!edsm.IsApiKeySet)
                return;

            Task taskEDSM = Task.Factory.StartNew(() =>
            {
                edsm.SetComment(star, note, edsmid);
            });
        }
예제 #7
0
        // (verified with EDSM 29/9/2016, seen UTC time being sent, and same UTC time on ESDM).
        public static void SendTravelLog(HistoryEntry he)
        {
            if (!EDDConfig.Instance.CheckCommanderEDSMAPI)
                return;

            EDSMClass edsm = new EDSMClass();

            string errmsg;
            Task taskEDSM = Task.Factory.StartNew(() =>
            {                                                   // LOCAL time, there is a UTC converter inside this call
                if (edsm.SendTravelLog(he.System.name, he.EventTimeUTC, he.System.HasCoordinate, he.System.x, he.System.y, he.System.z, out errmsg))
                    he.SetEdsmSync();
            });
        }
예제 #8
0
        // (verified with EDSM 29/9/2016, seen UTC time being sent, and same UTC time on ESDM).
        public static void SendTravelLog(HistoryEntry he)
        {
            EDSMClass edsm = new EDSMClass();

            if (!edsm.IsApiKeySet)
                return;

            string errmsg;
            Task taskEDSM = Task.Factory.StartNew(() =>
            {                                                   // LOCAL time, there is a UTC converter inside this call
                if (edsm.SendTravelLog(he.System.name, he.EventTimeUTC, he.System.HasCoordinate, he.System.x, he.System.y, he.System.z, out errmsg))
                    he.SetEdsmSync();
            });
        }
예제 #9
0
        public bool DownloadFromEDSM()
        {
            try
            {
                EDSMClass edsm = new EDSMClass();
                string url = EDSMClass.ServerAddress + "galactic-mapping/json-edd";
                bool newfile;

                return DownloadFileHandler.DownloadFile(url, GalacticMappingFile, out newfile);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("DownloadFromEDSM exception:" + ex.Message);
            }

            return false;
        }
예제 #10
0
        internal static bool SendTravelLog(EDSMClass edsm, VisitedSystemsClass system, EDDiscoveryForm mainform)
        {
            string json;

            if (!system.HasTravelCoordinates)
            {
                json = edsm.SetLog(system.Name, system.Time);
            }
            else
            {
                json = edsm.SetLogWithPos(system.Name, system.Time, system.X, system.Y, system.Z);
            }

            if (json != null)
            {
                JObject msg = (JObject)JObject.Parse(json);

                int    msgnum = msg["msgnum"].Value <int>();
                string msgstr = msg["msg"].Value <string>();


                if (msgnum == 100 || msgnum == 401 || msgnum == 402 || msgnum == 403)
                {
                    system.EDSM_sync = true;
                    system.Update();
                    return(true);
                }
                else
                {
                    if (mainform != null)
                    {
                        mainform.LogLine("EDSM sync ERROR:" + msgnum.ToString() + ":" + msgstr);
                    }

                    System.Diagnostics.Trace.WriteLine("Error sync:" + msgnum.ToString() + " : " + system.Name);
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
예제 #11
0
        private void GetEDSMDistances()
        {
            try
            {
                if (EDDConfig.UseDistances)
                {
                    EDSMClass edsm = new EDSMClass();
                    EDDBClass eddb = new EDDBClass();
                    string lstdist = _db.GetSettingString("EDSCLastDist", "2010-01-01 00:00:00");
                    string json;

                    // Get distances
                    lstdist = _db.GetSettingString("EDSCLastDist", "2010-01-01 00:00:00");
                    List<DistanceClass> dists = new List<DistanceClass>();

                    if (lstdist.Equals("2010-01-01 00:00:00"))
                    {
                        LogText("Downloading mirrored EDSM distance data. (Might take some time)" + Environment.NewLine);
                        eddb.GetEDSMDistances();
                        json = LoadJsonFile(_fileEDSMDistances);
                        if (json != null)
                        {
                            LogText("Adding mirrored EDSM distance data." + Environment.NewLine);

                            dists = new List<DistanceClass>();
                            dists = DistanceClass.ParseEDSM(json, ref lstdist);
                            LogText("Found " + dists.Count.ToString() + " distances." + Environment.NewLine);

                            Application.DoEvents();
                            DistanceClass.Store(dists);
                            _db.PutSettingString("EDSCLastDist", lstdist);
                        }
                    }

                    LogText("Checking for new distances from EDSM. ");

                    Application.DoEvents();
                    json = edsm.RequestDistances(lstdist);

                    dists = new List<DistanceClass>();
                    dists = DistanceClass.ParseEDSM(json, ref lstdist);

                    if (json == null)
                        LogText("No response from server." + Environment.NewLine);

                    else
                        LogText("Found " + dists.Count.ToString() + " new distances." + Environment.NewLine);

                    Application.DoEvents();
                    DistanceClass.Store(dists);
                    _db.PutSettingString("EDSCLastDist", lstdist);
                }
                _db.GetAllDistances(EDDConfig.UseDistances);  // Load user added distances
                updateMapData();
                OnDistancesLoaded();
                GC.Collect();
            }
            catch (Exception ex)
            {
                LogText("GetEDSMDistances exception:" + ex.Message + Environment.NewLine);
                LogText(ex.StackTrace + Environment.NewLine);
            }
        }
예제 #12
0
        private void buttonSync_Click(object sender, EventArgs e)
        {
            EDSMClass edsm = new EDSMClass();

            if (!edsm.IsApiKeySet)
            {
                MessageBox.Show("Please ensure a commander is selected and it has a EDSM API key set");
                return;
            }

            try
            {
                _discoveryForm.EdsmSync.StartSync(edsm, EDDiscoveryForm.EDDConfig.CurrentCommander.SyncToEdsm, EDDiscoveryForm.EDDConfig.CurrentCommander.SyncFromEdsm, EDDConfig.Instance.DefaultMapColour);
            }
            catch (Exception ex)
            {
                _discoveryForm.LogLine($"EDSM Sync failed: {ex.Message}");
            }
        }
예제 #13
0
 public void NewSystemBookmark(string name, string note, string tme)
 {
     this.Text = "New System Bookmark";
     textBoxName.Text = name;
     textBoxTravelNote.Text = note;
     textBoxTime.Text = tme;
     buttonDelete.Hide();
     var edsm = new EDSM.EDSMClass();
     edsmurl = edsm.GetUrlToEDSMSystem(name);
 }
예제 #14
0
        public bool StartSync(EDSMClass edsm, bool syncto, bool syncfrom, int defmapcolour)
        {
            if (running) // Only start once.
                return false;
            _syncTo = syncto;
            _syncFrom = syncfrom;
            _defmapcolour = defmapcolour;

            ThreadEDSMSync = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(SyncThread));
            ThreadEDSMSync.Name = "EDSM Sync";
            ThreadEDSMSync.IsBackground = true;
            ThreadEDSMSync.Start(edsm);

            return true;
        }
예제 #15
0
        private void viewOnEDSMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IEnumerable<DataGridViewRow> selectedRows = dataGridViewDistances.SelectedCells.Cast<DataGridViewCell>()
                                                                        .Select(cell => cell.OwningRow)
                                                                        .Distinct()
                                                                        .OrderBy(cell => cell.Index);

            this.Cursor = Cursors.WaitCursor;
            var cellVal = selectedRows.First<DataGridViewRow>().Cells[0].Value;
            if (cellVal != null)
            {
                string sysName = cellVal.ToString();
                EDSMClass edsm = new EDSMClass();
                if (!edsm.ShowSystemInEDSM(sysName)) LogTextHighlight("System could not be found - has not been synched or EDSM is unavailable" + Environment.NewLine);
            }
            this.Cursor = Cursors.Default;
        }
예제 #16
0
        private void viewOnEDSMToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            EDSMClass edsm = new EDSMClass();
            long? id_edsm = rightclicksystem.System?.id_edsm;

            if (id_edsm == 0)
            {
                id_edsm = null;
            }

            if (!edsm.ShowSystemInEDSM(rightclicksystem.System.name, id_edsm))
                MessageBox.Show("System could not be found - has not been synched or EDSM is unavailable");

            this.Cursor = Cursors.Default;
        }
        private void StoreSystemNote()
        {
            string txt;

            try
            {
                EDSMClass edsm = new EDSMClass();
                SQLiteDBClass db = new SQLiteDBClass();


                edsm.apiKey = db.GetSettingString("EDSMApiKey", "");
                edsm.commanderName = db.GetSettingString("CommanderName", "");


                if (currentSysPos == null || currentSysPos.curSystem == null)
                    return;

                //SystemPosition sp = (SystemPosition)dataGridView1.Rows[lastRowIndex].Cells[1].Tag;
                txt = richTextBoxNote.Text;

                
                if (currentSysPos.curSystem.Note == null)
                    currentSysPos.curSystem.Note = "";

                if (currentSysPos != null && !txt.Equals(currentSysPos.curSystem.Note))
                {
                    SystemNoteClass sn;
                    List<SystemClass> systems = new List<SystemClass>();

                    if (SQLiteDBClass.globalSystemNotes.ContainsKey(currentSysPos.curSystem.SearchName))
                    {
                        sn = SQLiteDBClass.globalSystemNotes[currentSysPos.curSystem.SearchName];
                        sn.Note = txt;
                        sn.Time = DateTime.Now;

                        sn.Update();
                    }
                    else
                    {
                        sn = new SystemNoteClass();

                        sn.Name = currentSysPos.curSystem.name;
                        sn.Note = txt;
                        sn.Time = DateTime.Now;
                        sn.Add();
                    }

                    
                    currentSysPos.curSystem.Note = txt;
                    dataGridView1.Rows[lastRowIndex].Cells[3].Value = txt;

                    if (edsm.commanderName == null || edsm.apiKey == null)
                        return;

                    if (edsm.commanderName.Length>1 && edsm.apiKey.Length>1)
                        edsm.SetComment(sn);
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("Exception : " + ex.Message);
                System.Diagnostics.Trace.WriteLine(ex.StackTrace);

                LogText("Exception : " + ex.Message, Color.Red);
                LogText(ex.StackTrace, Color.Red);
            }
        }
예제 #18
0
        public void NotedSystem(string name, string note, bool target)
        {
            this.Text = "System Information";
            buttonCancel.Hide();
            buttonDelete.Hide();
            textBoxNotes.Hide();
            textBoxTime.Hide();
            labelTimeMade.Hide();
            labelBookmarkNotes.Hide();
            textBoxName.Text = name;
            textBoxTravelNote.Text = (note != null) ? note : "";

            int delta = textBoxTravelNote.Location.Y - checkBoxTarget.Location.Y;       // before we move it

            checkBoxTarget.Location = new Point(checkBoxTarget.Location.X, labelTimeMade.Location.Y);
            buttonEDSM.Location = new Point(buttonEDSM.Location.X, labelTimeMade.Location.Y);

            ShiftLocationY(buttonOK, delta);
            ShiftLocationY(labelTravelNote, delta);
            ShiftLocationY(labelTravelNoteEdit, delta);
            ShiftLocationY(textBoxTravelNote, delta);
            this.Height -= delta;
            checkBoxTarget.Checked = target;

            var edsm = new EDSM.EDSMClass();
            edsmurl = edsm.GetUrlToEDSMSystem(name);
        }
예제 #19
0
        internal static bool SendTravelLog(EDSMClass edsm, VisitedSystemsClass system, EDDiscoveryForm mainform)
        {
            string json;

            if (!system.HasTravelCoordinates)
                json = edsm.SetLog(system.Name, system.Time);
            else
                json = edsm.SetLogWithPos(system.Name, system.Time, system.X, system.Y, system.Z);

            if (json != null)
            {
                JObject msg = (JObject)JObject.Parse(json);

                int msgnum = msg["msgnum"].Value<int>();
                string msgstr = msg["msg"].Value<string>();

                if (msgnum == 100 || msgnum == 401 || msgnum == 402 || msgnum == 403)
                {
                    system.EDSM_sync = true;
                    system.Update();
                    return true;
                }
                else
                {
                    if (mainform!=null)
                        mainform.LogLine("EDSM sync ERROR:" + msgnum.ToString() + ":" + msgstr);

                    System.Diagnostics.Trace.WriteLine("Error sync:" + msgnum.ToString() + " : " + system.Name);
                    return false;
                }

            }
            else
                return false;
        }
예제 #20
0
        public void Sync()
        {
            try
            {
                EDSMClass edsm = new EDSMClass();

                edsm.apiKey =  EDDiscoveryForm.EDDConfig.CurrentCommander.APIKey;
                edsm.commanderName = EDDiscoveryForm.EDDConfig.CurrentCommander.Name;

                //string comments =  edsm.GetComments(new DateTime(2015, 1, 1));
                List<VisitedSystemsClass> log;
                List<SystemNoteClass> notes;
                int ret = edsm.GetLogs(new DateTime(2011, 1, 1), out log);
                int nret = edsm.GetComments(new DateTime(2011, 1, 1), out notes);

                if (log == null)
                    log = new List<VisitedSystemsClass>();

                if (_syncTo)
                {
                    // Send Unsynced system to EDSM.

                    List<VisitedSystemsClass> systems = (from s in mainForm.VisitedSystems where s.EDSM_sync == false && s.Commander == EDDiscoveryForm.EDDConfig.CurrentCommander.Nr select s).ToList<VisitedSystemsClass>();
                    mainForm.LogLine("EDSM: Sending " + systems.Count.ToString() + " flightlog entries");
                    foreach (var system in systems)
                    {
                        if (Exit)
                        {
                            running = false;
                            return;
                        }

                        if ( system.EDSM_sync == false)
                        {
                            // check if it exist in EDSM
                            VisitedSystemsClass ps2 = (from c in log where c.Name == system.Name && c.Time.Ticks == system.Time.Ticks select c).FirstOrDefault<VisitedSystemsClass>();
                            if (ps2 != null)
                            {
                                system.EDSM_sync = true;
                                system.Update();

                            }
                            else
                            {
                                SendTravelLog(edsm, system, mainForm);

                            }
                        }
                    }
                }

                TravelLogUnit tlu = null;

                bool newsystem = false;
                if (_syncFrom)
                {
                    // Check for new systems from EDSM
                    foreach (var system in log)
                    {
                        VisitedSystemsClass ps2 = mainForm?.VisitedSystems == null ? null :
                            (from c in mainForm.VisitedSystems where c.Name == system.Name && c.Time.Ticks == system.Time.Ticks select c).FirstOrDefault<VisitedSystemsClass>();
                        if (ps2 == null)  // Add to local DB...
                        {
                            if (tlu == null) // If we dontt have a travellogunit yet then create it.
                            {
                                tlu = new TravelLogUnit();

                                tlu.type = 2;  // EDSM
                                tlu.Path = "https://www.edsm.net/api-logs-v1/get-logs";
                                tlu.Name = "EDSM-" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                                tlu.Size = 0;

                                tlu.Add();  // Add to Database
                            }

                            VisitedSystemsClass vs = new VisitedSystemsClass();

                            vs.Source = tlu.id;
                            vs.Unit = tlu.Name;

                            vs.Name = system.Name;
                            vs.Time = system.Time;
                            vs.MapColour = _defmapcolour;
                            vs.EDSM_sync = true;
                            vs.Commander = EDDiscoveryForm.EDDConfig.CurrentCommander.Nr;

                            vs.Add();  // Add to DB;
                            System.Diagnostics.Trace.WriteLine("New from EDSM");
                            newsystem = true;

                        }
                    }

                    // Sync comments from EDSM
                    foreach (var note in notes)
                    {
                        SystemNoteClass dbnote = SystemNoteClass.GetSystemNoteClass(note.Name.ToLower());

                        if ( dbnote != null )       // if there..
                        {
                            if (note.Time > dbnote.Time)
                            {
                                dbnote.Time = note.Time;
                                dbnote.Note = note.Note;
                                dbnote.Update();
                            }
                        }
                        else
                        {
                            note.Add();
                        }
                    }
                }
                mainForm.LogLine("EDSM sync Done");

                if (newsystem)
                    OnNewEDSMTravelLog(this);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("Exception ex:" + ex.Message);
                mainForm.LogLineHighlight("EDSM sync Exception " + ex.Message);
            }
        }
        private void GetEDSCSystems()
        {
            try
            {
                SQLiteDBClass db = new SQLiteDBClass();
                EDSMClass edsm = new EDSMClass();

                string json;

                string rwsystime = db.GetSettingString("RWLastSystems", "2000-01-01 00:00:00"); // Latest time from RW file.
                string rwsysfiletime = "";

                CommanderName = db.GetSettingString("CommanderName", "");
                Invoke((MethodInvoker) delegate {
                    travelHistoryControl1.textBoxCmdrName.Text = CommanderName;
                });

                json = LoadJsonArray(fileTgcSystems);
                List<SystemClass> systems = SystemClass.ParseEDSC(json, ref rwsysfiletime);

                if (!rwsystime.Equals(rwsysfiletime))  // New distance file from Redwizzard
                {
                    SystemClass.Delete(SystemStatusEnum.EDSC); // Remove all EDSC systems.

                    db.PutSettingString("RWLastSystems", rwsysfiletime);
                    db.PutSettingString("EDSMLastSystems", rwsysfiletime);
                    Invoke((MethodInvoker) delegate {
                        TravelHistoryControl.LogText("Adding data from tgcsystems.json " + Environment.NewLine);
                    });
                    SystemClass.Store(systems);
                    EDDBClass eddb = new EDDBClass();
                    DBUpdateEDDB(eddb);
                }

                string retstr = edsm.GetNewSystems(db);
                Invoke((MethodInvoker)delegate
                {
                    TravelHistoryControl.LogText(retstr);
                });

                db.GetAllSystemNotes();
                db.GetAllSystems();

                SystemNames.Clear();
                foreach (SystemClass system in SystemData.SystemList)
                {
                    SystemNames.Add(system.name);
                }

            }
            catch (Exception ex)
            {
                Invoke((MethodInvoker) delegate {
                    TravelHistoryControl.LogText("GetEDSCSystems exception:" + ex.Message + Environment.NewLine);
                });
            }
        }
        private void buttonSync_Click(object sender, EventArgs e)
        {
            if (textBoxCmdrName.Text.Equals(""))
            {
                MessageBox.Show("Please enter commander name before sending distances!");
                return;
            }

            var dists = from p in SQLiteDBClass.dictDistances where p.Value.Status == DistancsEnum.EDDiscovery  orderby p.Value.CreateTime  select p.Value;

            EDSMClass edsm = new EDSMClass();

            foreach (var dist in dists)
            {
                string json, json2;

                if (dist.Dist > 0)
                {
                    LogText("Add distance: " + dist.NameA + " => " + dist.NameB + " :" + dist.Dist.ToString("0.00") + "ly" + Environment.NewLine);
                    json = edsm.SubmitDistances(textBoxCmdrName.Text, dist.NameA, dist.NameB, dist.Dist);
                    json2 = edsc.SubmitDistances(textBoxCmdrName.Text, dist.NameA, dist.NameB, dist.Dist);
                }
                else
                {

                    dist.Delete();
                    return;
                }
                if (json != null)
                {
                    string str="";
                    bool trilok;
                    if (edsm.ShowDistanceResponse(json, out str, out trilok))
                    {
                        LogText(str);
                        dist.Status = DistancsEnum.EDDiscoverySubmitted;
                        dist.Update();
                    }
                    else
                    {
                        LogText(str);
                    }
                }
            }
        }
예제 #23
0
        /*
        private void GetRedWizzardFiles()
        {
            WebClient web = new WebClient();

            try
            {
                LogText("Checking for new EDDiscovery data" + Environment.NewLine);

                //GetNewRedWizzardFile(_fileTgcSystems, "http://robert.astronet.se/Elite/ed-systems/tgcsystems.json");
                //GetNewRedWizzardFile(fileTgcDistances, "http://robert.astronet.se/Elite/ed-systems/tgcdistances.json");
            }
            catch (Exception ex)
            {
                LogText("GetRedWizzardFiles exception:" + ex.Message + Environment.NewLine);
                return;
            }
        }

        private void GetNewRedWizzardFile(string filename, string url)
        {
            string etagFilename = filename + ".etag";

            var request = (HttpWebRequest) HttpWebRequest.Create(url);
            request.UserAgent = "EDDiscovery v" + Assembly.GetExecutingAssembly().FullName.Split(',')[1].Split('=')[1];
            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

            if (File.Exists(etagFilename))
            {
                var etag = File.ReadAllText(etagFilename);
                if (etag != "")
                {
                   request.Headers[HttpRequestHeader.IfNoneMatch] = etag;
                }
            }

            try {
                var response = (HttpWebResponse) request.GetResponse();

                LogText("Downloading " + filename + "..." + Environment.NewLine);

                File.WriteAllText(filename + ".etag.tmp", response.Headers[HttpResponseHeader.ETag]);
                var destFileStream = File.Open(filename + ".tmp", FileMode.Create, FileAccess.Write);
                response.GetResponseStream().CopyTo(destFileStream);

                destFileStream.Close();
                response.Close();

                if (File.Exists(filename))
                    File.Delete(filename);
                if (File.Exists(etagFilename))
                    File.Delete(etagFilename);

                File.Move(filename + ".tmp", filename);
                File.Move(etagFilename + ".tmp", etagFilename);
            } catch (WebException e)
            {
                var code = ((HttpWebResponse) e.Response).StatusCode;
                if (code == HttpStatusCode.NotModified)
                {
                    LogText(filename + " is up to date." + Environment.NewLine);
                } else
                {
                    throw e;
                }
            }
        }
        */
        private void GetEDSMSystems()
        {
            try
            {
                EDSMClass edsm = new EDSMClass();
                string rwsystime = _db.GetSettingString("EDSMLastSystems", "2000-01-01 00:00:00"); // Latest time from RW file.

                CommanderName = _db.GetSettingString("CommanderName", "");
                Invoke((MethodInvoker) delegate {
                    travelHistoryControl1.textBoxCmdrName.Text = CommanderName;
                });

                //                List<SystemClass> systems = SystemClass.ParseEDSC(json, ref rwsysfiletime);
                DateTime edsmdate = DateTime.Parse(rwsystime, new CultureInfo("sv-SE"));

                if (DateTime.Now.Subtract(edsmdate).TotalDays > 7)  // Over 7 days do a sync from EDSM
                {
                    SyncAllEDSMSystems();
                }
                else
                {
                    if (CanSkipSlowUpdates())
                    {
                        LogLine("Skipping loading updates (DEBUG option).");
                        LogLine("  Need to turn this back on again? Look in the Settings tab.");
                    }
                    else
                    {
                        string retstr = edsm.GetNewSystems(_db);
                        Invoke((MethodInvoker)delegate
                        {
                            TravelHistoryControl.LogText(retstr);
                        });
                    }

                }

                _db.GetAllSystemNotes();
                _db.GetAllSystems();

                Invoke((MethodInvoker)delegate
                {
                    SystemNames.Clear();
                    foreach (SystemClass system in SystemData.SystemList)
                    {
                        SystemNames.Add(system.name);
                    }
                });
            }
            catch (Exception ex)
            {
                Invoke((MethodInvoker) delegate {
                    TravelHistoryControl.LogText("GetEDSMSystems exception:" + ex.Message + Environment.NewLine);
                    TravelHistoryControl.LogText(ex.StackTrace + Environment.NewLine);
                });
            }

            GC.Collect();
        }
예제 #24
0
        private void Sync(EDSMClass edsm)
        {
            try
            {
                mainForm.LogLine("EDSM sync begin");

                List <HistoryEntry> hlfsdunsyncedlist = mainForm.history.FilterByNotEDSMSyncedAndFSD; // first entry is oldest

                if (_syncTo && hlfsdunsyncedlist.Count > 0)                                           // send systems to edsm (verified with dates, 29/9/2016, utc throughout)
                {
                    DateTime utcmin = hlfsdunsyncedlist[0].EventTimeUTC.AddDays(-1);                  // 1 days for margin ;-)  only get them back to this date for speed..

                    mainForm.LogLine("EDSM: Sending " + hlfsdunsyncedlist.Count.ToString() + " flightlog entries");

                    List <HistoryEntry> edsmsystemlog = null;
                    edsm.GetLogs(utcmin, out edsmsystemlog);        // always returns a log, time is in UTC as per HistoryEntry and JournalEntry

                    int edsmsystemssent = 0;

                    foreach (var he in hlfsdunsyncedlist)
                    {
                        if (Exit)
                        {
                            running = false;
                            return;
                        }

                        HistoryEntry ps2 = (from c in edsmsystemlog where c.System.name == he.System.name && c.EventTimeUTC.Ticks == he.EventTimeUTC.Ticks select c).FirstOrDefault();

                        if (ps2 != null)                // it did, just make sure EDSM sync flag is set..
                        {
                            he.SetEdsmSync();
                        }
                        else
                        {
                            string errmsg;              // (verified with EDSM 29/9/2016)

                            // it converts to UTC inside the function, supply local for now
                            if (edsm.SendTravelLog(he.System.name, he.EventTimeUTC, he.System.HasCoordinate && !he.IsStarPosFromEDSM, he.System.x, he.System.y, he.System.z, out errmsg))
                            {
                                he.SetEdsmSync();
                            }

                            if (errmsg.Length > 0)
                            {
                                mainForm.LogLine(errmsg);
                            }

                            edsmsystemssent++;
                        }
                    }

                    mainForm.LogLine(string.Format("EDSM Systems sent {0}", edsmsystemssent));
                }

                // TBD Comments to edsm?

                if (_syncFrom)                                                              // Verified ok with time 29/9/2016
                {
                    var json = edsm.GetComments(new DateTime(2011, 1, 1));

                    if (json != null)
                    {
                        JObject msg   = JObject.Parse(json);
                        int     msgnr = msg["msgnum"].Value <int>();

                        JArray comments = (JArray)msg["comments"];
                        if (comments != null)
                        {
                            int commentsadded = 0;

                            foreach (JObject jo in comments)
                            {
                                string name    = jo["system"].Value <string>();
                                string note    = jo["comment"].Value <string>();
                                string utctime = jo["lastUpdate"].Value <string>();
                                int    edsmid  = 0;

                                if (!Int32.TryParse(JSONHelper.GetStringDef(jo["systemId"], "0"), out edsmid))
                                {
                                    edsmid = 0;
                                }

                                DateTime localtime = DateTime.ParseExact(utctime, "yyyy-MM-dd HH:mm:ss",
                                                                         CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToLocalTime();

                                SystemNoteClass curnote = SystemNoteClass.GetNoteOnSystem(name, edsmid);

                                if (curnote != null)
                                {
                                    // curnote uses local time to store
                                    if (localtime.Ticks > curnote.Time.Ticks)   // if newer, add on (verified with EDSM 29/9/2016)
                                    {
                                        curnote.Note  += ". EDSM: " + note;
                                        curnote.Time   = localtime;
                                        curnote.EdsmId = edsmid;
                                        curnote.Update();
                                        commentsadded++;
                                    }
                                }
                                else
                                {
                                    curnote           = new SystemNoteClass();
                                    curnote.Note      = note;
                                    curnote.Time      = localtime;
                                    curnote.Name      = name;
                                    curnote.Journalid = 0;
                                    curnote.EdsmId    = edsmid;
                                    curnote.Add();
                                    commentsadded++;
                                }
                            }

                            mainForm.LogLine(string.Format("EDSM Comments downloaded/updated {0}", commentsadded));
                        }
                    }
                }

                if (_syncFrom)      // verified after struggle 29/9/2016
                {
                    List <HistoryEntry> edsmsystemlog = null;
                    edsm.GetLogs(new DateTime(2011, 1, 1), out edsmsystemlog);        // get the full list of systems
                    edsmsystemlog = edsmsystemlog.OrderBy(s => s.EventTimeUTC).ToList();

                    List <HistoryEntry> hlfsdlist = mainForm.history.FilterByFSD.OrderBy(h => h.EventTimeUTC).ToList();  // FSD jumps only

                    List <HistoryEntry> toadd = new List <HistoryEntry>();

                    int previdx = -1;
                    foreach (HistoryEntry he in edsmsystemlog)      // find out list of ones not present
                    {
                        int index = hlfsdlist.FindIndex(x => x.System.name.Equals(he.System.name, StringComparison.InvariantCultureIgnoreCase) && x.EventTimeUTC.Ticks == he.EventTimeUTC.Ticks);

                        if (index < 0)
                        {
                            // Look for any entries where DST may have thrown off the time
                            foreach (var vi in hlfsdlist.Select((v, i) => new { v = v, i = i }).Where(vi => vi.v.System.name.Equals(he.System.name, StringComparison.InvariantCultureIgnoreCase)))
                            {
                                if (vi.i > previdx)
                                {
                                    double hdiff = vi.v.EventTimeUTC.Subtract(he.EventTimeUTC).TotalHours;
                                    if (hdiff >= -2 && hdiff <= 2 && hdiff == Math.Floor(hdiff))
                                    {
                                        if (vi.v.System.id_edsm <= 0)
                                        {
                                            vi.v.System.id_edsm = 0;
                                            mainForm.history.FillEDSM(vi.v);
                                        }

                                        if (vi.v.System.id_edsm <= 0 || vi.v.System.id_edsm == he.System.id_edsm)
                                        {
                                            index = vi.i;
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        if (index < 0)
                        {
                            toadd.Add(he);
                        }
                        else
                        {
                            previdx = index;
                        }
                    }

                    if (toadd.Count > 0)                         // if we have any, we can add
                    {
                        TravelLogUnit tlu = new TravelLogUnit(); // need a tlu for it
                        tlu.type        = 2;                     // EDSM
                        tlu.Name        = "EDSM-" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                        tlu.Size        = 0;
                        tlu.Path        = "EDSM";
                        tlu.CommanderId = EDDiscoveryForm.EDDConfig.CurrentCommander.Nr;
                        tlu.Add();  // Add to Database

                        using (SQLiteConnectionUser cn = new SQLiteConnectionUser(utc: true))
                        {
                            foreach (HistoryEntry he in toadd)
                            {
                                EDDiscovery.EliteDangerous.JournalEntry je =
                                    EDDiscovery.EliteDangerous.JournalEntry.CreateFSDJournalEntry(tlu.id, tlu.CommanderId.Value, he.EventTimeUTC,
                                                                                                  he.System.name, he.System.x, he.System.y, he.System.z,
                                                                                                  _defmapcolour, (int)EDDiscovery.EliteDangerous.SyncFlags.EDSM);

                                System.Diagnostics.Trace.WriteLine(string.Format("Add {0} {1}", je.EventTimeUTC, he.System.name));
                                je.Add(cn);
                            }
                        }

                        if (OnDownloadedSystems != null)
                        {
                            OnDownloadedSystems();
                        }

                        mainForm.LogLine(string.Format("EDSM downloaded {0} systems", toadd.Count));
                    }
                }

                mainForm.LogLine("EDSM sync Done");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("Exception ex:" + ex.Message);
                mainForm.LogLineHighlight("EDSM sync Exception " + ex.Message);
            }
        }
예제 #25
0
        public void Sync()
        {
            try
            {
                EDSMClass edsm = new EDSMClass();

                edsm.apiKey        = EDDiscoveryForm.EDDConfig.CurrentCommander.APIKey;
                edsm.commanderName = EDDiscoveryForm.EDDConfig.CurrentCommander.Name;

                //string comments =  edsm.GetComments(new DateTime(2015, 1, 1));
                List <VisitedSystemsClass> log;
                List <SystemNoteClass>     notes;
                int ret  = edsm.GetLogs(new DateTime(2011, 1, 1), out log);
                int nret = edsm.GetComments(new DateTime(2011, 1, 1), out notes);

                if (log == null)
                {
                    log = new List <VisitedSystemsClass>();
                }


                if (_syncTo)
                {
                    // Send Unsynced system to EDSM.

                    List <VisitedSystemsClass> systems = (from s in mainForm.VisitedSystems where s.EDSM_sync == false && s.Commander == EDDiscoveryForm.EDDConfig.CurrentCommander.Nr select s).ToList <VisitedSystemsClass>();
                    mainForm.LogLine("EDSM: Sending " + systems.Count.ToString() + " flightlog entries");
                    foreach (var system in systems)
                    {
                        if (Exit)
                        {
                            running = false;
                            return;
                        }

                        if (system.EDSM_sync == false)
                        {
                            // check if it exist in EDSM
                            VisitedSystemsClass ps2 = (from c in log where c.Name == system.Name && c.Time.Ticks == system.Time.Ticks select c).FirstOrDefault <VisitedSystemsClass>();
                            if (ps2 != null)
                            {
                                system.EDSM_sync = true;
                                system.Update();
                            }
                            else
                            {
                                SendTravelLog(edsm, system, mainForm);
                            }
                        }
                    }
                }

                TravelLogUnit tlu = null;

                bool newsystem = false;
                if (_syncFrom)
                {
                    // Check for new systems from EDSM
                    foreach (var system in log)
                    {
                        VisitedSystemsClass ps2 = mainForm?.VisitedSystems == null ? null :
                                                  (from c in mainForm.VisitedSystems where c.Name == system.Name && c.Time.Ticks == system.Time.Ticks select c).FirstOrDefault <VisitedSystemsClass>();
                        if (ps2 == null)     // Add to local DB...
                        {
                            if (tlu == null) // If we dontt have a travellogunit yet then create it.
                            {
                                tlu = new TravelLogUnit();

                                tlu.type = 2;  // EDSM
                                tlu.Path = "https://www.edsm.net/api-logs-v1/get-logs";
                                tlu.Name = "EDSM-" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                                tlu.Size = 0;

                                tlu.Add();  // Add to Database
                            }

                            VisitedSystemsClass vs = new VisitedSystemsClass();

                            vs.Source = tlu.id;
                            vs.Unit   = tlu.Name;

                            vs.Name      = system.Name;
                            vs.Time      = system.Time;
                            vs.MapColour = _defmapcolour;
                            vs.EDSM_sync = true;
                            vs.Commander = EDDiscoveryForm.EDDConfig.CurrentCommander.Nr;


                            vs.Add();  // Add to DB;
                            System.Diagnostics.Trace.WriteLine("New from EDSM");
                            newsystem = true;
                        }
                    }

                    // Sync comments from EDSM
                    foreach (var note in notes)
                    {
                        SystemNoteClass dbnote = SystemNoteClass.GetSystemNoteClass(note.Name.ToLower());

                        if (dbnote != null)         // if there..
                        {
                            if (note.Time > dbnote.Time)
                            {
                                dbnote.Time = note.Time;
                                dbnote.Note = note.Note;
                                dbnote.Update();
                            }
                        }
                        else
                        {
                            note.Add();
                        }
                    }
                }
                mainForm.LogLine("EDSM sync Done");

                if (newsystem)
                {
                    OnNewEDSMTravelLog(this);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("Exception ex:" + ex.Message);
                mainForm.LogLineHighlight("EDSM sync Exception " + ex.Message);
            }
        }
예제 #26
0
        public void Update(string name, string note, string bookmarknote, string tme, bool regionmark , bool istarget )
        {
            this.Text = "Update Bookmark";
            buttonOK.Text = "Update";
            textBoxName.Text = name;
            textBoxName.ReadOnly = !regionmark;
            textBoxNotes.Text = bookmarknote;
            textBoxTravelNote.Text = note;
            textBoxTime.Text = tme;
            checkBoxTarget.Checked = istarget;

            if ( regionmark )
            {
                buttonEDSM.Hide();
                labelTravelNote.Hide();
                labelTravelNoteEdit.Hide();
                textBoxTravelNote.Hide();
                int delta = buttonOK.Location.Y - labelTravelNote.Location.Y;
                ShiftLocationY(buttonOK, delta);
                ShiftLocationY(buttonCancel, delta);
                ShiftLocationY(buttonDelete, delta);
                this.Height -= delta;
            }
            else
            {
                var edsm = new EDSM.EDSMClass();
                edsmurl = edsm.GetUrlToEDSMSystem(name);
            }
        }
        private void buttonSync_Click(object sender, EventArgs e)
        {
            if (textBoxCmdrName.Text.Equals(""))
            {
                MessageBox.Show("Please enter commander name before sending distances/ travel history to EDSM!");
                return;
            }
            var db = new SQLiteDBClass();




            var dists = from p in SQLiteDBClass.dictDistances where p.Value.Status == DistancsEnum.EDDiscovery  orderby p.Value.CreateTime  select p.Value;

            EDSMClass edsm = new EDSMClass();

            foreach (var dist in dists)
            {
                string json;

                if (dist.Dist > 0)
                {
                    LogText("Add distance: " + dist.NameA + " => " + dist.NameB + " :" + dist.Dist.ToString("0.00") + "ly" + Environment.NewLine);
                    json = edsm.SubmitDistances(textBoxCmdrName.Text, dist.NameA, dist.NameB, dist.Dist);
                }
                else
                {
                    if (dist.Dist < 0)  // Can removedistance by adding negative value
                        dist.Delete();
                    else
                    {
                        dist.Status = DistancsEnum.EDDiscoverySubmitted;
                        dist.Update();
                    }
                    json = null;
                }
                if (json != null)
                {
                    string str="";
                    bool trilok;
                    if (edsm.ShowDistanceResponse(json, out str, out trilok))
                    {
                        LogText(str);
                        dist.Status = DistancsEnum.EDDiscoverySubmitted;
                        dist.Update();
                    }
                    else
                    {
                        LogText(str);
                    }
                }
            }

            if (db.GetSettingString("EDSMApiKey", "").Equals(""))
            {
                MessageBox.Show("Please enter EDSM api key (In settings) before sending travel history to EDSM!");
                return;

            }
            sync.StartSync();


        }
예제 #28
0
 public void InitControl(EDDiscoveryForm discoveryForm)
 {
     _discoveryForm = discoveryForm;
     FreezeTrilaterationUI();
     edsm = new EDSMClass();
     edsm.apiKey = EDDiscoveryForm.EDDConfig.CurrentCommander.APIKey;
     edsm.commanderName = EDDiscoveryForm.EDDConfig.CurrentCommander.Name;
     SetTriStatus("Press Start New");
 }
예제 #29
0
        public static List<JournalScan> GetBodiesList(int edsmid)
        {
            List<JournalScan> bodies = new List<JournalScan>();

            EDSMClass edsm = new EDSMClass();

            JObject jo = edsm.GetBodies(edsmid);  // Colonia

            if (jo != null)
            {
                foreach (JObject bodie in jo["bodies"])
                {
                    EDSMClass.ConvertFromEDSMBodies(bodie);
                    JournalScan js = new JournalScan(bodie);
                    js.EdsmID = edsmid;

                    bodies.Add(js);
                }
                return bodies;
            }
            return null;
        }
예제 #30
0
        public void EDSM_Click(object sender, EventArgs e)
        {
            DrawnPanel dp = sender as DrawnPanel;
            Console.WriteLine("EDSM click on " + dp.Name);

            EDSMClass edsm = new EDSMClass();
            string url = edsm.GetUrlToEDSMSystem(dp.Name);

            if (url.Length > 0)         // may pass back empty string if not known, this solves another exception
                System.Diagnostics.Process.Start(url);
            else
                MessageBox.Show("System " + dp.Name + " unknown to EDSM");
        }
예제 #31
0
        public void Sync()
        {
            try
            {
                SQLiteDBClass db = new SQLiteDBClass();
                EDSMClass edsm = new EDSMClass();

                edsm.apiKey = db.GetSettingString("EDSMApiKey", "");
                edsm.commanderName = db.GetSettingString("CommanderName", "");

                //string comments =  edsm.GetComments(new DateTime(2015, 1, 1));
                List<SystemPosition> log;
                int ret = edsm.GetLogs(new DateTime(2011, 1, 1), out log);

                if (log == null)
                    log = new List<SystemPosition>();

                // Send Unsynced system to EDSM.

                List<SystemPosition> systems = (from s in mainForm.VisitedSystems where s.vs !=null && s.vs.EDSM_sync == false select s).ToList<SystemPosition>();
                mainForm.LogLine("EDSM: Sending " +  systems.Count.ToString() + " flightlog entries", Color.Black);
                foreach (var system in systems)
                {
                    string json = null;

                    if (Exit)
                    {
                        running = false;
                        return;
                    }

                    if (system.vs != null && system.vs.EDSM_sync == false)
                    {
                        // check if it exist in EDSM
                        SystemPosition ps2 = (from c in log where c.Name == system.Name && c.time.Ticks == system.time.Ticks select c).FirstOrDefault<SystemPosition>();
                        if (ps2 != null)
                        {
                            system.vs.EDSM_sync = true;
                            system.Update();

                        }
                        else
                            json = edsm.SetLog(system.Name, system.time);

                        if (json != null)
                        {
                            JObject msg = (JObject)JObject.Parse(json);

                            int msgnum = msg["msgnum"].Value<int>();
                            string msgstr = msg["msg"].Value<string>();


                            if (msgnum == 100 || msgnum == 401 || msgnum == 402 || msgnum == 403)
                            {
                                if (msgnum == 100)
                                    System.Diagnostics.Trace.WriteLine("New");

                                system.vs.EDSM_sync = true;
                                system.Update();
                            }
                            else
                            {
                                mainForm.LogLine("EDSM sync ERROR:" + msgnum.ToString() +":" + msgstr, Color.Red);
                                System.Diagnostics.Trace.WriteLine("Error sync:" + msgnum.ToString() + " : " + system.Name);
                                break;
                            }


                        }
                    }
                }

                TravelLogUnit tlu = null;

                // Check for new systems from EDSM
                bool newsystem = false;
                int defaultColour = db.GetSettingInt("DefaultMap", Color.Red.ToArgb());
                foreach (var system in log)
                {
                    SystemPosition ps2 = (from c in mainForm.VisitedSystems where c.Name == system.Name && c.time.Ticks == system.time.Ticks select c).FirstOrDefault<SystemPosition>();
                    if (ps2 == null)  // Add to local DB...
                    {
                        if (tlu == null) // If we dontt have a travellogunit yet then create it. 
                        {
                            tlu = new TravelLogUnit();

                            tlu.type = 2;  // EDSM
                            tlu.Path = "http://www.edsm.net/api-logs-v1/get-logs";
                            tlu.Name = "EDSM-" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                            tlu.Size = 0;

                            tlu.Add();  // Add to Database
                        }

                        VisitedSystemsClass vs = new VisitedSystemsClass();

                        vs.Source = tlu.id;
                        vs.Unit = tlu.Name;

                        vs.Name = system.Name;
                        vs.Time = system.time;
                        vs.MapColour = defaultColour;
                        vs.EDSM_sync = true;
                        

                        vs.Add();  // Add to DB;
                        System.Diagnostics.Trace.WriteLine("New from EDSM");
                        newsystem = true;
                        
                    }
                }
                mainForm.LogLine("EDSM sync Done", Color.Black);

                if (newsystem)
                    OnNewEDSMTravelLog(this);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("Exception ex:" + ex.Message);
                mainForm.LogLine("EDSM sync Exception " + ex.Message, Color.Red);
            }

        }
예제 #32
0
        private void Sync(EDSMClass edsm)
        {
            try
            {
                mainForm.LogLine("EDSM sync begin");

                List<HistoryEntry> hlfsdunsyncedlist = mainForm.history.FilterByNotEDSMSyncedAndFSD;        // first entry is oldest

                if ( _syncTo && hlfsdunsyncedlist.Count > 0 )                   // send systems to edsm (verified with dates, 29/9/2016, utc throughout)
                {
                    DateTime utcmin = hlfsdunsyncedlist[0].EventTimeUTC.AddDays(-1);        // 1 days for margin ;-)  only get them back to this date for speed..

                    mainForm.LogLine("EDSM: Sending " + hlfsdunsyncedlist.Count.ToString() + " flightlog entries");

                    List<HistoryEntry> edsmsystemlog = null;
                    edsm.GetLogs(utcmin, out edsmsystemlog);        // always returns a log, time is in UTC as per HistoryEntry and JournalEntry

                    int edsmsystemssent = 0;

                    foreach (var he in hlfsdunsyncedlist)
                    {
                        if (Exit)
                        {
                            running = false;
                            return;
                        }

                        HistoryEntry ps2 = (from c in edsmsystemlog where c.System.name == he.System.name && c.EventTimeUTC.Ticks == he.EventTimeUTC.Ticks select c).FirstOrDefault();

                        if (ps2 != null)                // it did, just make sure EDSM sync flag is set..
                        {
                            he.SetEdsmSync();
                        }
                        else
                        {
                            string errmsg;              // (verified with EDSM 29/9/2016)

                                                        // it converts to UTC inside the function, supply local for now
                            if ( edsm.SendTravelLog(he.System.name, he.EventTimeUTC, he.System.HasCoordinate && !he.IsStarPosFromEDSM, he.System.x, he.System.y, he.System.z, out errmsg) )
                                he.SetEdsmSync();

                            if (errmsg.Length > 0)
                                mainForm.LogLine(errmsg);

                            edsmsystemssent++;
                        }
                    }

                    mainForm.LogLine(string.Format("EDSM Systems sent {0}", edsmsystemssent));
                }

                // TBD Comments to edsm?

                if ( _syncFrom )                                                            // Verified ok with time 29/9/2016
                {
                    var json = edsm.GetComments(new DateTime(2011, 1, 1));

                    if (json != null)
                    {
                        JObject msg = JObject.Parse(json);
                        int msgnr = msg["msgnum"].Value<int>();

                        JArray comments = (JArray)msg["comments"];
                        if (comments != null)
                        {
                            int commentsadded = 0;

                            foreach (JObject jo in comments)
                            {
                                string name = jo["system"].Value<string>();
                                string note = jo["comment"].Value<string>();
                                string utctime = jo["lastUpdate"].Value<string>();
                                int edsmid = 0;

                                if (!Int32.TryParse(JSONHelper.GetStringDef(jo["systemId"], "0"), out edsmid))
                                    edsmid = 0;

                                DateTime localtime = DateTime.ParseExact(utctime, "yyyy-MM-dd HH:mm:ss",
                                            CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal).ToLocalTime();

                                SystemNoteClass curnote = SystemNoteClass.GetNoteOnSystem(name, edsmid);

                                if (curnote != null)
                                {
                                                                                // curnote uses local time to store
                                    if (localtime.Ticks > curnote.Time.Ticks)   // if newer, add on (verified with EDSM 29/9/2016)
                                    {
                                        curnote.Note += ". EDSM: " + note;
                                        curnote.Time = localtime;
                                        curnote.EdsmId = edsmid;
                                        curnote.Update();
                                        commentsadded++;
                                    }
                                }
                                else
                                {
                                    curnote = new SystemNoteClass();
                                    curnote.Note = note;
                                    curnote.Time = localtime;
                                    curnote.Name = name;
                                    curnote.Journalid = 0;
                                    curnote.EdsmId = edsmid;
                                    curnote.Add();
                                    commentsadded++;
                                }
                            }

                            mainForm.LogLine(string.Format("EDSM Comments downloaded/updated {0}", commentsadded));
                        }
                    }
                }

                if (_syncFrom )     // verified after struggle 29/9/2016
                {
                    List<HistoryEntry> edsmsystemlog = null;
                    edsm.GetLogs(new DateTime(2011, 1, 1), out edsmsystemlog);        // get the full list of systems
                    edsmsystemlog = edsmsystemlog.OrderBy(s => s.EventTimeUTC).ToList();

                    List<HistoryEntry> hlfsdlist = mainForm.history.FilterByTravel.Where(h => h.IsLocOrJump).OrderBy(h => h.EventTimeUTC).ToList();  // FSD jumps only

                    List<HistoryEntry> toadd = new List<HistoryEntry>();

                    int previdx = -1;
                    foreach (HistoryEntry he in edsmsystemlog)      // find out list of ones not present
                    {
                        int index = hlfsdlist.FindIndex(x => x.System.name.Equals(he.System.name, StringComparison.InvariantCultureIgnoreCase) && x.EventTimeUTC.Ticks == he.EventTimeUTC.Ticks);

                        if (index < 0)
                        {
                            // Look for any entries where DST may have thrown off the time
                            foreach (var vi in hlfsdlist.Select((v,i) => new {v = v, i = i}).Where(vi => vi.v.System.name.Equals(he.System.name, StringComparison.InvariantCultureIgnoreCase)))
                            {
                                if (vi.i > previdx)
                                {
                                    double hdiff = vi.v.EventTimeUTC.Subtract(he.EventTimeUTC).TotalHours;
                                    if (hdiff >= -2 && hdiff <= 2 && hdiff == Math.Floor(hdiff))
                                    {
                                        if (vi.v.System.id_edsm <= 0)
                                        {
                                            vi.v.System.id_edsm = 0;
                                            mainForm.history.FillEDSM(vi.v);
                                        }

                                        if (vi.v.System.id_edsm <= 0 || vi.v.System.id_edsm == he.System.id_edsm)
                                        {
                                            index = vi.i;
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        if (index < 0)
                        {
                            toadd.Add(he);
                        }
                        else
                        {
                            previdx = index;
                        }
                    }

                    if ( toadd.Count >0 )  // if we have any, we can add
                    {
                        TravelLogUnit tlu = new TravelLogUnit();    // need a tlu for it
                        tlu.type = 2;  // EDSM
                        tlu.Name = "EDSM-" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                        tlu.Size = 0;
                        tlu.Path = "EDSM";
                        tlu.CommanderId = EDDiscoveryForm.EDDConfig.CurrentCommander.Nr;
                        tlu.Add();  // Add to Database

                        using (SQLiteConnectionUser cn = new SQLiteConnectionUser(utc: true))
                        {
                            foreach (HistoryEntry he in toadd)
                            {
                                EDDiscovery.EliteDangerous.JournalEntry je =
                                    EDDiscovery.EliteDangerous.JournalEntry.CreateFSDJournalEntry(tlu.id, tlu.CommanderId.Value, he.EventTimeUTC,
                                                                                                  he.System.name, he.System.x, he.System.y, he.System.z,
                                                                                                  _defmapcolour, (int)EDDiscovery.EliteDangerous.SyncFlags.EDSM);

                                System.Diagnostics.Trace.WriteLine(string.Format("Add {0} {1}", je.EventTimeUTC, he.System.name));
                                je.Add(cn);
                            }
                        }

                        if (OnDownloadedSystems != null)
                            OnDownloadedSystems();

                        mainForm.LogLine(string.Format("EDSM downloaded {0} systems", toadd.Count));
                    }
                }

                mainForm.LogLine("EDSM sync Done");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("Exception ex:" + ex.Message);
                mainForm.LogLineHighlight("EDSM sync Exception " + ex.Message);
            }
        }
예제 #33
0
        public void Sync(bool pushOnly)
        {
            try
            {
                SQLiteDBClass db   = new SQLiteDBClass();
                EDSMClass     edsm = new EDSMClass();

                edsm.apiKey        = EDDiscoveryForm.EDDConfig.CurrentCommander.APIKey;
                edsm.commanderName = EDDiscoveryForm.EDDConfig.CurrentCommander.Name;

                //string comments =  edsm.GetComments(new DateTime(2015, 1, 1));
                List <SystemPosition> log;
                int ret = edsm.GetLogs(new DateTime(2011, 1, 1), out log);

                if (log == null)
                {
                    log = new List <SystemPosition>();
                }

                // Send Unsynced system to EDSM.

                List <SystemPosition> systems = (from s in mainForm.VisitedSystems where s.vs != null && s.vs.EDSM_sync == false && s.vs.Commander == EDDiscoveryForm.EDDConfig.CurrentCommander.Nr select s).ToList <SystemPosition>();
                mainForm.LogLine("EDSM: Sending " + systems.Count.ToString() + " flightlog entries", Color.Black);
                foreach (var system in systems)
                {
                    string json = null;

                    if (Exit)
                    {
                        running = false;
                        return;
                    }

                    if (system.vs != null && system.vs.EDSM_sync == false)
                    {
                        // check if it exist in EDSM
                        SystemPosition ps2 = (from c in log where c.Name == system.Name && c.time.Ticks == system.time.Ticks select c).FirstOrDefault <SystemPosition>();
                        if (ps2 != null)
                        {
                            system.vs.EDSM_sync = true;
                            system.Update();
                        }
                        else
                        {
                            json = edsm.SetLog(system.Name, system.time);
                        }

                        if (json != null)
                        {
                            JObject msg = (JObject)JObject.Parse(json);

                            int    msgnum = msg["msgnum"].Value <int>();
                            string msgstr = msg["msg"].Value <string>();


                            if (msgnum == 100 || msgnum == 401 || msgnum == 402 || msgnum == 403)
                            {
                                if (msgnum == 100)
                                {
                                    System.Diagnostics.Trace.WriteLine("New");
                                }

                                system.vs.EDSM_sync = true;
                                system.Update();
                            }
                            else
                            {
                                mainForm.LogLine("EDSM sync ERROR:" + msgnum.ToString() + ":" + msgstr, Color.Red);
                                System.Diagnostics.Trace.WriteLine("Error sync:" + msgnum.ToString() + " : " + system.Name);
                                break;
                            }
                        }
                    }
                }

                TravelLogUnit tlu = null;

                bool newsystem = false;
                if (!pushOnly)
                {
                    // Check for new systems from EDSM
                    int defaultColour = db.GetSettingInt("DefaultMap", Color.Red.ToArgb());
                    foreach (var system in log)
                    {
                        SystemPosition ps2 = (from c in mainForm.VisitedSystems where c.Name == system.Name && c.time.Ticks == system.time.Ticks select c).FirstOrDefault <SystemPosition>();
                        if (ps2 == null)     // Add to local DB...
                        {
                            if (tlu == null) // If we dontt have a travellogunit yet then create it.
                            {
                                tlu = new TravelLogUnit();

                                tlu.type = 2;  // EDSM
                                tlu.Path = "http://www.edsm.net/api-logs-v1/get-logs";
                                tlu.Name = "EDSM-" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
                                tlu.Size = 0;

                                tlu.Add();  // Add to Database
                            }

                            VisitedSystemsClass vs = new VisitedSystemsClass();

                            vs.Source = tlu.id;
                            vs.Unit   = tlu.Name;

                            vs.Name      = system.Name;
                            vs.Time      = system.time;
                            vs.MapColour = defaultColour;
                            vs.EDSM_sync = true;


                            vs.Add();  // Add to DB;
                            System.Diagnostics.Trace.WriteLine("New from EDSM");
                            newsystem = true;
                        }
                    }
                }
                mainForm.LogLine("EDSM sync Done", Color.Black);

                if (newsystem)
                {
                    OnNewEDSMTravelLog(this);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("Exception ex:" + ex.Message);
                mainForm.LogLine("EDSM sync Exception " + ex.Message, Color.Red);
            }
        }
 public void InitControl(EDDiscoveryForm discoveryForm)
 {
     _discoveryForm = discoveryForm;
     edsm = new EDSMClass();
     _currentRoute = new SavedRouteClass("");
     _savedRoutes = new List<SavedRouteClass>();
 }
예제 #35
0
        void gotoEDSM()
        {
            HistoryEntry sys = userControlTravelGrid.GetCurrentHistoryEntry;

            if (sys != null)
                _discoveryForm.history.FillEDSM(sys, reload: true);

            if (sys != null && sys.System != null) // solve a possible exception
            {
                if (!String.IsNullOrEmpty(sys.System.name))
                {
                    long? id_edsm = sys.System.id_edsm;
                    if (id_edsm <= 0)
                    {
                        id_edsm = null;
                    }

                    EDSMClass edsm = new EDSMClass();
                    string url = edsm.GetUrlToEDSMSystem(sys.System.name, id_edsm);

                    if (url.Length > 0)         // may pass back empty string if not known, this solves another exception
                        Process.Start(url);
                    else
                        MessageBox.Show("System unknown to EDSM");
                }
            }
        }
예제 #36
0
        private void SubmitToEDSC()
        {
            var travelHistoryControl = _discoveryForm.TravelControl;
            string commanderName = travelHistoryControl.GetCommanderName();

            if (string.IsNullOrEmpty(commanderName))
            {
                MessageBox.Show("Please enter commander name before submitting the system!");
                UnfreezeTrilaterationUI();
                return;
            }

            var distances = new Dictionary<string, double>();
            foreach (var item in lastTrilatelationEntries)
            {
                var system = item.Key;
                var entry = item.Value;
                distances.Add(system.name, entry.Distance);
            }

            var edsc = new EDSCClass();
            var edsm = new EDSMClass();
            //if (!EDSCClass.UseTest)
            //{
            //    Invoke((MethodInvoker) delegate
            //    {
            //        // TODO temporarily mess with EDSC in test mode only
            //        LogText("Forcibly switching to EDSC UseTest mode." + Environment.NewLine, Color.OrangeRed);
            //    });
            //    EDSCClass.UseTest = true;
            //}

            var responseC = edsc.SubmitDistances(commanderName, TargetSystem.name, distances);
            var responseM = edsm.SubmitDistances(commanderName, TargetSystem.name, distances);

            Console.WriteLine(responseC);
            Console.WriteLine(responseM);

            string infoC, infoM;
            bool trilaterationOkC;
            bool trilaterationOkM;
            var responseOkC = edsc.ShowDistanceResponse(responseC, out infoC);
            var responseOkM = edsm.ShowDistanceResponse(responseM, out infoM, out trilaterationOkM);

            trilaterationOkC = infoC.IndexOf("Trilateration succesful") != -1; // FIXME this is ugly
            Console.WriteLine(infoC);

            Invoke((MethodInvoker) delegate
            {
                if (responseOkC && trilaterationOkC)
                {
                    LogText("EDSC submission succeeded, trilateration successful." + Environment.NewLine, Color.Green);
                }
                else if (responseOkC)
                {
                    LogText("EDSC submission succeeded, but trilateration failed. Try adding more distances." + Environment.NewLine, Color.Orange);
                }
                else
                {
                    LogText("EDSC submission failed." + Environment.NewLine, Color.Red);
                }

                if (responseOkM && trilaterationOkM)
                {
                    LogText("EDSM submission succeeded, trilateration successful." + Environment.NewLine, Color.Green);
                }
                else if (responseOkM)
                {
                    LogText("EDSM submission succeeded, but trilateration failed. Try adding more distances." + Environment.NewLine, Color.Orange);
                }
                else
                {
                    LogText("EDSM submission failed." + Environment.NewLine, Color.Red);
                }

            });

            if (responseOkC && trilaterationOkC)
            {
                Invoke((MethodInvoker) delegate
                {
                    //Visible = false;
                    travelHistoryControl.TriggerEDSCRefresh(); // TODO we might eventually avoid this by further parsing EDSC response
                    travelHistoryControl.RefreshHistory();
                });
            }
            else
            {
                Invoke((MethodInvoker) UnfreezeTrilaterationUI);
                lastTrilatelationResult = null;
                lastTrilatelationEntries = null;
            }
        }
예제 #37
0
        private void SyncAllEDSMSystems()
        {
            try
            {
                EDDBClass eddb = new EDDBClass();
                EDSMClass edsm = new EDSMClass();

                string edsmsystems = Path.Combine(Tools.GetAppDataDirectory(), "edsmsystems.json");
                bool newfile = false;
                string  rwsysfiletime = "2014-01-01 00:00:00";
                LogText("Get systems from EDSM." + Environment.NewLine);

                eddb.DownloadFile("http://www.edsm.net/dump/systemsWithCoordinates.json", edsmsystems, out newfile);

                if (newfile)
                {
                    LogText("Adding EDSM systems." + Environment.NewLine);
                    _db.GetAllSystems();
                    string json = LoadJsonFile(edsmsystems);
                    List<SystemClass> systems = SystemClass.ParseEDSM(json, ref rwsysfiletime);

                    List<SystemClass> systems2Store = new List<SystemClass>();

                    foreach (SystemClass system in systems)
                    {
                        // Check if sys exists first
                        SystemClass sys = SystemData.GetSystem(system.name);
                        if (sys == null)
                            systems2Store.Add(system);
                        else if (!sys.name.Equals(system.name) || sys.x != system.x || sys.y!=system.y  || sys.z != system.z)  // Case or position changed
                            systems2Store.Add(system);
                    }
                    SystemClass.Store(systems2Store);
                    systems.Clear();
                    systems = null;
                    systems2Store.Clear();
                    systems2Store = null;
                    json = null;

                    _db.PutSettingString("EDSMLastSystems", rwsysfiletime);
                    _db.GetAllSystems();
                }
                else
                    LogText("No new file." + Environment.NewLine);

                string retstr = edsm.GetNewSystems(_db);
                Invoke((MethodInvoker)delegate
                {
                    TravelHistoryControl.LogText(retstr);
                });

                GC.Collect();
            }
            catch (Exception ex)
            {
                Invoke((MethodInvoker)delegate
                {
                    TravelHistoryControl.LogText("GetAllEDSMSystems exception:" + ex.Message + Environment.NewLine);
                });
            }
        }