/// <summary>
        /// Get all subscription matches for all active subscriptions where applicable
        /// </summary>
        /// <returns></returns>
        public async Task <List <SubscriptionMatchGroup> > GetAllSubscriptionMatches(bool excludeRecentlyNotified = true)
        {
            List <SubscriptionMatchGroup> allMatches = new List <SubscriptionMatchGroup>();

            //TODO: performance/optimisation (use cache for POI queries is done)
            //for each subscription, check if any changes match the criteria

            var refData = new ReferenceDataManager().GetCoreReferenceData();

            var dataModel = new OCM.Core.Data.OCMEntities();
            //var cacheManager = new OCM.Core.Data.CacheProviderMongoDB();
            var poiManager  = new POIManager();
            var currentTime = DateTime.UtcNow;

            int minHoursBetweenNotifications = 3;
            var minDateSinceNotification     = currentTime.AddHours(-minHoursBetweenNotifications);
            var allsubscriptions             = dataModel.UserSubscriptions.Where(s => s.IsEnabled == true && s.User.EmailAddress != null && (s.DateLastNotified == null || s.DateLastNotified < minDateSinceNotification));

            foreach (var subscription in allsubscriptions)
            {
                if (!excludeRecentlyNotified || (subscription.DateLastNotified == null || subscription.DateLastNotified.Value < currentTime.AddMinutes(-subscription.NotificationFrequencyMins)))
                {
                    var subscriptionMatchGroup = await GetSubscriptionMatches(dataModel, poiManager, subscription, refData);

                    if (subscriptionMatchGroup.SubscriptionMatches.Any())
                    {
                        subscriptionMatchGroup.Subscription = OCM.API.Common.Model.Extensions.UserSubscription.FromDataModel(subscription, true);
                        allMatches.Add(subscriptionMatchGroup);
                    }
                }
            }
            return(allMatches);
        }
예제 #2
0
        public void PromoteUserToCountryEditor(int authorizingUserId, int userId, List <int> CountryIDs, bool autoCreateSubscriptions, bool removePermission)
        {
            var authorisingUser = GetUser(authorizingUserId);
            var user            = GetUser(userId);

            foreach (var countryId in CountryIDs)
            {
                //grant country editor permissions for each country
                GrantPermission(user, StandardPermissionAttributes.CountryLevel_Editor, countryId.ToString(), removePermission, authorisingUser);
            }

            if (!removePermission && autoCreateSubscriptions)
            {
                var subscriptionManager = new UserSubscriptionManager();
                var refDataManager      = new ReferenceDataManager();
                var allSubscriptions    = subscriptionManager.GetUserSubscriptions(userId);

                foreach (var countryId in CountryIDs)
                {
                    //if no subscription exists for this country for this user, create one
                    if (!allSubscriptions.Any(s => s.CountryID == countryId))
                    {
                        var country = refDataManager.GetCountry(countryId);
                        subscriptionManager.UpdateUserSubscription(new UserSubscription {
                            Title = "All Updates For " + country.Title, IsEnabled = true, DateCreated = DateTime.UtcNow, CountryID = countryId, NotificationFrequencyMins = 720, NotifyComments = true, NotifyMedia = true, NotifyPOIAdditions = true, NotifyPOIEdits = true, NotifyPOIUpdates = true, UserID = userId
                        });
                    }
                }
            }
        }
예제 #3
0
        /// <summary>
        /// Returns new or cached location guess based on client IP address
        /// </summary>
        /// <returns></returns>
        public LocationLookupResult PerformLocationGuess(bool includeCountryID)
        {
            LocationLookupResult locationGuess = null;

            if (Session["locationGuess"] != null)
            {
                locationGuess = (LocationLookupResult)Session["locationGuess"];
            }

            if (locationGuess == null || (locationGuess != null && (locationGuess.Country_Code == null || includeCountryID && locationGuess.CountryID == 0)))
            {
                var clientIP = Request.ServerVariables["REMOTE_ADDR"];

                locationGuess = GeocodingHelper.GetLocationFromIP_FreegeoIP(clientIP);

                if (includeCountryID)
                {
                    var country = new ReferenceDataManager().GetCountryByISO(locationGuess.Country_Code);
                    if (country != null)
                    {
                        locationGuess.CountryID = country.ID;
                    }
                }

                Session["locationGuess"] = locationGuess;
            }

            return locationGuess;
        }
예제 #4
0
 public POIBrowseModel()
 {
     using (var refDataManager = new OCM.API.Common.ReferenceDataManager())
     {
         this.ReferenceData = refDataManager.GetCoreReferenceData();
         this.AllowOptionalCountrySelection = true;
         //this.CountryIDs = new int[] { 1 }; //default to uk
     }
 }
        public SubmissionManager()
        {
            AllowUpdates = false;

            using (var refDataManager = new ReferenceDataManager())
            {
                refData = refDataManager.GetCoreReferenceData();
            }
        }
예제 #6
0
 public ActionResult Networks(string countryname)
 {
     var country = new ReferenceDataManager().GetCountryByName(countryname);
     if (country != null)
     {
         //int[] genericOperatorIds = { 1, 44, 45 };
         var operators = new ReferenceDataManager().GetOperators(country.ID).Where(o=>o.ID!=1 && o.ID!=44 && o.ID!=45).ToList();
         ViewBag.Country = country;
         return View(operators);
     }
     return View();
 }
