Esempio n. 1
0
        /// <summary>
        /// Get all subscription matches for all active subscriptions where applicable
        /// </summary>
        /// <returns></returns>
        public 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 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 = GetSubscriptionMatches(dataModel, poiManager, subscription);
                    if (subscriptionMatchGroup.SubscriptionMatches.Any())
                    {
                        subscriptionMatchGroup.Subscription = OCM.API.Common.Model.Extensions.UserSubscription.FromDataModel(subscription, true);
                        allMatches.Add(subscriptionMatchGroup);
                    }
                }
            }
            return(allMatches);
        }
Esempio n. 2
0
        public void CleanupRedundantEditQueueitems()
        {
            var sourceList = DataModel.EditQueueItems;

            var redundantEdits = new List <Model.EditQueueItem>();

            var cpManager = new POIManager();

            foreach (var item in sourceList)
            {
                var editItem = GetItemWithDifferences(item, cpManager, true);
                if (editItem.Differences.Count == 0)
                {
                    redundantEdits.Add(editItem);
                }
            }

            //delete redundant edits
            foreach (var item in redundantEdits)
            {
                var delItem = DataModel.EditQueueItems.Find(item.ID);
                DataModel.EditQueueItems.Remove(delItem);
            }
            DataModel.SaveChanges();
        }
Esempio n. 3
0
        public IEnumerable <ChargePoint> Get()
        {
            // use custom query string parsing for compatibility
            var filter = new APIRequestParams();

            //set defaults
            var paramList = new NullSafeDictionary <string, string>();

            foreach (var k in Request.Query.Keys)
            {
                paramList.Add(k.ToLower(), Request.Query[k]);
            }

            filter.ParseParameters(filter, paramList);

            if (string.IsNullOrEmpty(filter.APIKey))
            {
                if (Request.Headers.ContainsKey("X-API-Key"))
                {
                    filter.APIKey = Request.Headers["X-API-Key"];
                }
            }

            var api = new POIManager();

            var list = api.GetPOIList(filter);

            return(list);
        }
Esempio n. 4
0
        public async Task <ActionResult> CommentActioned(int poiId, int commentId)
        {
            CheckForReadOnly();

            // if poi is awaiting review, publish now
            var poiManager = new POIManager();

            var poi = await poiManager.Get(poiId, true);

            var comment = poi.UserComments.Find(c => c.ID == commentId);

            using (var userManager = new UserManager())
            {
                var user = userManager.GetUser((int)UserID);

                if (POIManager.CanUserEditPOI(poi, user))
                {
                    using (var commentManager = new UserCommentManager())
                    {
                        await commentManager.ActionComment(user.ID, commentId);
                    }
                }
            }

            // return to approval queue
            return(RedirectToAction("details", "POI", new { id = poiId }));
        }
Esempio n. 5
0
        public async Task <ValidationResult> ProcessEquipmentSubmission(HttpContext context)
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.Body);
            //TODO: handle encoding (UTF etc) correctly
            string responseContent = await sr.ReadToEndAsync();

            string jsonString = responseContent.Trim();

            try
            {
                JObject o = JObject.Parse(jsonString);

                JsonSerializer serializer = new JsonSerializer();
                var            cp         = (Common.Model.ChargePoint)serializer.Deserialize(new JTokenReader(o), typeof(Common.Model.ChargePoint));

                //validate cp submission
                return(POIManager.IsValid(cp));
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine(exp);

                //submission failed
                return(new ValidationResult {
                    IsValid = false, Message = "Exception processing submission:" + exp.Message
                });
            }
        }
Esempio n. 6
0
        public ContentResult Share(int id)
        {
            // use custom query string parsing for compatibility

            var api = new POIManager();


            var poi = api.GetFullDetails(id);

            if (poi != null)
            {
                var content = $"<meta http-equiv='refresh' content = '0;url=https://openchargemap.org/site/poi/details/{poi.ID}' />";

                content += $"<meta property='og: title' content='{poi.AddressInfo.Title} - OCM-{poi.ID}'>";

                if (poi.MediaItems != null && poi.MediaItems.Any())
                {
                    content += $"<meta property = 'og:image' content = '{poi.MediaItems[0].ItemThumbnailURL}' >";
                }

                content += $"<h1>{poi.AddressInfo.Title} - OCM-{poi.ID}</h1>";

                return(base.Content(content, "text/html"));
            }


            return(base.Content("The location you have linked to does not currently exist. Please check your link and try again.", "text/html"));
        }
