/// <inheritdoc />
        public async Task <PointOfInterestExtended> AddPointOfInterest(PointOfInterestExtended pointOfInterest, TokenAndSecret tokenAndSecret, string language)
        {
            var osmGateway  = _httpGatewayFactory.CreateOsmGateway(tokenAndSecret);
            var changesetId = await osmGateway.CreateChangeset("Add POI interface from IHM site.");

            var node = new Node
            {
                Latitude  = pointOfInterest.Location.lat,
                Longitude = pointOfInterest.Location.lng,
                Tags      = new TagsCollection
                {
                    { FeatureAttributes.WEBSITE, pointOfInterest.Url }
                }
            };

            for (var imageIndex = 0; imageIndex < pointOfInterest.ImagesUrls.Length; imageIndex++)
            {
                var imageUrl = pointOfInterest.ImagesUrls[imageIndex];
                var tagName  = imageIndex == 0 ? FeatureAttributes.IMAGE_URL : FeatureAttributes.IMAGE_URL + imageIndex;
                node.Tags.Add(tagName, imageUrl);
            }
            SetTagByLanguage(node.Tags, FeatureAttributes.NAME, pointOfInterest.Title, language);
            SetTagByLanguage(node.Tags, FeatureAttributes.DESCRIPTION, pointOfInterest.Description, language);
            AddTagsByIcon(node.Tags, pointOfInterest.Icon);
            RemoveEmptyTags(node.Tags);
            var id = await osmGateway.CreateElement(changesetId, node);

            node.Id = long.Parse(id);
            await osmGateway.CloseChangeset(changesetId);

            var feature = await UpdateElasticSearch(node, pointOfInterest.Title);

            return(await FeatureToExtendedPoi(feature, language));
        }
示例#2
0
        /// <inheritdoc />
        public async Task <PointOfInterestExtended> AddPointOfInterest(PointOfInterestExtended pointOfInterest, TokenAndSecret tokenAndSecret, string language)
        {
            var osmGateway  = _httpGatewayFactory.CreateOsmGateway(tokenAndSecret);
            var changesetId = await osmGateway.CreateChangeset($"Added {pointOfInterest.Title} using IsraelHiking.osm.org.il");

            var node = new Node
            {
                Latitude  = pointOfInterest.Location.Lat,
                Longitude = pointOfInterest.Location.Lng,
                Tags      = new TagsCollection()
            };

            SetWebsiteUrl(node.Tags, pointOfInterest);
            SetMultipleValuesForTag(node.Tags, FeatureAttributes.IMAGE_URL, pointOfInterest.ImagesUrls);
            SetTagByLanguage(node.Tags, FeatureAttributes.NAME, pointOfInterest.Title, language);
            SetTagByLanguage(node.Tags, FeatureAttributes.DESCRIPTION, pointOfInterest.Description, language);
            AddTagsByIcon(node.Tags, pointOfInterest.Icon);
            RemoveEmptyTags(node.Tags);
            var id = await osmGateway.CreateElement(changesetId, node);

            node.Id = long.Parse(id);
            await osmGateway.CloseChangeset(changesetId);

            var feature = await UpdateElasticSearch(node, pointOfInterest.Title);

            return(await FeatureToExtendedPoi(feature, language));
        }
        public void GetTraces_ShouldGetThemFromOsm()
        {
            _controller.SetupIdentity();
            var osmGateWay = Substitute.For <IOsmGateway>();

            _httpGatewayFactory.CreateOsmGateway(Arg.Any <TokenAndSecret>()).Returns(osmGateWay);

            _controller.GetTraces().Wait();

            osmGateWay.Received(1).GetTraces();
        }