예제 #7
0
        private async Task <CoreReferenceData> GetCoreReferenceDataAsync()
        {
            if (_cache.TryGetValue("_coreRefData", out var refData))
            {
                return(refData as CoreReferenceData);
            }
            else
            {
                using (var refDataManager = new OCM.API.Common.ReferenceDataManager())
                {
                    var result = await refDataManager.GetCoreReferenceDataAsync();

                    _cache.Set("_coreRefData", result);
                    return(result);
                }
            }
        }
        public async Task <SubscriptionMatchGroup> GetSubscriptionMatches(int subscriptionId, int userId, DateTime?dateFrom)
        {
            var refData    = new ReferenceDataManager().GetCoreReferenceData();
            var dataModel  = new OCM.Core.Data.OCMEntities();
            var poiManager = new POIManager();

            var subscription = dataModel.UserSubscriptions.FirstOrDefault(s => s.Id == subscriptionId && s.UserId == userId);

            if (subscription != null)
            {
                return(await GetSubscriptionMatches(dataModel, poiManager, subscription, refData, dateFrom));
            }
            else
            {
                return(null);
            }
        }
예제 #9
0
        //[AuthSignedInOnly]
        public ActionResult Add()
        {
            var refData = new POIBrowseModel();
            refData.AllowOptionalCountrySelection = false;

            ViewBag.ReferenceData = refData;
            ViewBag.ConnectionIndex = 0; //connection counter shared by equipment detais
            ViewBag.EnableEditView = false;

            //get a default new POI using std core reference data
            var coreReferenceData = new ReferenceDataManager().GetCoreReferenceData();
            coreReferenceData.ChargePoint.OperatorInfo.ID = 1;// Unknown Operator
            coreReferenceData.ChargePoint.StatusType.ID = 50; //Operational
            coreReferenceData.ChargePoint.UsageType.ID = 6; //private for staff and visitors
            coreReferenceData.ChargePoint.SubmissionStatus = null; //let system decide on submit
            coreReferenceData.ChargePoint.SubmissionStatusTypeID = null;
            return View("Edit", coreReferenceData.ChargePoint);
        }
예제 #10
0
        public ActionResult Index(string countryname)
        {
            if (!String.IsNullOrEmpty(countryname))
            {

                var country = new ReferenceDataManager().GetCountryByName(countryname);
                return this.Summary(countryname);
            }

            //list of all countries
            var allCountries = new ReferenceDataManager().GetCountries(false);
            var countryStats = new DataSummaryManager().GetAllCountryStats();

            var continents = new Dictionary<string, string>();
            continents.Add("AS", "Asia");
            continents.Add("EU", "Europe");
            continents.Add("NA", "North America");
            continents.Add("OC", "Oceania");
            continents.Add("SA", "South America");

            ViewBag.Continents = continents;
            ViewBag.CountryStats = countryStats;
            return View(allCountries);
        }
예제 #11
0
        public void PromoteUserToCountryEditor(int authorizingUserId, int userId, List<int> CountryIDs, bool autoCreateSubscriptions, bool removePermission)
        {
            var authorisingUser = GetUser(authorizingUserId);
            var user = GetUser(userId);

            foreach (var countryId in CountryIDs)
            {
                //grant country editor permissions for each country
                GrantPermission(user, StandardPermissionAttributes.CountryLevel_Editor, countryId.ToString(), removePermission, authorisingUser);
            }

            if (!removePermission && autoCreateSubscriptions)
            {
                var subscriptionManager = new UserSubscriptionManager();
                var refDataManager = new ReferenceDataManager();
                var allSubscriptions = subscriptionManager.GetUserSubscriptions(userId);

                foreach (var countryId in CountryIDs)
                {
                    //if no subscription exists for this country for this user, create one
                    if (!allSubscriptions.Any(s => s.CountryID == countryId))
                    {
                        var country = refDataManager.GetCountry(countryId);
                        subscriptionManager.UpdateUserSubscription(new UserSubscription { Title = "All Updates For " + country.Title, IsEnabled = true, DateCreated = DateTime.UtcNow, CountryID = countryId, NotificationFrequencyMins = 720, NotifyComments = true, NotifyMedia = true, NotifyPOIAdditions = true, NotifyPOIEdits = true, NotifyPOIUpdates = true, UserID = userId });
                    }
                }
            }
        }
예제 #12
0
        public async Task<ActionResult> Import(string providerName, bool fetchLiveData, bool performImport = false)
        {
            var stopwatch = new Stopwatch();
            stopwatch.Start();

            var importManager = new Import.ImportManager(Server.MapPath("~/Temp"));

            var providers = importManager.GetImportProviders(new ReferenceDataManager().GetDataProviders());
            var provider = providers.FirstOrDefault(p => p.GetProviderName() == providerName);
            var coreReferenceData = new ReferenceDataManager().GetCoreReferenceData();
            ((BaseImportProvider)provider).InputPath = importManager.TempFolder + "//cache_" + provider.GetProviderName() + ".dat";
            var result = await importManager.PerformImport(OCM.Import.Providers.ExportType.POIModelList, fetchLiveData, new OCM.API.Client.APICredentials(), coreReferenceData, "", provider, true);

            var systemUser = new UserManager().GetUser((int)StandardUsers.System);
            if (performImport)
            {
                //add/update/delist POIs
                await Task.Run(() =>
                {
                    importManager.UpdateImportedPOIList(result, systemUser);
                });
            }

            stopwatch.Stop();
            result.Log += "\r\nImport processing time (seconds): " + stopwatch.Elapsed.TotalSeconds;

            return View(result);
        }