Esempio n. 7
0
        public bool ProcessEquipmentSubmission(HttpContext context, ref OCM.API.Common.Model.ChargePoint cp)
        {
            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);
            //TODO: handle encoding (UTF etc) correctly
            string responseContent = sr.ReadToEnd().Trim();

            string jsonString = responseContent;

            try
            {
                JObject o = JObject.Parse(jsonString);

                JsonSerializer serializer = new JsonSerializer();
                cp = (Common.Model.ChargePoint)serializer.Deserialize(new JTokenReader(o), typeof(Common.Model.ChargePoint));

                //validate cp submission

                if (POIManager.IsValid(cp))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception exp)
            {
                System.Diagnostics.Debug.WriteLine(exp);

                //submission failed
                return(false);
            }
        }
Esempio n. 8
0
        //
        // GET: /POI/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id > 0)
            {
                var poi = new POIManager().Get((int)id);
                if (poi != null)
                {
                    InitEditReferenceData(poi);

                    var refData = new POIBrowseModel();
                    ViewBag.ReferenceData    = refData;
                    ViewBag.HideAdvancedInfo = true;

                    try
                    {
                        var user = new UserManager().GetUser((int)Session["UserID"]);
                        if (POIManager.CanUserEditPOI(poi, user))
                        {
                            ViewBag.HideAdvancedInfo = false;
                        }
                    }
                    catch (Exception)
                    {
                        ;;  //user not signed in
                    }

                    //enable advanced edit options for full editors/admin
                    return(View(poi));
                }
            }

            //no applicable poi, jump back to browse
            return(RedirectToAction("Index", "POI"));
        }
Esempio n. 9
0
        /// <summary>
        /// Output compact (id's only for reference data) POI list
        /// </summary>
        /// <param name="context"></param>
        /// <param name="filter"></param>
        private void OutputCompactPOIList(HttpContext context, APIRequestParams filter)
        {
            //get list of charge points as compact POISearchResult List for output:
            List <OCM.API.Common.Model.ChargePoint> dataList = new POIManager().GetChargePoints(filter);
            int numResults = dataList.Count;

            List <POISearchResult> poiList = new List <POISearchResult>();

            foreach (var c in dataList)
            {
                var poi = new POISearchResult
                {
                    ID           = c.ID,
                    Title        = c.AddressInfo.Title,
                    Address      = c.AddressInfo.AddressLine1,
                    Distance     = c.AddressInfo.Distance,
                    Latitude     = (double)c.AddressInfo.Latitude,
                    Longitude    = (double)c.AddressInfo.Longitude,
                    Postcode     = c.AddressInfo.Postcode,
                    UsageTypeID  = c.UsageType != null ? c.UsageType.ID : 0,
                    StatusTypeID = c.StatusType != null ? c.StatusType.ID : 0
                };
                poiList.Add(poi);
            }
            var    o           = new JSONOutputProvider();
            string description = "Compact POI List: id=ID, t= Title, u= UsageTypeID, s= StatusTypeID, a=Address, p=Postcode, lt=Latitude, lg=Longitude, d= Distance";

            o.PerformSerialisationV2(context.Response.OutputStream, new { status = "OK", description = description, count = poiList.Count, results = poiList }, filter.Callback);
        }
Esempio n. 10
0
        public void CleanupRedundantEditQueueitems()
        {
            var cpManager = new POIManager();

            // cleanup new items not marked as processed but not awaiting review
            var sourceList = DataModel
                             .EditQueueItems
                             .Include(e => e.User)
                             .Include(e => e.ProcessedByUser)
                             .Include(e => e.EntityType)
                             .Where(e => e.IsProcessed == false && e.PreviousData == null);

            System.Diagnostics.Debug.WriteLine($"Cleanup of added items: {sourceList.Count()}");

            var processedEdits = new List <Model.EditQueueItem>();

            foreach (var item in sourceList)
            {
                var p = cpManager.Get((int)item.EntityId);
                if (p != null)
                {
                    if (p.SubmissionStatusTypeID != (int)StandardSubmissionStatusTypes.Submitted_UnderReview && p.SubmissionStatusTypeID != (int)StandardSubmissionStatusTypes.Submitted_UnderReview)
                    {
                        item.IsProcessed       = true;
                        item.ProcessedByUserId = (int)StandardUsers.System;
                        item.DateProcessed     = p.DateCreated;
                    }
                }
            }
            DataModel.SaveChanges();

            // cleanup edits with no differences

            sourceList = DataModel
                         .EditQueueItems
                         .Include(e => e.User)
                         .Include(e => e.ProcessedByUser)
                         .Include(e => e.EntityType)
                         .AsNoTracking().Where(e => e.IsProcessed == false && e.PreviousData != null);

            var redundantEdits = new List <Model.EditQueueItem>();

            foreach (var item in sourceList)
            {
                var editItem = GetItemWithDifferences(item, cpManager, true);
                if (editItem.Differences.Count == 0)
                {
                    redundantEdits.Add(editItem);
                }
            }

            //delete redundant edits
            foreach (var item in redundantEdits)
            {
                var delItem = DataModel.EditQueueItems.Find(item.ID);
                DataModel.EditQueueItems.Remove(delItem);
            }
            DataModel.SaveChanges();
        }