示例#4
0
        public ClaimsPrincipal ValidateToken(string securityToken, TokenValidationParameters validationParameters, out SecurityToken validatedToken)
        {
            var token          = securityToken.Split(';').First().Trim('"');
            var tokenSecret    = securityToken.Split(';').Last().Trim('"');
            var tokenAndSecret = new TokenAndSecret(token, tokenSecret);
            var userId         = _cache.ReverseGet(tokenAndSecret);

            if (string.IsNullOrEmpty(userId))
            {
                var osmGateway = _httpGatewayFactory.CreateOsmGateway(tokenAndSecret);
                var user       = osmGateway.GetUser().Result;
                userId = user.Id.ToString();
                _logger.LogInformation("User " + userId + " had just logged in");
                _cache.Add(userId, tokenAndSecret);
            }
            validatedToken = new JwtSecurityToken();
            if (string.IsNullOrWhiteSpace(userId))
            {
                throw new ArgumentException("Invalid user id", nameof(securityToken));
            }
            var identity = new ClaimsIdentity("Osm");

            identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId));
            identity.AddClaim(new Claim(ClaimTypes.Name, userId));

            return(new ClaimsPrincipal(identity));
        }
示例#5
0
        public Task <User> GetUserDetails()
        {
            var token   = _cache.Get(User.Identity.Name);
            var gateway = _httpGatewayFactory.CreateOsmGateway(token);

            return(gateway.GetUser());
        }
示例#6
0
        private IOsmGateway SetupHttpFactory()
        {
            var gateway = Substitute.For <IOsmGateway>();

            _httpGatewayFactory.CreateOsmGateway(Arg.Any <TokenAndSecret>()).Returns(gateway);
            return(gateway);
        }
示例#7
0
        private IOsmGateway SetupOsmGateway(string changesetId)
        {
            var osmGateway = Substitute.For <IOsmGateway>();

            osmGateway.CreateChangeset(Arg.Any <string>()).Returns(changesetId);
            _httpGatewayFactory.CreateOsmGateway(null).Returns(osmGateway);
            return(osmGateway);
        }
示例#8
0
        private IOsmGateway SetupOsmGateway(string changesetId)
        {
            var osmGateway = Substitute.For <IOsmGateway>();
            var nodeId     = 10;

            osmGateway.CreateChangeset(Arg.Any <string>()).Returns(changesetId);
            osmGateway.CreateElement(changesetId, Arg.Any <Node>()).Returns(x => Task.Run(() => (++nodeId).ToString()));
            _httpGatewayFactory.CreateOsmGateway(null).Returns(osmGateway);
            return(osmGateway);
        }
示例#9
0
        public void PostUploadGpsTrace_UploadFile_ShouldSendItToOsmGateway()
        {
            var file = Substitute.For <IFormFile>();

            file.FileName.Returns("SomeFile.gpx");
            var gateway = Substitute.For <IOsmGateway>();

            _httpGatewayFactory.CreateOsmGateway(Arg.Any <TokenAndSecret>()).Returns(gateway);
            _controller.SetupIdentity();

            _controller.PostUploadGpsTrace(file).Wait();

            gateway.Received(1).CreateTrace(Arg.Any <string>(), Arg.Any <MemoryStream>());
        }
 /// <summary>
 /// Service's constructor
 /// </summary>
 /// <param name="factory"></param>
 /// <param name="elasticSearchGateway"></param>
 /// <param name="osmGeoJsonPreprocessorExecutor"></param>
 /// <param name="tagsHelper"></param>
 /// <param name="osmRepository"></param>
 /// <param name="adapters"></param>
 /// <param name="logger"></param>
 public OsmElasticSearchUpdaterService(IHttpGatewayFactory factory,
                                       IElasticSearchGateway elasticSearchGateway,
                                       IOsmGeoJsonPreprocessorExecutor osmGeoJsonPreprocessorExecutor,
                                       ITagsHelper tagsHelper, IOsmRepository osmRepository,
                                       IEnumerable <IPointsOfInterestAdapter> adapters,
                                       ILogger logger)
 {
     _elasticSearchGateway           = elasticSearchGateway;
     _osmGeoJsonPreprocessorExecutor = osmGeoJsonPreprocessorExecutor;
     _tagsHelper    = tagsHelper;
     _osmRepository = osmRepository;
     _adapters      = adapters;
     _logger        = logger;
     _osmGateway    = factory.CreateOsmGateway(new TokenAndSecret("", ""));
 }