예제 #13
0
        public GeocodingResult ReverseGecode_MapquestOSM(double latitude, double longitude, ReferenceDataManager refDataManager)
        {
            GeocodingResult result = new GeocodingResult();

            result.Service = "MapQuest Open";

            string url = "http://open.mapquestapi.com/geocoding/v1/reverse?location=" + latitude + "," + longitude + "&key=" + _settings.ApiKeys.MapQuestOpenAPIKey;

            if (IncludeQueryURL)
            {
                result.QueryURL = url;
            }

            string data = "";

            try
            {
                WebClient client = new WebClient();
                client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
                client.Encoding = Encoding.GetEncoding("UTF-8");
                data            = client.DownloadString(url);

                if (IncludeExtendedData)
                {
                    result.ExtendedData = data;
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine(data);
                }

                if (data == "[]")
                {
                    System.Diagnostics.Debug.WriteLine("No geocoding results:" + url);
                    result.ResultsAvailable = false;
                }
                else
                {
                    JObject o         = JObject.Parse(data);
                    var     locations = o["results"][0]["locations"];
                    if (locations.Any())
                    {
                        var item = o["results"][0]["locations"][0];


                        result.AddressInfo              = new AddressInfo();
                        result.AddressInfo.Title        = item["street"]?.ToString();
                        result.AddressInfo.Postcode     = item["postalCode"]?.ToString();
                        result.AddressInfo.AddressLine1 = item["street"]?.ToString();

                        if (item["adminArea5Type"]?.ToString() == "City")
                        {
                            result.AddressInfo.Town = item["adminArea5"]?.ToString();
                        }

                        if (item["adminArea3Type"]?.ToString() == "State")
                        {
                            result.AddressInfo.StateOrProvince = item["adminArea3"]?.ToString();
                        }

                        if (item["adminArea3Type"]?.ToString() == "State")
                        {
                            result.AddressInfo.StateOrProvince = item["adminArea3"]?.ToString();
                        }
                        if (item["adminArea1Type"]?.ToString() == "Country")
                        {
                            var countryCode = item["adminArea1"]?.ToString();
                            var country     = refDataManager.GetCountryByISO(countryCode);
                            if (country != null)
                            {
                                result.AddressInfo.CountryID = country.ID;
                            }
                        }

                        result.Latitude              = latitude;
                        result.Longitude             = longitude;
                        result.Attribution           = "Portions © OpenStreetMap contributors"; // using mapquest open so results are from OSM
                        result.AddressInfo.Latitude  = latitude;
                        result.AddressInfo.Longitude = longitude;

                        result.ResultsAvailable = true;
                    }
                    else
                    {
                        result.ResultsAvailable = false;
                    }
                }
            }
            catch (Exception)
            {
                //
            }
            return(result);
        }
예제 #14
0
        public GeocodingResult ReverseGecode_OSM(double latitude, double longitude, ReferenceDataManager refDataManager)
        {
            GeocodingResult result = new GeocodingResult();

            result.Service = "Nominatim OSM";


            string url = $"https://nominatim.openstreetmap.org/reverse?format=json&lat={latitude}&lon={longitude}&zoom=18&addressdetails=1";

            if (IncludeQueryURL)
            {
                result.QueryURL = url;
            }

            string data = "";

            try
            {
                WebClient client = new WebClient();
                client.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1");
                client.Encoding = Encoding.GetEncoding("UTF-8");
                data            = client.DownloadString(url);


                /* e.g.:
                 * {
                 *  "place_id": 101131804,
                 *  "licence": "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright",
                 *  "osm_type": "way",
                 *  "osm_id": 61267076,
                 *  "lat": "-32.1685328505288",
                 *  "lon": "115.9882328723638",
                 *  "display_name": "Eleventh Road, Haynes, Armadale, Western Australia, 6112, Australia",
                 *  "address": {
                 *      "road": "Eleventh Road",
                 *      "suburb": "Haynes",
                 *      "town": "Armadale",
                 *      "state": "Western Australia",
                 *      "postcode": "6112",
                 *      "country": "Australia",
                 *      "country_code": "au"
                 *  },
                 *  "boundingbox": [
                 *      "-32.1689883",
                 *      "-32.1619497",
                 *      "115.9805577",
                 *      "115.9887699"
                 *  ]
                 * }
                 * */
                if (IncludeExtendedData)
                {
                    result.ExtendedData = data;
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine(data);
                }

                if (data == "{}")
                {
                    System.Diagnostics.Debug.WriteLine("No geocoding results:" + url);
                    result.ResultsAvailable = false;
                }
                else
                {
                    JObject o = JObject.Parse(data);

                    var item = o["address"];


                    result.AddressInfo                 = new AddressInfo();
                    result.AddressInfo.Title           = item["road"]?.ToString();
                    result.AddressInfo.Postcode        = item["postcode"]?.ToString();
                    result.AddressInfo.AddressLine1    = item["road"]?.ToString();
                    result.AddressInfo.AddressLine2    = item["suburb"]?.ToString();
                    result.AddressInfo.Town            = item["town"]?.ToString();
                    result.AddressInfo.StateOrProvince = item["state"]?.ToString();

                    var countryCode = item["country_code"]?.ToString();
                    var country     = refDataManager.GetCountryByISO(countryCode);
                    if (country != null)
                    {
                        result.AddressInfo.CountryID = country.ID;
                    }


                    result.Latitude              = latitude;
                    result.Longitude             = longitude;
                    result.Attribution           = "Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright";
                    result.AddressInfo.Latitude  = latitude;
                    result.AddressInfo.Longitude = longitude;

                    result.ResultsAvailable = true;
                }
            }
            catch (Exception)
            {
                //
            }
            return(result);
        }