Esempio n. 11
0
    void Start()
    {
        GameObject tempPrefab = Instantiate(pointOfIntrestPrefab, this.transform.position, Quaternion.identity);

        tempPrefab.transform.parent = this.transform;
        tempPrefab.GetComponent <PointOfIntrest>().pointType = disasterType;
        tempPrefab.GetComponent <PointOfIntrest>().initPoint(disasterType);
        poiManager = GameObject.Find("POIManager").GetComponent <POIManager>();
    }
Esempio n. 12
0
        /// <summary>
        /// Output standard POI List results
        /// </summary>
        /// <param name="outputProvider"></param>
        /// <param name="context"></param>
        /// <param name="filter"></param>
        private void OutputPOIList(IOutputProvider outputProvider, HttpContext context, APIRequestSettings filter)
        {
            List <OCM.API.Common.Model.ChargePoint> dataList = null;

            //get list of charge points for output:
            dataList = new POIManager().GetChargePoints(filter);

            int numResults = dataList.Count;

            //send response
            outputProvider.GetOutput(context.Response.OutputStream, dataList, filter);
        }
Esempio n. 13
0
        public async Task <MediaItem> AddPOIMediaItem(string tempFolder, string sourceImageFile, int chargePointId, string comment, bool isVideo, int userId)
        {
            var dataModel = new OCMEntities();

            var mediaItem = new MediaItem();

            var poi = new POIManager().Get(chargePointId);

            if (poi == null)
            {
                //POI not recognised
                return(null);
            }
            string[] urls = await UploadPOIImageToStorage(tempFolder, sourceImageFile, poi);

            if (urls == null)
            {
                //failed to upload, preserve submission data
                System.IO.File.WriteAllText(tempFolder + "\\OCM_" + chargePointId + "_" + (DateTime.Now.ToFileTimeUtc().ToString()) + ".json", "{userId:" + userId + ",comment:\"" + comment + "\"}");
                return(null);
            }
            else
            {
                mediaItem.ItemUrl          = urls[0];
                mediaItem.ItemThumbnailUrl = urls[1];

                mediaItem.User               = dataModel.Users.FirstOrDefault(u => u.Id == userId);
                mediaItem.ChargePoint        = dataModel.ChargePoints.FirstOrDefault(cp => cp.Id == chargePointId);
                mediaItem.Comment            = comment;
                mediaItem.DateCreated        = DateTime.UtcNow;
                mediaItem.IsEnabled          = true;
                mediaItem.IsExternalResource = false;
                mediaItem.IsVideo            = isVideo;

                dataModel.MediaItems.Add(mediaItem);

                dataModel.ChargePoints.Find(chargePointId).DateLastStatusUpdate = DateTime.UtcNow;
                dataModel.SaveChanges();

                new UserManager().AddReputationPoints(userId, 1);

                try
                {
                    //fire and forget cache update
                    CacheManager.RefreshCachedPOI(poi.ID);
                }
                catch { }

                return(mediaItem);
            }
        }
Esempio n. 14
0
        public async Task <ActionResult> Edit(int?id, bool createCopy = false)
        {
            ViewBag.IsReadOnlyMode = this.IsReadOnlyMode;

            if (id > 0)
            {
                ChargePoint poi = null;

                if (createCopy)
                {
                    //get version of POI with location details removed, copying equipment etc
                    poi = await new POIManager().GetCopy((int)id, true);
                }
                else
                {
                    poi = await new POIManager().Get((int)id);
                }

                if (poi != null)
                {
                    InitEditReferenceData(poi);

                    var refData = new POIBrowseModel(GetCoreReferenceData());
                    ViewBag.ReferenceData    = refData;
                    ViewBag.HideAdvancedInfo = true;

                    if (!createCopy)
                    {
                        try
                        {
                            var user = new UserManager().GetUser((int)UserID);
                            if (POIManager.CanUserEditPOI(poi, user))
                            {
                                ViewBag.HideAdvancedInfo = false;
                            }
                        }
                        catch (Exception)
                        {
                            ;;  //user not signed in
                        }
                    }

                    //enable advanced edit options for full editors/admin
                    return(View(poi));
                }
            }

            //no applicable poi, jump back to browse
            return(RedirectToAction("Index", "POI"));
        }