示例#11
0
        public async Task <IActionResult> UploadPointOfInterest([FromBody] PointOfInterestExtended pointOfInterest,
                                                                [FromQuery] string language)
        {
            if (!pointOfInterest.Source.Equals(Sources.OSM, StringComparison.InvariantCultureIgnoreCase))
            {
                return(BadRequest("OSM is the only supported source for this action..."));
            }
            var tokenAndSecret = _cache.Get(User.Identity.Name);
            var osmGateway     = _httpGatewayFactory.CreateOsmGateway(tokenAndSecret);
            var user           = await osmGateway.GetUser();

            var imageUrls = pointOfInterest.ImagesUrls ?? new string[0];

            for (var urlIndex = 0; urlIndex < imageUrls.Length; urlIndex++)
            {
                var url      = imageUrls[urlIndex];
                var fileName = string.IsNullOrWhiteSpace(pointOfInterest.Title)
                    ? pointOfInterest.Icon.Replace("icon-", "")
                    : pointOfInterest.Title;
                var file = _base64ImageConverter.ConvertToFile(url, fileName);
                if (file == null)
                {
                    continue;
                }
                using (var memoryStream = new MemoryStream(file.Content))
                {
                    var imageName = await _wikimediaCommonGateway.UploadImage(pointOfInterest.Title,
                                                                              pointOfInterest.Description, user.DisplayName, file.FileName, memoryStream,
                                                                              new Coordinate().FromLatLng(pointOfInterest.Location));

                    url = await _wikimediaCommonGateway.GetImageUrl(imageName);

                    imageUrls[urlIndex] = url;
                }
            }

            if (string.IsNullOrWhiteSpace(pointOfInterest.Id))
            {
                return(Ok(await _pointsOfInterestProvider.AddPointOfInterest(pointOfInterest, tokenAndSecret, language)));
            }
            return(Ok(await _pointsOfInterestProvider.UpdatePointOfInterest(pointOfInterest, tokenAndSecret, language)));
        }
 /// <summary>
 /// Service's constructor
 /// </summary>
 /// <param name="factory"></param>
 /// <param name="elasticSearchGateway"></param>
 /// <param name="osmGeoJsonPreprocessorExecutor"></param>
 /// <param name="tagsHelper"></param>
 /// <param name="osmRepository"></param>
 /// <param name="pointsOfInterestAdapterFactory"></param>
 /// <param name="featuresMergeExecutor"></param>
 /// <param name="latestFileFetcherExecutor"></param>
 /// <param name="graphHopperGateway"></param>
 /// <param name="logger"></param>
 public ElasticSearchUpdaterService(IHttpGatewayFactory factory,
                                    IElasticSearchGateway elasticSearchGateway,
                                    IOsmGeoJsonPreprocessorExecutor osmGeoJsonPreprocessorExecutor,
                                    ITagsHelper tagsHelper, IOsmRepository osmRepository,
                                    IPointsOfInterestAdapterFactory pointsOfInterestAdapterFactory,
                                    IFeaturesMergeExecutor featuresMergeExecutor,
                                    IOsmLatestFileFetcherExecutor latestFileFetcherExecutor,
                                    IGraphHopperGateway graphHopperGateway,
                                    ILogger logger)
 {
     _elasticSearchGateway           = elasticSearchGateway;
     _osmGeoJsonPreprocessorExecutor = osmGeoJsonPreprocessorExecutor;
     _tagsHelper    = tagsHelper;
     _osmRepository = osmRepository;
     _pointsOfInterestAdapterFactory = pointsOfInterestAdapterFactory;
     _logger = logger;
     _featuresMergeExecutor     = featuresMergeExecutor;
     _latestFileFetcherExecutor = latestFileFetcherExecutor;
     _graphHopperGateway        = graphHopperGateway;
     _osmGateway = factory.CreateOsmGateway(new TokenAndSecret("", ""));
 }