예제 #15
0
        public ActionResult SubscriptionEdit(UserSubscription userSubscription)
        {
            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(Request["CountryCode"]))
                {
                    //TEMP fix country id passed as ISO
                    var country = new ReferenceDataManager().GetCountryByISO(Request["CountryCode"]);
                    userSubscription.CountryID = country.ID;
                }
                else
                {
                    userSubscription.Country = null;
                    userSubscription.CountryID = null;
                }
                userSubscription = new UserSubscriptionManager().UpdateUserSubscription(userSubscription);
                return RedirectToAction("Subscriptions", "Profile");
            }

            PopulateSubscriptionEditorViewBag(userSubscription);
            return View(userSubscription);
        }
예제 #16
0
        public async Task <ActionResult> Index(POIBrowseModel filter)
        {
            if (filter?.ReferenceData == null)
            {
                if (filter == null)
                {
                    filter = new POIBrowseModel();
                    filter.ShowAdvancedOptions = true;
                }
                filter.ReferenceData = await GetCoreReferenceDataAsync();
            }

            var cpManager = new API.Common.POIManager();

            //dropdown selections of -1 represent an intended null selection, fix this by nulling relevant items
            filter.CountryIDs        = this.ConvertNullableSelection(filter.CountryIDs);
            filter.LevelIDs          = this.ConvertNullableSelection(filter.LevelIDs);
            filter.ConnectionTypeIDs = this.ConvertNullableSelection(filter.ConnectionTypeIDs);
            filter.OperatorIDs       = this.ConvertNullableSelection(filter.OperatorIDs);
            filter.StatusTypeIDs     = this.ConvertNullableSelection(filter.StatusTypeIDs);
            filter.UsageTypeIDs      = this.ConvertNullableSelection(filter.UsageTypeIDs);
            filter.DataProviderIDs   = this.ConvertNullableSelection(filter.DataProviderIDs);
            filter.IncludeComments   = true;

            if (IsRequestByRobot)
            {
                //force mirror db when browser is a robot
                filter.AllowMirrorDB    = true;
                filter.AllowDataStoreDB = false;
            }

            if (!String.IsNullOrWhiteSpace(filter.Country))
            {
                //TODO: cache country id lookup
                using (var refData = new OCM.API.Common.ReferenceDataManager())
                {
                    var countrySelected = refData.GetCountryByName(filter.Country);
                    if (countrySelected != null)
                    {
                        filter.CountryIDs = new int[] { countrySelected.ID };
                    }
                }
            }
            else
            {
                //default to UK
                // if (filter.CountryIDs == null) filter.CountryIDs = new int[] { 1 };
            }

            filter.MaxResults = 100;

            if (!String.IsNullOrWhiteSpace(filter.SearchLocation))
            {
                if (filter.SearchLocation.ToUpper().StartsWith("OCM-"))
                {
                    filter.SearchLocation = filter.SearchLocation.Replace("OCM-", "");
                }
                if (filter.SearchLocation.ToUpper().StartsWith("OCM"))
                {
                    filter.SearchLocation = filter.SearchLocation.Replace("OCM", "");
                }

                if (IsNumeric(filter.SearchLocation.Trim()))
                {
                    int poiID = -1;
                    //treat numbers as OCM ref
                    if (int.TryParse(filter.SearchLocation.Trim(), out poiID))
                    {
                        filter.ChargePointIDs = new int[] { poiID };
                    }
                }
                else
                {
                    //attempt to geocode
                    var    geocode           = new GeocodingHelper(_settings);
                    string searchCountryName = null;
                    if (filter.CountryIDs != null && filter.CountryIDs.Count() > 0)
                    {
                        var searchCountry = filter.ReferenceData.Countries.FirstOrDefault(c => c.ID == filter.CountryIDs[0]);
                        searchCountryName = searchCountry.Title;
                    }

                    API.Common.Model.Extended.GeocodingResult position = null;

                    // FIXME: geocoding is disabled, find an laternative service to use
                    //geocode.GeolocateAddressInfo_Google(filter.SearchLocation.Trim() + (searchCountryName != null ? ", " + searchCountryName : ""));

                    if (filter.SearchLocation.Contains(","))
                    {
                        var vals = filter.SearchLocation.Split(',');
                        if (IsNumeric(vals[0]) && IsNumeric(vals[1]))
                        {
                            position = new API.Common.Model.Extended.GeocodingResult
                            {
                                Latitude  = double.Parse(vals[0]),
                                Longitude = double.Parse(vals[1])
                            };
                        }
                    }
                    if (position != null)
                    {
                        filter.Latitude  = position.Latitude;
                        filter.Longitude = position.Longitude;
                        if (filter.Distance == null)
                        {
                            filter.Distance = 50;
                        }
                        filter.DistanceUnit = API.Common.Model.DistanceUnit.Miles;
                        //TODO: distance unit KM
                        //if (distanceunit == "km") searchfilters.DistanceUnit = API.Common.Model.DistanceUnit.KM;

                        ViewBag.FormattedAddress = position.Address ?? "";
                    }
                }
            }

            filter.POIList = (await cpManager.GetPOIListAsync((OCM.API.Common.APIRequestParams)filter, filter.ReferenceData)).ToList();
            return(View(filter));
        }
