Example #1
0
        public JsonResult GetLastTrackerDetail(string systemNumber)
        {
            TrackerInfo trackingInformation = new TrackerInfo();

            try
            {
                var strSQL = "SELECT TOP 1 [Time], [Longitude], [Latitude], [Velocity] FROM " + systemNumber + " " +
                             "WHERE [Time] <= '" + DateTime.Now.AddHours(5) + "' ORDER BY Time DESC";
                trackingInformation = _db.Database.SqlQuery <TrackerInfo>(strSQL).FirstOrDefault();

                if (trackingInformation != null)
                {
                    string latitude  = trackingInformation.Latitude.ToString();
                    string longitude = trackingInformation.Longitude.ToString();
                    trackingInformation.Time.AddHours(-5);
                    trackingInformation.Address = "";
                }

                return(Json(trackingInformation, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                ErrorLog.LogException(ex);
                return(Json(trackingInformation, JsonRequestBehavior.AllowGet));
            }
        }
Example #2
0
        public async Task SendEventAsync(TrackerInfo model, string category, string eventName, string eventValue = null)
        {
            var eventCategory = GetCategoryName(category);
            var gaEvent       = GaEvent.Create(model, eventCategory, eventName, eventValue);

            await FillGaHitAsync(gaEvent);
            await SendDataAsync(gaEvent);
        }
Example #3
0
        public void SetTrackerInfo(GTSLocationMessage theMsg)
        {
            TrackerInfo tracker = theMsg.TrackerDetail;

            _locationMessage   = theMsg;
            _locationMessageId = theMsg.Id;
            _tracker           = tracker;
            _trackerName       = _tracker.Name;
            _objectid          = tracker.Id;
        }
Example #4
0
        public static GTSLocationMessageHistory GetTrackerInfoByDate(string trackerId, DateTime startDate, DateTime endDate)
        {
            List <GTSLocationMessageLite> _messages =
                Management.GetTrackerInfoByDate(trackerId, startDate, endDate);

            TrackerInfo _info = Management.GetTrackerInfo(trackerId);

            GTSLocationMessageHistory history = new GTSLocationMessageHistory(_messages, _info);

            return(history);
        }
Example #5
0
 public TrackerInfo GetInfo(IProperties properties)
 {
     TrackerInfo result = new TrackerInfo();
     result.TypeName = "Beetle.Tracker.TestImpl.Group,Beetle.Tracker.TestImpl";
     TestProperties tp = new TestProperties();
     tp.FromHeaders(properties.ToHeaders());
     Group group = mGroups.Find(e => e.Name == tp.Group);
     if (group == null)
         return null;
     result.Data= Formater.ToStringValue(group);
     return result;
 }
Example #6
0
 // init
 public void init(int port, TrackerInfo trackerInfo, int timeWaitMiliseconds = 60000, int milisecondsForVibration = 500)
 {
     puerto           = port;
     this.trackerInfo = trackerInfo;
     timeWait         = timeWaitMiliseconds;
     vibrationTime    = milisecondsForVibration;
     listeners        = new List <InputMovileInterface>();
     receiveThread    = new Thread(
         new ThreadStart(ReceiveData));
     receiveThread.IsBackground = true;
     receiveThread.Start();
     sendThread = new Thread(
         new ThreadStart(SendData));
     sendThread.IsBackground = true;
     sendThread.Start();
 }
Example #7
0
 public static GaEvent Create(TrackerInfo src, string category, string action, string value)
 {
     return(new GaEvent
     {
         Type = GaHitType.GaEvent,
         EventCategory = category,
         EventAction = action,
         EventValue = value,
         UserId = src.UserId,
         UserAgent = src.UserAgent,
         ClientInfo = src.ClientInfo,
         Ip = src.Ip.SanitizeIp(),
         CreatedAt = src.CreatedAt,
         Cid = src.Cid
     });
 }
Example #8
0
        public TrackerInfo GetInfo(IProperties properties)
        {
            TrackerInfo result = new TrackerInfo();

            result.TypeName = "Beetle.Tracker.TestImpl.Group,Beetle.Tracker.TestImpl";
            TestProperties tp = new TestProperties();

            tp.FromHeaders(properties.ToHeaders());
            Group group = mGroups.Find(e => e.Name == tp.Group);

            if (group == null)
            {
                return(null);
            }
            result.Data = Formater.ToStringValue(group);
            return(result);
        }
Example #9
0
 public TrackerEvent(GTSDataStorage.Event eventt) : base(eventt)
 {
     if (eventt.ExtendedProperties != null)
     {
         XDocument doc  = XDocument.Parse(eventt.ExtendedProperties);
         XElement  name = doc.Descendants("TrackerName").FirstOrDefault();
         if (name != null)
         {
             _trackerName = name.Value;
         }
         XElement locmsg = doc.Descendants("LocationMessageID").FirstOrDefault();
         if (locmsg != null)
         {
             int.TryParse(locmsg.Value, out _locationMessageId);
             this._locationMessage = GTSBizObjects.Management.GetLocationMessageById(_locationMessageId);
             this._tracker         = _locationMessage.TrackerDetail;
         }
     }
 }
        private void SetTrackersList(List <Tuple <string, string> > list, PipeCommands.SetTrackerSerialNumbers setting)
        {
            TrackersList.Clear();
            list.Add(Tuple.Create("HMD", default(string)));
            list.Add(Tuple.Create("コントローラー", default(string)));
            list.Add(Tuple.Create("トラッカー", default(string)));
            list.Add(Tuple.Create("割り当てしない", default(string)));
            foreach (var d in list.OrderBy(d => d.Item1).ThenBy(d => d.Item2))
            {
                var trackerinfo = new TrackerInfo {
                    TypeName = d.Item1, SerialNumber = d.Item2, Background = WhiteBrush
                };
                TrackersList.Add(trackerinfo);
                if (d.Item2 != null)
                {
                    TrackersViewList.Add(trackerinfo);
                }
            }
            Func <Tuple <string, string>, TrackerInfo> getItem = (set) =>
            {
                var item = TrackersList.Where(d => d.TypeName == set.Item1 && d.SerialNumber == set.Item2).FirstOrDefault();
                if (item == null)
                {
                    var newitem = new TrackerInfo {
                        TypeName = set.Item1, SerialNumber = set.Item2, Background = WhiteBrush
                    }; TrackersList.Add(newitem); item = newitem;
                }
                return(item);
            };

            IsSetting = true;
            HeadTrackerComboBox.SelectedItem       = getItem(setting.Head);
            LeftHandTrackerComboBox.SelectedItem   = getItem(setting.LeftHand);
            RightHandTrackerComboBox.SelectedItem  = getItem(setting.RightHand);
            PelvisTrackerComboBox.SelectedItem     = getItem(setting.Pelvis);
            LeftFootTrackerComboBox.SelectedItem   = getItem(setting.LeftFoot);
            RightFootTrackerComboBox.SelectedItem  = getItem(setting.RightFoot);
            LeftElbowTrackerComboBox.SelectedItem  = getItem(setting.LeftElbow);
            RightElbowTrackerComboBox.SelectedItem = getItem(setting.RightElbow);
            LeftKneeTrackerComboBox.SelectedItem   = getItem(setting.LeftKnee);
            RightKneeTrackerComboBox.SelectedItem  = getItem(setting.RightKnee);
        }
Example #11
0
            static UnitTracker()
            {
                foreach (var hero in GameObjects.Heroes.Where(i => !i.IsMe && !StoredList.ContainsKey(i.NetworkId)))
                {
                    var info = new TrackerInfo();
                    info.AttackTick = info.StopTick = TickCount;
                    StoredList.Add(hero.NetworkId, info);
                }

                Obj_AI_Base.OnProcessSpellCast += (sender, args) =>
                {
                    if (sender.IsMe || !(sender is Obj_AI_Hero) || !StoredList.ContainsKey(sender.NetworkId) ||
                        !AutoAttack.IsAutoAttack(args.SData.Name))
                    {
                        return;
                    }
                    StoredList[sender.NetworkId].AttackTick = TickCount;
                };
                Obj_AI_Base.OnNewPath += (sender, args) =>
                {
                    if (sender.IsMe || !(sender is Obj_AI_Hero) || !StoredList.ContainsKey(sender.NetworkId))
                    {
                        return;
                    }
                    if (args.Path.Length == 1 && !sender.IsMoving)
                    {
                        StoredList[sender.NetworkId].StopTick = TickCount;
                    }
                    else
                    {
                        StoredList[sender.NetworkId].Paths.Add(
                            new PathInfo {
                            Position = args.Path.Last().ToVector2(), Time = Game.Time
                        });
                    }
                    if (StoredList[sender.NetworkId].Paths.Count > 3)
                    {
                        StoredList[sender.NetworkId].Paths.RemoveAt(0);
                    }
                };
            }
Example #12
0
        public async Task SendWithdrawDepositEventAsync(WithdrawDepositInfo model)
        {
            BaseAssetSettings baseAsset = GetBaseAsset(model.AssetId);

            if (baseAsset == null)
            {
                _log.WriteWarning(nameof(SendWithdrawDepositEventAsync), model.UserId, $"{model.AssetId} is not tracked. (asset is not in Fiat or Crypto lists)");
                return;
            }

            var assetAmount = await GetAmountAsync(model.AssetId, model.Amount, baseAsset.AssetId);

            if (assetAmount == 0)
            {
                _log.WriteWarning(nameof(SendWithdrawDepositEventAsync), model.UserId, $"Can't convert {model.Amount} {model.AssetId} to {baseAsset.AssetId} (Multiplier = {baseAsset.Multiplier})");
                return;
            }

            var walletEventName = await GetWalletEventNameAsync(assetAmount, model.AssetId);

            var eventName = GetDepositWithdrawEventName(assetAmount, model.AssetId, baseAsset.Multiplier);

            if (eventName == null)
            {
                return;
            }

            var trackerInfo = new TrackerInfo
            {
                Ip         = model.Ip,
                UserAgent  = model.UserAgent,
                UserId     = model.UserId,
                ClientInfo = model.ClientInfo
            };

            await SendEventAsync(trackerInfo, TrackerCategories.Wallet, walletEventName);
            await SendEventAsync(trackerInfo, TrackerCategories.Wallet, eventName, Math.Round(Math.Abs(assetAmount *baseAsset.Multiplier)).ToString(CultureInfo.InvariantCulture));
        }
        public JsonResult GetDepartureTimeAtPlant(string systemNumber, decimal longitude, decimal latitude, DateTime date, DateTime standard)
        {
            TrackerInfo trackingInformation = new TrackerInfo();

            try
            {
                string strSQL = "SELECT Top 1 Time, Longitude, Latitude, Velocity, Distance " +
                                "From (SELECT Time, Longitude, Latitude, Velocity, (6371.393 * " +
                                "acos (cos ( radians(" + latitude + ") ) * cos( radians( Latitude ) ) * " +
                                "cos( radians( Longitude ) - radians(" + longitude + ") ) + " +
                                "sin ( radians(" + latitude + ") ) * sin( radians( Latitude ) ) ) ) AS distance " +
                                "FROM " + systemNumber + ") X Where Distance <= 0.5 And Time < '" + date + "' And Time > '" + standard + "' " +
                                "Order By Time Desc";
                trackingInformation = db.Database.SqlQuery <TrackerInfo>(strSQL).FirstOrDefault();

                return(Json(trackingInformation, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                ErrorLog.LogException(ex);
                return(Json(trackingInformation, JsonRequestBehavior.AllowGet));
            }
        }
Example #14
0
 public void Track(TrackerInfo trackerInfo)
 {
     Console.WriteLine(trackerInfo.ToString());
 }
Example #15
0
        public JsonResult GetMinMax(string systemNumber, decimal longitude, decimal latitude, decimal distance, DateTime startDate, DateTime endDate)
        {
            try
            {
                SqlParameter[] sqlParameters =
                {
                    new SqlParameter("@systemNumber", SqlDbType.NVarChar)
                    {
                        Value = systemNumber
                    },
                    new SqlParameter("@longitude", SqlDbType.Decimal)
                    {
                        Value = longitude
                    },
                    new SqlParameter("@latitude", SqlDbType.Decimal)
                    {
                        Value = latitude
                    },
                    new SqlParameter("@startDate", SqlDbType.DateTime)
                    {
                        Value = startDate
                    },
                    new SqlParameter("@endDate", SqlDbType.DateTime)
                    {
                        Value = endDate
                    }
                };

                string strSQL = "IF EXISTS (SELECT name FROM sysobjects WHERE type='U' AND name='" + systemNumber + "') " +
                                "SELECT Time, Longitude, Latitude, Velocity FROM " + systemNumber + " " +
                                "WHERE Time BETWEEN @startDate AND @endDate AND Locate=1 ORDER BY Time ASC";

                var trackingInformation = (_db.Database.SqlQuery <TrackerInfo>(strSQL, sqlParameters)).OrderBy(t => t.Time).ToList();
                var trackingInfo        = new List <TrackerInfo>();
                var responseData        = new List <ResponseData>();

                if (trackingInformation.Count > 0)
                {
                    TrackerInfo min         = new TrackerInfo();
                    TrackerInfo minDriveOut = new TrackerInfo();
                    TrackerInfo max         = new TrackerInfo();

                    //Get min time within bound
                    foreach (var info in trackingInformation)
                    {
                        if (GetDistanceTo(Convert.ToDouble(latitude), Convert.ToDouble(longitude), Convert.ToDouble(info.Latitude), Convert.ToDouble(info.Longitude)) <= Convert.ToDouble(distance) && info.Time > startDate && info.Time < endDate)
                        {
                            min = info;
                            break;
                        }
                    }

                    // Get drive in time outside bound
                    if (min != null && !min.Time.ToString().Contains("0001"))
                    {
                        SqlParameter[] minSqlParameters =
                        {
                            new SqlParameter("@minStartDate", SqlDbType.DateTime)
                            {
                                Value = min.Time.AddDays(-3)
                            },
                            new SqlParameter("@minEndDate", SqlDbType.DateTime)
                            {
                                Value = min.Time
                            }
                        };

                        string strMinSQL = "IF EXISTS (SELECT name FROM sysobjects WHERE type='U' AND name='" + systemNumber + "') " +
                                           "SELECT Time, Longitude, Latitude, Velocity FROM " + systemNumber + " " +
                                           "WHERE Time BETWEEN @minStartDate AND @minEndDate AND Locate=1 ORDER BY Time ASC";

                        var minTrackingInformation = (_db.Database.SqlQuery <TrackerInfo>(strMinSQL, minSqlParameters)).OrderByDescending(t => t.Time).ToList();

                        foreach (var item in minTrackingInformation)
                        {
                            if (GetDistanceTo(Convert.ToDouble(latitude), Convert.ToDouble(longitude), Convert.ToDouble(item.Latitude), Convert.ToDouble(item.Longitude)) <= Convert.ToDouble(distance))
                            {
                                min = item;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    //Get first drive out time
                    if (min != null && !min.Time.ToString().Contains("0001"))
                    {
                        var updatedTrackingInformation = trackingInformation.Where(t => t.Time > min.Time).OrderBy(t => t.Time).ToList();
                        if (updatedTrackingInformation.Count > 0)
                        {
                            foreach (var data in updatedTrackingInformation)
                            {
                                if (GetDistanceTo(Convert.ToDouble(latitude), Convert.ToDouble(longitude), Convert.ToDouble(data.Latitude), Convert.ToDouble(data.Longitude)) <= Convert.ToDouble(distance))
                                {
                                    minDriveOut = data;
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }

                    //Get max time within bound
                    foreach (var info in trackingInformation.OrderByDescending(t => t.Time))
                    {
                        if (GetDistanceTo(Convert.ToDouble(latitude), Convert.ToDouble(longitude), Convert.ToDouble(info.Latitude), Convert.ToDouble(info.Longitude)) <= Convert.ToDouble(distance) && info.Time >= startDate && info.Time <= endDate)
                        {
                            max = info;
                            break;
                        }
                    }

                    // Get drive out time outside bound
                    if (max != null && !max.Time.ToString().Contains("0001"))
                    {
                        SqlParameter[] maxSqlParameters =
                        {
                            new SqlParameter("@maxStartDate", SqlDbType.DateTime)
                            {
                                Value = max.Time
                            },
                            new SqlParameter("@maxEndDate", SqlDbType.DateTime)
                            {
                                Value = max.Time.AddDays(3)
                            }
                        };

                        string strMaxSQL = "IF EXISTS (SELECT name FROM sysobjects WHERE type='U' AND name='" + systemNumber + "') " +
                                           "SELECT Time, Longitude, Latitude, Velocity FROM " + systemNumber + " " +
                                           "WHERE Time BETWEEN @maxStartDate AND @maxEndDate AND Locate=1 ORDER BY Time ASC";

                        var maxTrackingInformation = (_db.Database.SqlQuery <TrackerInfo>(strMaxSQL, maxSqlParameters)).OrderBy(t => t.Time).ToList();

                        foreach (var item in maxTrackingInformation)
                        {
                            if (GetDistanceTo(Convert.ToDouble(latitude), Convert.ToDouble(longitude), Convert.ToDouble(item.Latitude), Convert.ToDouble(item.Longitude)) <= Convert.ToDouble(distance))
                            {
                                max = item;
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    if (min != null && !min.Time.ToString().Contains("0001"))
                    {
                        responseData.Add(new ResponseData()
                        {
                            Time        = min.Time.ToString(),
                            Longitude   = min.Longitude,
                            Latitude    = min.Latitude,
                            Velocity    = min.Velocity,
                            Description = "Min"
                        });
                    }

                    if (minDriveOut != null && !minDriveOut.Time.ToString().Contains("0001"))
                    {
                        responseData.Add(new ResponseData()
                        {
                            Time        = minDriveOut.Time.ToString(),
                            Longitude   = minDriveOut.Longitude,
                            Latitude    = minDriveOut.Latitude,
                            Velocity    = minDriveOut.Velocity,
                            Description = "MinDriveOut"
                        });
                    }

                    if (max != null && !max.Time.ToString().Contains("0001"))
                    {
                        responseData.Add(new ResponseData()
                        {
                            Time        = max.Time.ToString(),
                            Longitude   = max.Longitude,
                            Latitude    = max.Latitude,
                            Velocity    = max.Velocity,
                            Description = "Max"
                        });
                    }
                }

                return(Json(responseData, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                ErrorLog.LogException(ex);
                TrackerInfo trackerDetail = new TrackerInfo();
                return(Json(trackerDetail, JsonRequestBehavior.AllowGet));
            }
        }
Example #16
0
        static void Main(string[] args)
        {
            int gpus = SySal.GPU.Utilities.GetAvailableGPUs();

            if (C.MaxGPUs >= 0 && gpus > C.MaxGPUs)
            {
                gpus = C.MaxGPUs;
            }
            Trackers = new TrackerInfo[gpus];
            Out.WriteLine("GPUs found: " + gpus);
            int g;

            for (g = 0; g < gpus; g++)
            {
                Trackers[g]         = new TrackerInfo();
                Trackers[g].Tracker = new GPU.MapTracker();
                Trackers[g].Tracker.SetGPU(g);
                Trackers[g].ExecThread = new System.Threading.Thread(new System.Threading.ThreadStart(Trackers[g].Process));
                Trackers[g].ExecThread.Start();
            }
            Out.WriteLine("Initialization done, starting HTTP server");
            SySal.Web.WebServer ws = new Web.WebServer(1783, new Program());
            Out.WriteLine("Notifying startup.");
            SendAliveNotification(true);
            Out.WriteLine("Starting \"alive\" notifier.");
            System.Timers.Timer alivetimer = new System.Timers.Timer(60000);
            alivetimer.Elapsed += new System.Timers.ElapsedEventHandler(alivetimer_Elapsed);
            alivetimer.Start();
            Out.WriteLine("Starting profiler.");
            System.Timers.Timer profiletimer = new System.Timers.Timer(100);
            profiletimer.Elapsed += new System.Timers.ElapsedEventHandler(profiletimer_Elapsed);
            profiletimer.Start();
            Out.WriteLine("Service started, type exit to terminate or help to get the list of commands.");
            string line;

            while ((line = Console.ReadLine()) != null)
            {
                System.Text.RegularExpressions.Match m;
                if ((m = rx_Exit.Match(line)).Success)
                {
                    break;
                }
                else if ((m = rx_AliveAddress.Match(line)).Success)
                {
                    C.NotifyAliveAddress = m.Groups[1].Value;
                    C.Save();
                }
                else if ((m = rx_Help.Match(line)).Success)
                {
                    Out.WriteLine();
                    Out.WriteLine("exit -> Stop service.");
                    Out.WriteLine("alive <addr> -> Set <addr> as the address of the computer to notify that this server is working.");
                    Out.WriteLine("debdumpdir <directory> -> Set <directory> as location for debug dump files.");
                    Out.WriteLine("nodebdump -> Disable debug dump.");
                    Out.WriteLine("log <0|1|2|3|on|off> -> Enable|disable logging (on|off) or set verbosity level (0=off;1=on;2,3 for debugging).");
                    Out.WriteLine("help -> Show this help.");
                    Out.WriteLine();
                }
                else if ((m = rx_Log.Match(line)).Success)
                {
                    switch (m.Groups[1].Value)
                    {
                    case "0": C.LogLevel = 0; break;

                    case "1": C.LogLevel = 1; break;

                    case "2": C.LogLevel = 2; break;

                    case "3": C.LogLevel = 3; break;

                    case "off": C.LogLevel = 0; break;

                    case "on": C.LogLevel = 1; break;
                    }
                    C.Save();
                }
                else if ((m = rx_DebugDumpDir.Match(line)).Success)
                {
                    C.DebugDumpDir = m.Groups[1].Value;
                    if (C.DebugDumpDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
                    {
                        C.DebugDumpDir = C.DebugDumpDir.Substring(0, C.DebugDumpDir.Length - 1);
                    }
                    C.Save();
                }
                else if ((m = rx_NoDebugDump.Match(line)).Success)
                {
                    C.DebugDumpDir = "";
                    C.Save();
                }
            }
            Out.WriteLine("Sending stop signal to trackers.");
            foreach (TrackerInfo t in Trackers)
            {
                t.Terminate = true;
            }
            Out.WriteLine("Stopping profiler.");
            profiletimer.Stop();
            Out.WriteLine("Stopping \"alive\" notifier.");
            alivetimer.Stop();
            Out.WriteLine("Notifying shutdown.");
            SendAliveNotification(false);
            Out.WriteLine("Waiting for trackers to stop - it may take long if they are working.");
            foreach (TrackerInfo t in Trackers)
            {
                t.ExecThread.Join();
            }
            Out.WriteLine("Terminated.");
        }
        public JsonResult GetMinMaxReverse(string systemNumber, decimal longitude, decimal latitude, DateTime startDate, DateTime endDate)
        {
            try
            {
                SqlParameter[] sqlParameters =
                {
                    new SqlParameter("@systemNumber", SqlDbType.NVarChar)
                    {
                        Value = systemNumber
                    },
                    new SqlParameter("@longitude", SqlDbType.Decimal)
                    {
                        Value = longitude
                    },
                    new SqlParameter("@latitude", SqlDbType.Decimal)
                    {
                        Value = latitude
                    },
                    new SqlParameter("@startDate", SqlDbType.DateTime)
                    {
                        Value = startDate
                    },
                    new SqlParameter("@endDate", SqlDbType.DateTime)
                    {
                        Value = endDate
                    }
                };

                string strSQL = "IF EXISTS (SELECT name FROM sysobjects WHERE type='U' AND name='" + systemNumber + "') " +
                                "SELECT Time, Longitude, Latitude, Velocity FROM " + systemNumber + " " +
                                "WHERE Time BETWEEN @startDate AND @endDate AND Locate=1 ORDER BY Time ASC";

                var trackingInformation = (db.Database.SqlQuery <TrackerInfo>(strSQL, sqlParameters)).OrderByDescending(t => t.Time).ToList();
                var trackingInfo        = new List <TrackerInfo>();

                if (trackingInformation.Count > 0)
                {
                    TrackerInfo min = new TrackerInfo();
                    TrackerInfo max = trackingInformation.First();

                    foreach (var info in trackingInformation)
                    {
                        if (GetDistanceTo(Convert.ToDouble(latitude), Convert.ToDouble(longitude), Convert.ToDouble(info.Latitude), Convert.ToDouble(info.Longitude)) <= 500)
                        {
                            min = info;
                        }
                        else
                        {
                            break;
                        }
                    }
                    trackingInfo.Add(min);
                    trackingInfo.Add(max);
                }

                return(Json(trackingInfo, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                ErrorLog.LogException(ex);
                TrackerInfo trackerDetail = new TrackerInfo();
                return(Json(trackerDetail, JsonRequestBehavior.AllowGet));
            }
        }
        public JsonResult GetMinMaxOld(string systemNumber, decimal longitude, decimal latitude, DateTime startDate, DateTime endDate)
        {
            try
            {
                SqlParameter[] sqlParameters =
                {
                    new SqlParameter("@systemNumber", SqlDbType.NVarChar)
                    {
                        Value = systemNumber
                    },
                    new SqlParameter("@longitude", SqlDbType.Decimal)
                    {
                        Value = longitude
                    },
                    new SqlParameter("@latitude", SqlDbType.Decimal)
                    {
                        Value = latitude
                    },
                    new SqlParameter("@startDate", SqlDbType.DateTime)
                    {
                        Value = startDate
                    },
                    new SqlParameter("@endDate", SqlDbType.DateTime)
                    {
                        Value = endDate
                    }
                };

                string strSQL = "SELECT Time, Longitude, Latitude, Velocity, Distance From " +
                                "(SELECT Time, Longitude, Latitude, Velocity, " +
                                "(6371.393 * acos (cos ( radians(" + latitude + ") ) * " +
                                "cos( radians( Latitude ) ) * cos( radians( Longitude ) - " +
                                "radians(" + longitude + ") ) + sin ( radians(" + latitude + ") ) * " +
                                "sin( radians( Latitude ) ) ) ) AS distance FROM " + systemNumber + ") X " +
                                "Where Distance <= 0.5 And Time Between @startDate And @endDate";

                var trackingInformation = (db.Database.SqlQuery <TrackerInfo>(strSQL, sqlParameters)).ToList();

                var minMax = new List <MinMax>();

                if (trackingInformation.Count > 0)
                {
                    var arrivalTime   = trackingInformation.Min(i => i.Time);
                    var departureTime = trackingInformation.Max(i => i.Time);

                    TrackerInfo arrival   = trackingInformation.FirstOrDefault(i => i.Time == arrivalTime);
                    TrackerInfo departure = trackingInformation.FirstOrDefault(i => i.Time == departureTime);

                    if (arrival != null)
                    {
                        minMax.Add(
                            new MinMax()
                        {
                            Time      = arrival.Time,
                            Longitude = arrival.Longitude,
                            Latitude  = arrival.Latitude,
                            Velocity  = arrival.Velocity,
                            Address   = ""
                        });
                    }

                    if (departure != null)
                    {
                        minMax.Add(
                            new MinMax()
                        {
                            Time      = departure.Time,
                            Longitude = departure.Longitude,
                            Latitude  = departure.Latitude,
                            Velocity  = departure.Velocity,
                            Address   = String.Empty
                        });
                    }
                }

                return(Json(minMax, JsonRequestBehavior.AllowGet));
            }
            catch (Exception ex)
            {
                ErrorLog.LogException(ex);
                TrackerInfo trackerDetail = new TrackerInfo();

                return(Json(trackerDetail, JsonRequestBehavior.AllowGet));
            }
        }
        public void Load()
        {
            trackers.Clear();

            foreach (var path in Directory.GetFiles(configSerivce.GetAutoDLFolder(), "*.tracker"))
            {
                var xml  = XDocument.Load(path);
                var info = new TrackerInfo()
                {
                    FileName  = Path.GetFileName(path),
                    LongName  = xml.Root.AttributeString("longName"),
                    ShortName = xml.Root.AttributeString("shortName"),
                    SiteName  = xml.Root.AttributeString("siteName"),
                    Type      = xml.Root.AttributeString("type")
                };

                Condition.Requires <string>(info.FileName, "FileName").IsNotNullOrWhiteSpace();
                Condition.Requires <string>(info.LongName, "LongName").IsNotNullOrWhiteSpace();
                Condition.Requires <string>(info.ShortName, "ShortName").IsNotNullOrWhiteSpace();
                // Condition.Requires<string>(info.SiteName, "SiteName").IsNotNullOrWhiteSpace();
                Condition.Requires <string>(info.Type, "Type").IsNotNullOrWhiteSpace();

                info.Options.Add(new ConfigOption()
                {
                    Name         = "enabled",
                    Label        = "Enabled",
                    DefaultValue = "true",
                    Type         = ConfigOptionType.Bool
                });

                info.Options.Add(new ConfigOption()
                {
                    Name         = "upload-delay-secs",
                    Label        = "Delay",
                    Tooltip      = "Wait this many seconds before uploading/saving the torrent. Default is 0.",
                    DefaultValue = "0",
                    Type         = ConfigOptionType.Integer
                });

                info.Options.Add(new ConfigOption()
                {
                    Name         = "force-ssl",
                    Label        = "Force HTTPS (SSL) downloads",
                    Tooltip      = "If checked, all torrent file downloads from this tracker will be forced to use the HTTPS protocol. Not all trackers support this.",
                    DefaultValue = "false",
                    Type         = ConfigOptionType.Bool
                });

                foreach (var setting in xml.Root.Element("settings").Elements())
                {
                    var tag    = setting.Name;
                    var option = new ConfigOption()
                    {
                        Name          = setting.AttributeString("name"),
                        DefaultValue  = setting.AttributeString("defaultValue") ?? string.Empty,
                        Label         = setting.AttributeString("text"),
                        EmptyText     = setting.AttributeString("emptytext"),
                        Tooltip       = setting.AttributeString("tooltiptext"),
                        PasteGroup    = setting.AttributeString("pasteGroup"),
                        PasteRegex    = setting.AttributeString("pasteRegex"),
                        MinValue      = setting.AttributeString("minValue"),
                        MaxValue      = setting.AttributeString("maxValue"),
                        IsDownloadVar = setting.AttributeString("name") == "true"
                    };

                    if (!string.IsNullOrEmpty(setting.AttributeString("type")))
                    {
                        option.Type = (ConfigOptionType)Enum.Parse(typeof(ConfigOptionType), setting.AttributeString("type"), true);
                    }

                    if (tag == "gazelle_description" || tag == "description" || tag == "cookie_description")
                    {
                        option.Type  = ConfigOptionType.Description;
                        option.Label = "Paste (Ctrl+V) any torrent download link into any one of the two text boxes below to automatically extract authkey and torrent_pass.";
                    }
                    else if (tag == "gazelle_authkey" || tag == "authkey")
                    {
                        option.Type       = ConfigOptionType.TextBox;
                        option.Name       = "authkey";
                        option.Label      = "authkey";
                        option.Tooltip    = "The authkey in any torrent download link.";
                        option.PasteGroup = "authkey,torrent_pass";
                        option.PasteRegex = "[\\?&]authkey=([\\da-zA-Z]{32})";
                    }
                    else if (tag == "gazelle_torrent_pass")
                    {
                        option.Type       = ConfigOptionType.TextBox;
                        option.Name       = "torrent_pass";
                        option.Label      = "torrent_pass";
                        option.Tooltip    = "The torrent_pass in any torrent download link.";
                        option.PasteGroup = "authkey,torrent_pass";
                        option.PasteRegex = "[\\?&]torrent_pass=([\\da-zA-Z]{32})";
                    }
                    else if (tag == "description")
                    {
                        option.Type = ConfigOptionType.Description;
                    }
                    else if (tag == "authkey")
                    {
                        option.Type       = ConfigOptionType.TextBox;
                        option.Name       = "authkey";
                        option.Label      = "authkey";
                        option.Tooltip    = "The authkey in any torrent download link.";
                        option.PasteGroup = "authkey";
                        option.PasteRegex = "[\\?&]authkey=([\\da-fA-F]{32})";
                    }
                    else if (tag == "passkey")
                    {
                        option.Type       = ConfigOptionType.TextBox;
                        option.Name       = "passkey";
                        option.Label      = "passkey";
                        option.Tooltip    = "The passkey in any torrent download link.";
                        option.PasteGroup = "passkey";
                        option.PasteRegex = "[\\?&]passkey=([\\da-fA-F]{32})";
                    }
                    else if (tag == "cookie")
                    {
                        option.Type    = ConfigOptionType.TextBox;
                        option.Name    = "cookie";
                        option.Label   = "Log in to your tracker's home page with your browser.<br><br><strong>Chrome:</strong> Options Menu -&gt; Privacy -&gt; Content Settings -&gt; All cookies and site data<br><strong>Firefox:</strong> Firefox Menu -&gt; Options -&gt; Privacy -&gt; Show cookies<br><strong>Safari:</strong> Action Menu -&gt; Preferences -&gt; Privacy -&gt; Details<br><br>Find your tracker site in the cookie or file list.The values needed may vary between trackers. Often these are _uid_ and _pass_.<br />Set the cookie like <strong>uid=XXX; pass=YYY</strong>, separating each key=value pair with a semicolon.";
                        option.Tooltip = "The cookie.";
                    }
                    else if (tag == "integer")
                    {
                        option.Type     = ConfigOptionType.Integer;
                        option.MinValue = "-999999999";
                    }
                    else if (tag == "delta")
                    {
                        option.Type     = ConfigOptionType.Integer;
                        option.Name     = "delta";
                        option.Label    = "Torrent ID delta";
                        option.MinValue = "-999999999";
                    }
                    else if (tag == "textbox")
                    {
                        option.Type    = ConfigOptionType.TextBox;
                        option.Tooltip = $"{info.LongName} {setting.Name}";
                    }

                    if (string.IsNullOrWhiteSpace(option.Label))
                    {
                        option.Label = option.Name;
                    }
                    if (!option.Type.HasValue)
                    {
                        throw new Exception($"No option type specified for setting {tag} on tracker {info.LongName}");
                    }

                    info.Options.Add(option);
                }

                foreach (var server in xml.Root.Element("servers").Elements())
                {
                    var serverInfo = new ServerInfo()
                    {
                        Announcers = server.AttributeStringList("announcerNames"),
                        Channels   = server.AttributeStringList("channelNames"),
                        Network    = server.AttributeString("network"),
                        Servers    = server.AttributeStringList("serverNames"),
                    };

                    info.Servers.Add(serverInfo);
                }

                foreach (var node in xml.Root.Element("parseinfo").Elements())
                {
                    switch (node.Name.ToString())
                    {
                    case "multilinepatterns":
                        // todo
                        break;

                    case "linepatterns":
                        info.Parser.SingleLineMatches.Add(new LinePatterns()
                        {
                            Children = ParseCommands(node)
                        });
                        break;

                    case "linematched":
                        info.Parser.MatchParsers.Add(new LineMatched()
                        {
                            Children = ParseCommands(node)
                        });
                        break;

                    case "ignore":
                        info.Parser.IgnoreMatches.Add(new Ignore(logFactory.CreateLogger <Ignore>())
                        {
                            Children = ParseCommands(node)
                        });
                        break;
                    }
                }

                logger.LogDebug($"Loaded {info.FileName}");
                trackers.Add(info);
            }

            logger.LogInformation($"Loaded {trackers.Count} irc profiles.");

            var savedConfig = configSerivce.GetConfig <SavedAutoDLConfigurations>();

            if (savedConfig != null)
            {
                foreach (var config in savedConfig.Configurations)
                {
                    var tracker = trackers.Where(t => t.Type == config.Type).FirstOrDefault();
                    if (tracker != null)
                    {
                        tracker.IsConfigured = true;
                        foreach (var savedOption in config.Options)
                        {
                            var trackerOption = tracker.Options.Where(o => o.Name == savedOption.Key).FirstOrDefault();
                            if (trackerOption != null)
                            {
                                trackerOption.Value = savedOption.Value;
                            }
                        }
                    }
                }
            }
        }