Esempio n. 15
0
        //convert a simple POI to data and back again to fully populate all related properties, as submission may only have simple IDs for ref data etc
        private Model.ChargePoint PopulateFullPOI(Model.ChargePoint poi, Model.CoreReferenceData refData)
        {
            OCMEntities tempDataModel = new OCMEntities();

            //convert simple poi to fully populated db version
            var poiData = new POIManager().PopulateChargePoint_SimpleToData(poi, tempDataModel);

            //convert back to simple POI
            var modelPOI = Model.Extensions.ChargePoint.FromDataModel(poiData, false, false, true, true, refData);

            //clear temp changes from the poi
            //dataModel.Entry(poiData).Reload();
            tempDataModel.Dispose();
            return(modelPOI);
        }
Esempio n. 16
0
        public POIRecentActivity GetActivitySummary(APIRequestParams filterSettings)
        {
            //default to last month
            DateTime dateFrom = DateTime.UtcNow.AddMonths(-1);

            if (filterSettings != null)
            {
                if (filterSettings.ChangesFromDate != null)
                {
                    dateFrom = filterSettings.ChangesFromDate.Value;
                }
                else
                {
                    filterSettings.ChangesFromDate = dateFrom;
                }
            }

            //populate recently added comments
            var recentComments = from c in DataModel.UserComments
                                 where c.DateCreated >= dateFrom
                                 select c;

            var summary = new POIRecentActivity();

            summary.RecentComments = new List <UserComment>();
            foreach (var c in recentComments.OrderByDescending(c => c.DateCreated).Take(10).ToList())
            {
                summary.RecentComments.Add(Model.Extensions.UserComment.FromDataModel(c, true));
            }

            //populate recently modified charge points TODO: differentiate between updated since and created since?
            var poiManager = new POIManager();

            var allRecentPOIChanges = poiManager.GetChargePoints(filterSettings);

            summary.POIRecentlyAdded   = allRecentPOIChanges.Where(p => p.DateCreated >= dateFrom).OrderByDescending(p => p.DateCreated).Take(10).ToList();
            summary.POIRecentlyUpdated = allRecentPOIChanges.Where(p => p.DateLastStatusUpdate >= dateFrom && p.DateCreated != p.DateLastStatusUpdate).OrderByDescending(p => p.DateLastStatusUpdate).Take(10).ToList();

            var recentMedia = DataModel.MediaItems.Where(m => m.DateCreated > dateFrom && m.IsEnabled == true).OrderByDescending(m => m.DateCreated).Take(10).ToList();

            summary.RecentMedia = new List <MediaItem>();
            foreach (var mediaItem in recentMedia.OrderByDescending(m => m.DateCreated))
            {
                summary.RecentMedia.Add(Model.Extensions.MediaItem.FromDataModel(mediaItem));
            }

            return(summary);
        }
Esempio n. 17
0
        public SubscriptionMatchGroup GetSubscriptionMatches(int subscriptionId, int userId, DateTime?dateFrom)
        {
            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(GetSubscriptionMatches(dataModel, poiManager, subscription, dateFrom));
            }
            else
            {
                return(null);
            }
        }
        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);
            }
        }
Esempio n. 19
0
 public POI(POIType type, POIManager pm)
 {
     this.type   = type;
     this.status = POIStatus.Hidden;
     this.pm     = pm;
     if (status == POIStatus.Hidden)
     {
         Prefab = pm.gm.poiPrefabs[0];
     }
     else if (status == POIStatus.Revealed && type == POIType.Victim)
     {
         Prefab = pm.gm.poiPrefabs[1];
     }
     else if (status == POIStatus.Treated && type == POIType.Victim)
     {
         Prefab = pm.gm.poiPrefabs[2];
     }
 }