예제 #17
0
        // GET: /POI/

        public ActionResult Index(POIBrowseModel filter)
        {
            if (filter == null)
            {
                filter = new POIBrowseModel();
                filter.ShowAdvancedOptions = true;
            }
            var cpManager = new API.Common.POIManager();

            //dropdown selections of -1 represent an intended null selection, fix this by nulling relevant items
            filter.CountryIDs        = this.ConvertNullableSelection(filter.CountryIDs);
            filter.LevelIDs          = this.ConvertNullableSelection(filter.LevelIDs);
            filter.ConnectionTypeIDs = this.ConvertNullableSelection(filter.ConnectionTypeIDs);
            filter.OperatorIDs       = this.ConvertNullableSelection(filter.OperatorIDs);
            filter.StatusTypeIDs     = this.ConvertNullableSelection(filter.StatusTypeIDs);
            filter.UsageTypeIDs      = this.ConvertNullableSelection(filter.UsageTypeIDs);
            filter.DataProviderIDs   = this.ConvertNullableSelection(filter.DataProviderIDs);
            filter.IncludeComments   = true;

            if (IsRequestByRobot)
            {
                //force mirror db when browser is a robot
                filter.AllowMirrorDB = true;
            }

            if (!String.IsNullOrWhiteSpace(filter.Country))
            {
                //TODO: cache country id lookup
                var countrySelected = new OCM.API.Common.ReferenceDataManager().GetCountryByName(filter.Country);
                if (countrySelected != null)
                {
                    filter.CountryIDs = new int[] { countrySelected.ID };
                }
            }
            else
            {
                //default to UK
                // if (filter.CountryIDs == null) filter.CountryIDs = new int[] { 1 };
            }

            filter.MaxResults = 100;

            if (!String.IsNullOrWhiteSpace(filter.SearchLocation))
            {
                if (filter.SearchLocation.ToUpper().StartsWith("OCM-"))
                {
                    filter.SearchLocation = filter.SearchLocation.Replace("OCM-", "");
                }
                if (filter.SearchLocation.ToUpper().StartsWith("OCM"))
                {
                    filter.SearchLocation = filter.SearchLocation.Replace("OCM", "");
                }

                if (IsNumeric(filter.SearchLocation.Trim()))
                {
                    int poiID = -1;
                    //treat numbers as OCM ref
                    if (int.TryParse(filter.SearchLocation.Trim(), out poiID))
                    {
                        filter.ChargePointIDs = new int[] { poiID };
                    }
                }
                else
                {
                    //attempt to geocode
                    var    geocode           = new GeocodingHelper();
                    string searchCountryName = null;
                    if (filter.CountryIDs != null && filter.CountryIDs.Count() > 0)
                    {
                        var searchCountry = filter.ReferenceData.Countries.FirstOrDefault(c => c.ID == filter.CountryIDs[0]);
                        searchCountryName = searchCountry.Title;
                    }

                    var position = geocode.GeolocateAddressInfo_Google(filter.SearchLocation.Trim() + (searchCountryName != null ? ", " + searchCountryName : ""));

                    if (position != null)
                    {
                        filter.Latitude  = position.Latitude;
                        filter.Longitude = position.Longitude;
                        if (filter.Distance == null)
                        {
                            filter.Distance = 50;
                        }
                        filter.DistanceUnit = API.Common.Model.DistanceUnit.Miles;
                        //TODO: distance unit KM
                        //if (distanceunit == "km") searchfilters.DistanceUnit = API.Common.Model.DistanceUnit.KM;

                        ViewBag.FormattedAddress = position.Address;
                    }
                }
            }

            filter.POIList = cpManager.GetChargePoints((OCM.API.Common.APIRequestParams)filter);
            return(View(filter));
        }