示例#13
0
        public Task <List <GpxFile> > GetTraces()
        {
            var gateway = _httpGatewayFactory.CreateOsmGateway(_cache.Get(User.Identity.Name));

            return(gateway.GetTraces());
        }
示例#14
0
        /// <inheritdoc/>
        public async Task Add(LineString line, Dictionary <string, string> tags, TokenAndSecret tokenAndSecret)
        {
            _osmGateway = _httpGatewayFactory.CreateOsmGateway(tokenAndSecret);
            var createdElements = new List <OsmGeo>();
            var modifiedElement = new List <OsmGeo>();
            int generatedId     = -1;
            var newWayNodeIds   = new List <string>();
            var highways        = await GetHighwaysInArea(line);

            var itmHighways     = highways.Select(ToItmLineString).ToList();
            var waysToUpdateIds = new List <long?>();

            for (int coordinateIndex = 0; coordinateIndex < line.Coordinates.Length; coordinateIndex++)
            {
                var coordinate = line.Coordinates[coordinateIndex];
                if (coordinateIndex > 0)
                {
                    var previousCoordinate = line.Coordinates[coordinateIndex - 1];
                    AddIntersectingNodes(previousCoordinate, coordinate, newWayNodeIds, itmHighways, highways);
                }
                var closetHighway = GetClosetHighway(coordinate, itmHighways, highways);
                if (closetHighway == null)
                {
                    // no close highways, adding a new node
                    var node = new Node {
                        Id = generatedId--, Latitude = coordinate.Y, Longitude = coordinate.X
                    };
                    createdElements.Add(node);
                    newWayNodeIds.Add(node.Id.ToString());
                    continue;
                }
                var itmPoint             = GetItmCoordinate(coordinate);
                var closestItmHighway    = itmHighways.First(hw => hw.GetOsmId() == closetHighway.GetOsmId());
                var closestItmPointInWay = closestItmHighway.Coordinates.OrderBy(c => c.Distance(itmPoint.Coordinate)).First();
                var indexOnWay           = closestItmHighway.Coordinates.ToList().IndexOf(closestItmPointInWay);
                var closestNodeId        = ((List <object>)closetHighway.Attributes[FeatureAttributes.OSM_NODES])[indexOnWay].ToString();
                if (!CanAddNewNode(newWayNodeIds, closestNodeId))
                {
                    continue;
                }
                if (closestItmPointInWay.Distance(itmPoint.Coordinate) <= _options.MaxDistanceToExisitngLineForMerge)
                {
                    // close highway, adding the node id from that highway
                    newWayNodeIds.Add(closestNodeId);
                    continue;
                }
                // need to add a new node to existing highway
                var newNode = new Node {
                    Id = generatedId--, Latitude = coordinate.Y, Longitude = coordinate.X
                };
                createdElements.Add(newNode);
                newWayNodeIds.Add(newNode.Id.ToString());
                var indexToInsert = GetIndexToInsert(indexOnWay, closestItmHighway, itmPoint);
                if (modifiedElement.FirstOrDefault(w => w.Id.ToString() == closestItmHighway.GetOsmId()) is Way modifiedWay &&
                    modifiedWay.Nodes[indexToInsert] < 0)
                {
                    // a new node was added to this highway - no reason to add a new one to the same location
                    continue;
                }
                var simpleWay = await AddNewNodeToExistingWay(newNode.Id.ToString(), closestItmHighway.GetOsmId(), indexToInsert);

                modifiedElement.Add(simpleWay);
                waysToUpdateIds.Add(simpleWay.Id);
            }
            var newWay = CreateWay(newWayNodeIds, tags, generatedId--);

            createdElements.Add(newWay);
            waysToUpdateIds.Add(newWay.Id);

            var changes = new OsmChange
            {
                Create = createdElements.ToArray(),
                Modify = modifiedElement.ToArray(),
                Delete = new OsmGeo[0]
            };
            var changesetId = await _osmGateway.CreateChangeset(CreateCommentFromTags(tags));

            try
            {
                var diffResult = await _osmGateway.UploadChangeset(changesetId, changes);

                waysToUpdateIds = waysToUpdateIds.Select(id =>
                {
                    var newIdResult = diffResult.Results.FirstOrDefault(r => r.OldId.Equals(id));
                    return(newIdResult?.NewId ?? id);
                }).ToList();
                await AddWaysToElasticSearch(waysToUpdateIds);
            }
            finally
            {
                await _osmGateway.CloseChangeset(changesetId);
            }
        }