Esempio n. 20
0
        public Model.EditQueueItem GetItemWithDifferences(Core.Data.EditQueueItem item, POIManager cpManager, bool loadCurrentItem)
        {
            var queueItem = Model.Extensions.EditQueueItem.FromDataModel(item);

            //get diff between previous and edit

            Model.ChargePoint poiA = DeserializePOIFromJSON(queueItem.PreviousData);

            if (loadCurrentItem && poiA != null)
            {
                poiA = new POIManager().Get(poiA.ID);
            }
            Model.ChargePoint poiB = DeserializePOIFromJSON(queueItem.EditData);

            queueItem.Differences = cpManager.CheckDifferences(poiA, poiB, useObjectCompare: true);

            return(queueItem);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            var evseManager = new POIManager();
            var testPoint   = evseManager.Get(3400);

            if (testPoint != null)
            {
                List <ChargePoint> sourceList = new List <ChargePoint>();
                sourceList.Add(testPoint);
                GridViewSource.DataSource = sourceList;
                GridViewSource.DataBind();

                var similarPoints = evseManager.FindSimilar(testPoint);

                GridViewSimilar.DataSource = similarPoints;
                GridViewSimilar.DataBind();
            }
            else
            {
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Output standard POI List results
        /// </summary>
        /// <param name="outputProvider"></param>
        /// <param name="context"></param>
        /// <param name="filter"></param>
        private void OutputPOIList(IOutputProvider outputProvider, HttpContext context, APIRequestParams filter)
        {
#if DEBUG
            var stopwatch = Stopwatch.StartNew();
#endif
            List <OCM.API.Common.Model.ChargePoint> dataList = null;

            //get list of charge points for output:
            dataList = new POIManager().GetChargePoints(filter);

#if DEBUG
            System.Diagnostics.Debug.WriteLine("OutputPOIList: Time for Query/Conversion: " + stopwatch.ElapsedMilliseconds + "ms");
            stopwatch.Restart();
#endif
            //send response
            outputProvider.GetOutput(context.Response.OutputStream, dataList, filter);

#if DEBUG
            System.Diagnostics.Debug.WriteLine("OutputPOIList: Time for Output to stream: " + stopwatch.ElapsedMilliseconds + "ms");
#endif
        }
Esempio n. 23
0
    private void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
        else
        {
            return;
        }

        SceneManager.sceneUnloaded += ClearPOIList;
        SceneManager.sceneLoaded   += UpdateBookmarks;

        defaultPOIMat     = defaultPOIMaterialEditor;
        highlightedPOIMat = highlightedPOIMaterialEditor;
        selectedPOIMat    = selectedPOIMaterialEditor;

        gameManager = GetComponentInParent <GameManager>();
        bookmarks   = gameManager.user.GetComponentInChildren <BookmarkController>();
    }
Esempio n. 24
0
        /// <summary>
        /// Output standard POI List results
        /// </summary>
        /// <param name="outputProvider"></param>
        /// <param name="context"></param>
        /// <param name="filter"></param>
        private async Task OutputPOIList(IOutputProvider outputProvider, HttpContext context, APIRequestParams filter)
        {
#if DEBUG
            var stopwatch = Stopwatch.StartNew();
#endif
            IEnumerable <OCM.API.Common.Model.ChargePoint> dataList = null;

            //get list of charge points for output:
            var poiManager = new POIManager();
            dataList = await poiManager.GetPOIListAsync(filter);

#if DEBUG
            System.Diagnostics.Debug.WriteLine("OutputPOIList: Time for Query/Conversion: " + stopwatch.ElapsedMilliseconds + "ms");
            stopwatch.Restart();
#endif
            //send response
            await outputProvider.GetOutput(context, context.Response.Body, dataList, filter);

#if DEBUG
            System.Diagnostics.Debug.WriteLine("OutputPOIList: Time for Output to stream: " + stopwatch.ElapsedMilliseconds + "ms");
#endif
        }
Esempio n. 25
0
        public async Task <ActionResult> Approve(int id)
        {
            CheckForReadOnly();

            // if poi is awaiting review, publish now
            var poiManager = new POIManager();

            var poi = await poiManager.Get(id, true);

            if (poi.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Submitted_UnderReview || poi.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Imported_UnderReview)
            {
                var user = new UserManager().GetUser((int)UserID);
                if (POIManager.CanUserEditPOI(poi, user))
                {
                    poi.SubmissionStatusTypeID = (int)StandardSubmissionStatusTypes.Submitted_Published;
                    await new SubmissionManager().PerformPOISubmission(poi, user);
                }
            }

            // return to approval queue
            return(RedirectToAction("Index", "POI", new { submissionStatusTypeId = 1 }));
        }
Esempio n. 26
0
        public List <Model.EditQueueItem> GetEditQueueItems(EditQueueFilter filter)
        {
            var sourceList =
                DataModel.EditQueueItems.Where(
                    i => (
                        (filter.ShowProcessed || (filter.ShowProcessed == false && i.IsProcessed == false)) &&
                        (filter.DateFrom == null || (filter.DateFrom != null && i.DateSubmitted >= filter.DateFrom)) &&
                        (filter.DateTo == null || (filter.DateTo != null && i.DateSubmitted <= filter.DateTo)) &&
                        (filter.ShowEditsOnly == false || (filter.ShowEditsOnly == true && i.PreviousData != null))
                        )).OrderByDescending(e => e.DateSubmitted);

            var cpManager  = new POIManager();
            var outputList = new List <Model.EditQueueItem>();

            //perform object level differencing on json contents of edit queue items (very expensive), used to get summary and count of differences per item
            foreach (var editQueueItem in sourceList)
            {
                outputList.Add(GetItemWithDifferences(editQueueItem, cpManager, false));
            }

            return(outputList.Where(i => i.Differences.Count >= filter.MinimumDifferences).Take(filter.MaxResults).ToList());
        }
Esempio n. 27
0
        public ActionResult ReviewDuplicates(int?countryId, bool enableCache = true, double maxDupeRange = 500, int minConfidence = 70)
        {
            if (countryId == null)
            {
                countryId = 1;                   //default to UK
            }
            ViewBag.MinConfidenceLevel = minConfidence;
            string cacheKey = "DupeList_" + countryId;

            OCM.API.Common.Model.Extended.POIDuplicates duplicateSummary = null;
            if (HttpRuntime.Cache[cacheKey] != null && enableCache)
            {
                duplicateSummary = (OCM.API.Common.Model.Extended.POIDuplicates)HttpRuntime.Cache[cacheKey];
            }
            else
            {
                duplicateSummary            = new POIManager().GetAllPOIDuplicates((int)countryId, maxDupeRange);
                HttpRuntime.Cache[cacheKey] = duplicateSummary;
            }

            ViewBag.ShowDataProvider = true;
            return(View(duplicateSummary.DuplicateSummaryList));
        }
Esempio n. 28
0
    public Fireman(String name, Colors color, GameObject s, GameObject firemanplusvictim, int in_x, int in_z, GameManager gm, Role role, POIManager
                   pOIManager, HazmatManager hazmatManager)
    {
        this.name          = name;
        this.color         = color;
        this.s             = s;
        this.fireandvictim = firemanplusvictim;
        this.currentX      = in_x;
        this.currentZ      = in_z;
        this.gm            = gm;
        setRole(role);
        Debug.Log("FreeAP: " + FreeAP);
        this.FreeAP          = AP + savedAP;
        this.remainingSpecAp = this.specialtyAP;

        this.pOIManager     = pOIManager;
        this.hazamatManager = hazmatManager;


        //if (string.Equals(level, "Experienced"))
        //{
        //    setRole(role);
        //}
    }
Esempio n. 29
0
        public async Task <JsonResult> PollForTasks(string key)
        {
            int          notificationsSent = 0;
            MirrorStatus mirrorStatus      = null;

            //poll for periodic tasks (subscription notifications etc)
            if (key == System.Configuration.ConfigurationManager.AppSettings["AdminPollingAPIKey"])
            {
                //send all pending subscription notifications
                if (bool.Parse(ConfigurationManager.AppSettings["EnableSubscriptionChecks"]) == true)
                {
                    try
                    {
                        //TODO: can't run in seperate async thread becuase HttpContext is not available
                        string templateFolderPath = _host.ContentRootPath + "/templates/Notifications";

                        notificationsSent = await new UserSubscriptionManager().SendAllPendingSubscriptionNotifications(templateFolderPath);
                    }
                    catch (Exception)
                    {
                        ;;  //failed to send notifications
                    }
                }


                var autoApproveDays = 3;

                var poiManager = new POIManager();
                var newPois    = await poiManager.GetPOIListAsync(new APIRequestParams { SubmissionStatusTypeID = 1 });

                var user = new UserManager().GetUser((int)StandardUsers.System);

                foreach (var poi in newPois)
                {
                    if (poi.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Submitted_UnderReview || poi.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Imported_UnderReview)
                    {
                        if (poi.DateCreated < DateTime.UtcNow.AddDays(-autoApproveDays))
                        {
                            poi.SubmissionStatusTypeID = (int)StandardSubmissionStatusTypes.Submitted_Published;
                            new SubmissionManager().PerformPOISubmission(poi, user);
                        }
                    }
                }

                // check for edit queue items to auto approve
                using (var editQueueManager = new EditQueueManager())
                {
                    var queueItems = editQueueManager.GetEditQueueItems(new EditQueueFilter {
                        ShowProcessed = false
                    })
                                     .Where(q => q.DateProcessed == null).ToList()
                                     .OrderBy(q => q.DateSubmitted);

                    foreach (var i in queueItems)
                    {
                        if (i.DateSubmitted < DateTime.UtcNow.AddDays(-autoApproveDays))
                        {
                            editQueueManager.ProcessEditQueueItem(i.ID, true, (int)StandardUsers.System, true, "Auto Approved");
                        }
                    }
                }


                //update cache mirror
                try
                {
                    _cache.Set("_MirrorRefreshInProgress", true);
                    mirrorStatus = await CacheManager.RefreshCachedData(CacheUpdateStrategy.Modified);
                }
                catch (Exception)
                {
                    ;; //failed to update cache
                }
                finally
                {
                    _cache.Set("_MirrorRefreshInProgress", false);
                }

                //update stats
                if (_cache.Get("_StatsRefreshed") == null)
                {
                    using (var dataSummaryManager = new API.Common.DataSummary.DataSummaryManager())
                    {
                        await dataSummaryManager.RefreshStats();

                        _cache.Set("_StatsRefreshed", true);
                    }
                }
            }
            return(Json(new { NotificationsSent = notificationsSent, MirrorStatus = mirrorStatus }));
        }
Esempio n. 30
0
        public POIDuplicates GetAllPOIDuplicates(POIManager poiManager, int countryId, double maxDupeRange = 500)
        {
            List <DuplicatePOIItem> allDuplicates = new List <DuplicatePOIItem>();

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

            double DUPLICATE_DISTANCE_METERS          = 25;
            double POSSIBLE_DUPLICATE_DISTANCE_METERS = maxDupeRange;

            //TODO: better method for large number of POIs
            //grab all live POIs (30-100,000 items)
            //var allPOIs = dataModel.ChargePoints.Where(s => s.AddressInfo.CountryID == countryId && (s.SubmissionStatusTypeID == 100 || s.SubmissionStatusTypeID == 200)).ToList();
            var allPOIs = poiManager.GetPOIList(new APIRequestParams {
                CountryIDs = new int[] { countryId }, MaxResults = 100000
            });

            foreach (var poi in allPOIs)
            {
                //find pois which duplicate the given poi
                var dupePOIs = allPOIs.Where(p => p.ID != poi.ID &&
                                             (
                                                 p.DataProvidersReference != null && p.DataProvidersReference.Length > 0 && p.DataProvidersReference == poi.DataProvidersReference ||
                                                 new GeoCoordinate(p.AddressInfo.Latitude, p.AddressInfo.Longitude).GetDistanceTo(new GeoCoordinate(poi.AddressInfo.Latitude, poi.AddressInfo.Longitude)) < POSSIBLE_DUPLICATE_DISTANCE_METERS
                                             )
                                             );

                if (dupePOIs.Any())
                {
                    var poiModel = poi;// OCM.API.Common.Model.Extensions.ChargePoint.FromDataModel(poi, true, true, true, true);

                    foreach (var dupe in dupePOIs)
                    {
                        //poi has duplicates
                        DuplicatePOIItem dupePoi = new DuplicatePOIItem {
                            DuplicatePOI = dupe, DuplicateOfPOI = poiModel
                        };
                        dupePoi.Reasons = new List <string>();
                        if (dupe.AddressInfo.Latitude == poi.AddressInfo.Latitude && dupe.AddressInfo.Longitude == poi.AddressInfo.Longitude)
                        {
                            dupePoi.Reasons.Add("POI location is exact match for OCM-" + poi.ID);
                            dupePoi.Confidence = 95;
                        }
                        else
                        {
                            double distanceMeters = new GeoCoordinate(dupe.AddressInfo.Latitude, dupe.AddressInfo.Longitude).GetDistanceTo(new GeoCoordinate(poi.AddressInfo.Latitude, poi.AddressInfo.Longitude));
                            if (distanceMeters < DUPLICATE_DISTANCE_METERS)
                            {
                                dupePoi.Reasons.Add("POI location is close proximity (" + distanceMeters + "m) to OCM-" + poi.ID);
                                dupePoi.Confidence = 75;
                            }
                            else
                            {
                                if (distanceMeters < POSSIBLE_DUPLICATE_DISTANCE_METERS)
                                {
                                    dupePoi.Reasons.Add("POI location is in surrounding proximity (" + distanceMeters + "m) to OCM-" + poi.ID);
                                    dupePoi.Confidence = 50;
                                }
                            }
                        }

                        allDuplicates.Add(dupePoi);
                    }
                }
            }

            //arrange all duplicates into groups
            POIDuplicates duplicatesSummary = new POIDuplicates();

            duplicatesSummary.DuplicateSummaryList = new List <DuplicatePOIGroup>();
            foreach (var dupe in allDuplicates)
            {
                bool isNewGroup = false;
                var  dupeGroup  = duplicatesSummary.DuplicateSummaryList.FirstOrDefault(d => d.DuplicatePOIList.Any(p => p.DuplicateOfPOI.ID == dupe.DuplicateOfPOI.ID || p.DuplicatePOI.ID == dupe.DuplicatePOI.ID) || d.SuggestedBestPOI.ID == dupe.DuplicatePOI.ID);
                if (dupeGroup == null)
                {
                    isNewGroup = true;
                    dupeGroup  = new DuplicatePOIGroup();
                    dupeGroup.SuggestedBestPOI = dupe.DuplicatePOI;//TODO: select best

                    dupeGroup.DuplicatePOIList = new List <DuplicatePOIItem>();
                }

                //only add to dupe group if not already added for another reason
                if (!dupeGroup.DuplicatePOIList.Contains(dupe) && !dupeGroup.DuplicatePOIList.Any(d => d.DuplicatePOI.ID == dupe.DuplicatePOI.ID))
                {
                    dupeGroup.DuplicatePOIList.Add(dupe);
                }

                if (isNewGroup)
                {
                    duplicatesSummary.DuplicateSummaryList.Add(dupeGroup);
                }
            }

            //loop through groups and rearrange
            RearrangeDuplicates(duplicatesSummary);

            //go through all groups and populate final list of All POI per group
            foreach (var g in duplicatesSummary.DuplicateSummaryList)
            {
                var poiList = new List <OCM.API.Common.Model.ChargePoint>();
                foreach (var d in g.DuplicatePOIList)
                {
                    if (!poiList.Contains(d.DuplicatePOI))
                    {
                        poiList.Add(d.DuplicatePOI);
                    }

                    if (!poiList.Contains(d.DuplicateOfPOI))
                    {
                        poiList.Add(d.DuplicateOfPOI);
                    }

                    g.AllPOI = poiList;
                }
            }

            //TODO: go through all dupe groups and nominate best poi to be main poi (most comments, most equipment info etc)
            return(duplicatesSummary);
        }
Esempio n. 31
0
        public POIRecentActivity GetActivitySummary(APIRequestParams filterSettings)
        {
            //default to last month
            DateTime dateFrom = DateTime.UtcNow.AddMonths(-1);

            if (filterSettings != null)
            {
                if (filterSettings.ChangesFromDate != null)
                {
                    dateFrom = filterSettings.ChangesFromDate.Value;
                }
                else
                {
                    filterSettings.ChangesFromDate = dateFrom;
                }
            }

            //populate recently added comments
            var recentComments = from c in DataModel.UserComments
                                 where c.DateCreated >= dateFrom
                                 select c;

            var summary = new POIRecentActivity();
            summary.RecentComments = new List<UserComment>();
            foreach (var c in recentComments.OrderByDescending(c => c.DateCreated).Take(10).ToList())
            {
                summary.RecentComments.Add(Model.Extensions.UserComment.FromDataModel(c, true));
            }

            //populate recently modified charge points TODO: differentiate between updated since and created since?
            var poiManager = new POIManager();

            var allRecentPOIChanges = poiManager.GetChargePoints(filterSettings);
            summary.POIRecentlyAdded = allRecentPOIChanges.Where(p => p.DateCreated >= dateFrom).OrderByDescending(p => p.DateCreated).Take(10).ToList();
            summary.POIRecentlyUpdated = allRecentPOIChanges.Where(p => p.DateLastStatusUpdate >= dateFrom && p.DateCreated != p.DateLastStatusUpdate).OrderByDescending(p => p.DateLastStatusUpdate).Take(10).ToList();

            var recentMedia = DataModel.MediaItems.Where(m => m.DateCreated > dateFrom && m.IsEnabled == true).OrderByDescending(m => m.DateCreated).Take(10).ToList();
            summary.RecentMedia = new List<MediaItem>();
            foreach (var mediaItem in recentMedia.OrderByDescending(m => m.DateCreated))
            {
                summary.RecentMedia.Add(Model.Extensions.MediaItem.FromDataModel(mediaItem));
            }

            return summary;
        }