예제 #18
0
        //
        // GET: /POI/
        public ActionResult Index(POIBrowseModel filter)
        {
            if (filter == null)
            {
                filter = new POIBrowseModel();
                filter.ShowAdvancedOptions = true;
            }
            var cpManager = new API.Common.POIManager();

            //dropdown selections of -1 represent an intended null selection, fix this by nulling relevant items
            filter.CountryIDs = this.ConvertNullableSelection(filter.CountryIDs);
            filter.LevelIDs = this.ConvertNullableSelection(filter.LevelIDs);
            filter.ConnectionTypeIDs = this.ConvertNullableSelection(filter.ConnectionTypeIDs);
            filter.OperatorIDs = this.ConvertNullableSelection(filter.OperatorIDs);
            filter.StatusTypeIDs = this.ConvertNullableSelection(filter.StatusTypeIDs);
            filter.UsageTypeIDs = this.ConvertNullableSelection(filter.UsageTypeIDs);
            filter.DataProviderIDs = this.ConvertNullableSelection(filter.DataProviderIDs);
            filter.IncludeComments = true;

            if (IsRequestByRobot)
            {
                //force mirror db when browser is a robot
                filter.AllowMirrorDB = true;
            }

            if (!String.IsNullOrWhiteSpace(filter.Country))
            {
                //TODO: cache country id lookup
                var countrySelected = new OCM.API.Common.ReferenceDataManager().GetCountryByName(filter.Country);
                if (countrySelected != null)
                {
                    filter.CountryIDs = new int[] { countrySelected.ID };
                }
            }
            else
            {
                //default to UK
                // if (filter.CountryIDs == null) filter.CountryIDs = new int[] { 1 };
            }

            filter.MaxResults = 100;

            if (!String.IsNullOrWhiteSpace(filter.SearchLocation))
            {
                if (filter.SearchLocation.ToUpper().StartsWith("OCM-")) filter.SearchLocation = filter.SearchLocation.Replace("OCM-", "");
                if (filter.SearchLocation.ToUpper().StartsWith("OCM")) filter.SearchLocation = filter.SearchLocation.Replace("OCM", "");

                if (IsNumeric(filter.SearchLocation.Trim()))
                {
                    int poiID = -1;
                    //treat numbers as OCM ref
                    if (int.TryParse(filter.SearchLocation.Trim(), out poiID))
                    {
                        filter.ChargePointIDs = new int[] { poiID };
                    }
                }
                else
                {
                    //attempt to geocode
                    var geocode = new GeocodingHelper();
                    string searchCountryName = null;
                    if (filter.CountryIDs != null && filter.CountryIDs.Count() > 0)
                    {
                        var searchCountry = filter.ReferenceData.Countries.FirstOrDefault(c => c.ID == filter.CountryIDs[0]);
                        searchCountryName = searchCountry.Title;
                    }

                    var position = geocode.GeolocateAddressInfo_Google(filter.SearchLocation.Trim() + (searchCountryName != null ? ", " + searchCountryName : ""));

                    if (position != null)
                    {
                        filter.Latitude = position.Latitude;
                        filter.Longitude = position.Longitude;
                        if (filter.Distance == null) filter.Distance = 50;
                        filter.DistanceUnit = API.Common.Model.DistanceUnit.Miles;
                        //TODO: distance unit KM
                        //if (distanceunit == "km") searchfilters.DistanceUnit = API.Common.Model.DistanceUnit.KM;

                        ViewBag.FormattedAddress = position.Address;
                    }
                }
            }

            filter.POIList = cpManager.GetChargePoints((OCM.API.Common.APIRequestParams)filter);
            return View(filter);
        }
예제 #19
0
        private void PopulateSubscriptionEditorViewBag(UserSubscription subscription)
        {
            var refDataManager = new ReferenceDataManager();
            var coreRefData = refDataManager.GetCoreReferenceData();

            var allCountries = coreRefData.Countries;

            allCountries.Insert(0, new Country { ID = 0, ISOCode = "", Title = "(All Countries)" });

            ViewBag.CountryList = new SelectList(allCountries, "ISOCode", "Title", (subscription.Country != null ? subscription.Country.ISOCode : null));

            var NotificationFrequencyOptions = new[]{
                new { ID = 5, Title = "Every 5 Minutes"},
                new { ID = 30, Title = "Every 30 Minutes"},
                new { ID = 60, Title = "Every Hour"},
                new { ID = 60*12, Title = "Every 12 Hours"},
                new { ID = 60*24, Title = "Every Day"},
                new { ID = 60*24*7, Title = "Every Week"},
                new { ID = 60*24*7*31, Title = "Every Month"},
            };

            ViewBag.NotificationFrequencyOptions = new SelectList(NotificationFrequencyOptions, "ID", "Title", subscription.NotificationFrequencyMins);

            //var matchingItems = new UserSubscriptionManager().GetAllSubscriptionMatches();
            //ViewBag.MatchingItems = matchingItems;

            ViewBag.CountryExtendedInfo = JsonConvert.SerializeObject(OCM.Core.Data.CacheManager.GetExtendedCountryInfo());

            if (subscription.FilterSettings == null) subscription.FilterSettings = new UserSubscriptionFilter();
            ViewBag.OperatorList = new MultiSelectList(refDataManager.GetOperators(subscription.CountryID), "ID", "Title", subscription.FilterSettings.OperatorIDs);
            ViewBag.LevelList = new MultiSelectList(coreRefData.ChargerTypes, "ID", "Title", subscription.FilterSettings.LevelIDs);
            ViewBag.ConnectionTypeList = new MultiSelectList(coreRefData.ConnectionTypes, "ID", "Title", subscription.FilterSettings.ConnectionTypeIDs);
            ViewBag.StatusTypeList = new MultiSelectList(coreRefData.StatusTypes, "ID", "Title", subscription.FilterSettings.StatusTypeIDs);
            ViewBag.UsageTypeList = new MultiSelectList(coreRefData.UsageTypes, "ID", "Title", subscription.FilterSettings.UsageTypeIDs);
        }