示例#15
0
        /// <inheritdoc/>
        public async Task Add(LineString line, Dictionary <string, string> tags, TokenAndSecret tokenAndSecret)
        {
            _osmGateway = _httpGatewayFactory.CreateOsmGateway(tokenAndSecret);
            var changesetId = await _osmGateway.CreateChangeset(CreateCommentFromTags(tags));

            try
            {
                var nodeIds  = new List <string>();
                var highways = await GetHighwaysInArea(line);

                var itmHighways     = highways.Select(ToItmLineString).ToList();
                var waysToUpdateIds = new List <string>();
                for (int coordinateIndex = 0; coordinateIndex < line.Coordinates.Length; coordinateIndex++)
                {
                    var coordinate = line.Coordinates[coordinateIndex];
                    if (coordinateIndex > 0)
                    {
                        var previousCoordinate = line.Coordinates[coordinateIndex - 1];
                        await AddIntersectingNodes(previousCoordinate, coordinate, nodeIds, itmHighways);
                    }
                    var closestCompleteWay = await GetClosetHighway(coordinate, itmHighways);

                    if (closestCompleteWay == null)
                    {
                        // no close highways, adding a new node
                        nodeIds.Add(await _osmGateway.CreateElement(changesetId, new Node {
                            Id = 0, Latitude = coordinate.Y, Longitude = coordinate.X
                        }));
                        continue;
                    }
                    var itmPoint             = GetItmCoordinate(coordinate);
                    var closestItmHighway    = itmHighways.First(hw => hw.GetOsmId() == closestCompleteWay.Id.ToString());
                    var closestItmPointInWay = closestItmHighway.Coordinates.OrderBy(c => c.Distance(itmPoint.Coordinate)).First();
                    var indexOnWay           = closestItmHighway.Coordinates.ToList().IndexOf(closestItmPointInWay);
                    var closestNodeId        = closestCompleteWay.Nodes[indexOnWay].Id.ToString();
                    if (nodeIds.Any() && nodeIds.Last() == closestNodeId)
                    {
                        continue;
                    }
                    if (closestItmPointInWay.Distance(itmPoint.Coordinate) <= _options.DistanceToExisitngLineMergeThreshold)
                    {
                        // close hihgway, adding the node id from that highway
                        nodeIds.Add(closestNodeId);
                        continue;
                    }
                    // need to add a new node to existing highway
                    var newNodeId = await _osmGateway.CreateElement(changesetId, new Node { Id = 0, Latitude = coordinate.Y, Longitude = coordinate.X });

                    nodeIds.Add(newNodeId);
                    var simpleWay = AddNewNodeToExistingWay(newNodeId, closestCompleteWay, closestItmHighway, indexOnWay, itmPoint);
                    await _osmGateway.UpdateElement(changesetId, simpleWay);

                    waysToUpdateIds.Add(simpleWay.Id.ToString());
                }
                var newWayId = await AddWayToOsm(nodeIds, tags, changesetId);

                waysToUpdateIds.Add(newWayId);
                await AddWaysToElasticSearch(waysToUpdateIds);
            }
            finally
            {
                await _osmGateway.CloseChangeset(changesetId);
            }
        }