예제 #20
0
        /// <summary>
        /// Consumers should prepare a new/updated ChargePoint with as much info populated as possible
        /// </summary>
        /// <param name="submission">ChargePoint info for submission, if ID and UUID set will be treated as an update</param>
        /// <returns>false on error or not enough data supplied</returns>
        public async Task <ValidationResult> PerformPOISubmission(Model.ChargePoint updatedPOI, Model.User user, bool performCacheRefresh = true, bool disablePOISuperseding = false)
        {
            try
            {
                var  poiManager             = new POIManager();
                bool enableEditQueueLogging = bool.Parse(ConfigurationManager.AppSettings["EnableEditQueue"]);
                bool isUpdate = false;
                bool userCanEditWithoutApproval = false;
                bool isSystemUser = false;
                int? supersedesID = null;//POI from another data provider which has been superseded by an edit

                //if user signed in, check if they have required permission to perform an edit/approve (if required)
                if (user != null)
                {
                    if (user.ID == (int)StandardUsers.System)
                    {
                        isSystemUser = true;
                    }

                    //if user is system user, edits/updates are not recorded in edit queue
                    if (isSystemUser)
                    {
                        enableEditQueueLogging = false;
                    }

                    userCanEditWithoutApproval = POIManager.CanUserEditPOI(updatedPOI, user);
                }

                var dataModel = new Core.Data.OCMEntities();

                //if poi is an update, validate if update can be performed
                if (updatedPOI.ID > 0 && !String.IsNullOrEmpty(updatedPOI.UUID))
                {
                    if (dataModel.ChargePoints.Any(c => c.Id == updatedPOI.ID && c.Uuid == updatedPOI.UUID))
                    {
                        //update is valid poi, check if user has permission to perform an update
                        isUpdate = true;
                        if (userCanEditWithoutApproval)
                        {
                            AllowUpdates = true;
                        }
                        if (!AllowUpdates && !enableEditQueueLogging)
                        {
                            //valid update requested but updates not allowed
                            return(new ValidationResult {
                                IsValid = false, Message = "Updates are disabled"
                            });
                        }
                    }
                    else
                    {
                        //update does not correctly identify an existing poi
                        return(new ValidationResult {
                            IsValid = false, Message = "Update does not correctly match an existing POI"
                        });
                    }
                }

                //validate if minimal required data is present
                if (updatedPOI.AddressInfo.Title == null || (updatedPOI.AddressInfo.Country == null && updatedPOI.AddressInfo.CountryID == null))
                {
                    return(new ValidationResult {
                        IsValid = false, Message = "Update failed basic validation"
                    });
                }

                //convert to DB version of POI and back so that properties are fully populated
                using (var refDataManager = new ReferenceDataManager())
                {
                    var refData = await refDataManager.GetCoreReferenceDataAsync();

                    updatedPOI = PopulateFullPOI(updatedPOI, refData);
                }

                Model.ChargePoint oldPOI = null;

                if (updatedPOI.ID > 0)
                {
                    //get json snapshot of current cp data to store as 'previous'
                    oldPOI = await poiManager.Get(updatedPOI.ID);
                }

                //if user cannot edit directly, add to edit queue for approval
                var editQueueItem = new Core.Data.EditQueueItem {
                    DateSubmitted = DateTime.UtcNow
                };
                if (enableEditQueueLogging)
                {
                    editQueueItem.EntityId   = updatedPOI.ID;
                    editQueueItem.EntityType = dataModel.EntityTypes.FirstOrDefault(t => t.Id == 1);
                    //charging point location entity type id

                    //serialize cp as json

                    //null extra data we don't want to serialize/compare
                    updatedPOI.UserComments = null;
                    updatedPOI.MediaItems   = null;

                    string editData = PerformSerialisationToString(updatedPOI, new JsonSerializerSettings {
                        NullValueHandling = NullValueHandling.Ignore
                    });

                    editQueueItem.EditData = editData;

                    if (updatedPOI.ID > 0)
                    {
                        //check if poi will change with this edit, if not we discard it completely
                        if (!poiManager.HasDifferences(oldPOI, updatedPOI))
                        {
                            System.Diagnostics.Debug.WriteLine("POI Update has no changes, discarding change.");
                            return(new ValidationResult {
                                IsValid = true, ItemId = updatedPOI.ID, Message = "No POI changes detected"
                            });
                        }
                        else
                        {
                            editQueueItem.PreviousData = PerformSerialisationToString(oldPOI, new JsonSerializerSettings {
                                NullValueHandling = NullValueHandling.Ignore
                            });
                        }
                    }

                    if (user != null)
                    {
                        editQueueItem.User = dataModel.Users.FirstOrDefault(u => u.Id == user.ID);
                    }
                    var processedByUser = editQueueItem.User ?? dataModel.Users.FirstOrDefault(u => u.Id == (int)StandardUsers.System);

                    editQueueItem.IsProcessed = false;
                    dataModel.EditQueueItems.Add(editQueueItem);
                    //TODO: send notification of new item for approval

                    //save edit queue item
                    dataModel.SaveChanges();

                    //if previous edit queue item exists by same user for same POI, mark as processed
                    var previousEdits = dataModel.EditQueueItems.Where(e => e.UserId == editQueueItem.UserId && e.EntityId == editQueueItem.EntityId && e.EntityTypeId == editQueueItem.EntityTypeId && e.Id != editQueueItem.Id && e.IsProcessed != true);
                    foreach (var previousEdit in previousEdits)
                    {
                        previousEdit.IsProcessed     = true;
                        previousEdit.ProcessedByUser = processedByUser;

                        previousEdit.DateProcessed = DateTime.UtcNow;
                    }
                    //save updated edit queue items
                    dataModel.SaveChanges();
                }

                //prepare and save changes POI changes/addition
                if (isUpdate && !AllowUpdates)
                {
                    //user has submitted an edit but is not an approved editor
                    //SendEditSubmissionNotification(updatedPOI, user);

                    //user is not an editor, item is now pending in edit queue for approval.
                    return(new ValidationResult {
                        IsValid = true, ItemId = updatedPOI.ID, Message = "Update submitted for review"
                    });
                }

                if (isUpdate && updatedPOI.SubmissionStatusTypeID >= 1000)
                {
                    //update is a delisting, skip superseding poi
                    System.Diagnostics.Debug.WriteLine("skipping superseding of imported POI due to delisting");
                }
                else
                {
                    //if poi being updated exists from an imported source we supersede the old POI with the new version, unless we're doing a fresh import from same data provider
                    if (!disablePOISuperseding)
                    {
                        //if update by non-system user will change an imported/externally provided data, supersede old POI with new one (retain ID against new POI)
                        if (isUpdate && !isSystemUser && oldPOI.DataProviderID != (int)StandardDataProviders.OpenChargeMapContrib)
                        {
                            //move old poi to new id, set status of new item to superseded
                            supersedesID = poiManager.SupersedePOI(dataModel, oldPOI, updatedPOI);
                        }
                    }
                }

                //user is an editor, go ahead and store the addition/update
                //set/update cp properties
                var cpData = poiManager.PopulateChargePoint_SimpleToData(updatedPOI, dataModel);

                //if item has no submission status and user permitted to edit, set to published
                if (userCanEditWithoutApproval && cpData.SubmissionStatusTypeId == null)
                {
                    cpData.SubmissionStatusTypeId = (int)StandardSubmissionStatusTypes.Submitted_Published; //hack due to conflicting state change for SubmissionStatusType
                }
                else
                {
                    //no submission status, set to 'under review'
                    if (cpData.SubmissionStatusTypeId == null)
                    {
                        cpData.SubmissionStatusTypeId = (int)StandardSubmissionStatusTypes.Submitted_UnderReview;
                    }
                }

                cpData.DateLastStatusUpdate = DateTime.UtcNow;

                if (!isUpdate)
                {
                    //new data objects need added to data model before save
                    if (cpData.AddressInfo != null)
                    {
                        dataModel.AddressInfos.Add(cpData.AddressInfo);
                    }

                    dataModel.ChargePoints.Add(cpData);
                }

                //finally - save poi update
                dataModel.SaveChanges();

                //get id of update/new poi
                int newPoiID = cpData.Id;

                //this is an authorised update, reflect change in edit queue item
                if (enableEditQueueLogging && user != null && user.ID > 0)
                {
                    var editUser = dataModel.Users.FirstOrDefault(u => u.Id == user.ID);
                    editQueueItem.User = editUser;

                    if (newPoiID > 0)
                    {
                        editQueueItem.EntityId = newPoiID;
                    }

                    //if user is authorised to edit, process item automatically without review
                    if (userCanEditWithoutApproval)
                    {
                        editQueueItem.ProcessedByUser = editUser;
                        editQueueItem.DateProcessed   = DateTime.UtcNow;
                        editQueueItem.IsProcessed     = true;
                    }

                    //save edit queue item changes
                    dataModel.SaveChanges();
                }
                else
                {
                    //anonymous submission, update edit queue item
                    if (enableEditQueueLogging && user == null)
                    {
                        if (newPoiID > 0)
                        {
                            editQueueItem.EntityId = newPoiID;
                        }
                        dataModel.SaveChanges();
                    }
                }

                System.Diagnostics.Debug.WriteLine("Added/Updated CP:" + cpData.Id);

                //if user is not anonymous, log their submission and update their reputation points
                if (user != null)
                {
                    AuditLogManager.Log(user, isUpdate ? AuditEventType.UpdatedItem : AuditEventType.CreatedItem, "Modified OCM-" + cpData.Id, null);
                    //add reputation points
                    new UserManager().AddReputationPoints(user, 1);
                }

                //preserve new POI Id for caller
                updatedPOI.ID = cpData.Id;

                if (performCacheRefresh)
                {
                    if (supersedesID != null)
                    {
                        await CacheManager.RefreshCachedPOI((int)supersedesID);
                    }
                    await CacheManager.RefreshCachedPOI(updatedPOI.ID);
                }

                return(new ValidationResult {
                    IsValid = true, ItemId = updatedPOI.ID, Message = "Update submitted."
                });
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine(exp.ToString());
                AuditLogManager.ReportWebException(true, null, AuditEventType.SystemErrorWeb, "POI Submission Failed", exp);

                //error performing submission
                return(new ValidationResult {
                    IsValid = false, Message = "Submission Failed with an Exception: " + exp.Message
                });
            }
        }
예제 #21
0
        /// <summary>
        /// Output Core Reference Data (lookup lists, default objects)
        /// </summary>
        /// <param name="outputProvider"></param>
        /// <param name="context"></param>
        /// <param name="filter"></param>
        private void OutputCoreReferenceData(IOutputProvider outputProvider, HttpContext context, APIRequestParams filter)
        {
            //get core reference data
            var refDataManager = new ReferenceDataManager();
            CoreReferenceData data = null;

            //cache result
            if (HttpContext.Current.Cache["CoreRefData"] != null && filter.EnableCaching)
            {
                data = (CoreReferenceData)HttpContext.Current.Cache["CoreRefData"];
            }
            else
            {
                data = refDataManager.GetCoreReferenceData();

                HttpContext.Current.Cache.Add("CoreRefData", data, null, Cache.NoAbsoluteExpiration, new TimeSpan(1, 0, 0), CacheItemPriority.Normal, null);
            }

            //populate non-cached fragments (user profile)
            data.UserProfile = new InputProviderBase().GetUserFromAPICall(context);

            //send response
            outputProvider.GetOutput(context.Response.OutputStream, data, filter);
        }