Beispiel #1
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "DeleteInReachFeedFromCosmos/{userWebId}/{trackId}")] HttpRequest req,
            [CosmosDB(
                 databaseName: "FreeCosmosDB",
                 collectionName: "TrackMe",
                 ConnectionStringSetting = "CosmosDBForFree",
                 PartitionKey = "{userWebId}",
                 Id = "{trackId}"
                 )] KMLInfo kMLInfo,
            [CosmosDB(
                 databaseName: "FreeCosmosDB",
                 collectionName: "TrackMe",
                 ConnectionStringSetting = "CosmosDBForFree",
                 SqlQuery = "SELECT * FROM c WHERE c.groupid = 'user'"
                 )] IEnumerable <InReachUser> inReachUsers,
            [CosmosDB(
                 databaseName: "FreeCosmosDB",
                 collectionName: "TrackMe",
                 ConnectionStringSetting = "CosmosDBForFree"
                 )] DocumentClient documentClient,
            ExecutionContext context)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();
            var StorageContainerConnectionString = config["StorageContainerConnectionString"];
            CloudStorageAccount storageAccount   = CloudStorageAccount.Parse(StorageContainerConnectionString);
            CloudBlobClient     blobClient       = storageAccount.CreateCloudBlobClient();

            HelperKMLParse  helperKMLParse  = new HelperKMLParse();
            ClaimsPrincipal Identities      = req.HttpContext.User;
            var             checkUser       = new HelperCheckUser();
            var             LoggedInUser    = checkUser.LoggedInUser(inReachUsers, Identities);
            var             IsAuthenticated = false;

            if (LoggedInUser.status == Status.ExistingUser)
            {
                IsAuthenticated = true;
            }

            if (IsAuthenticated)
            {
                //selfLink is like this: "dbs/auo6AA==/colls/auo6AOdfluE=/docs/auo6AOdfluEnFwIAAAAAAA==/";
                await documentClient.DeleteDocumentAsync(kMLInfo._self, new RequestOptions { PartitionKey = new PartitionKey(LoggedInUser.userWebId) });

                //delete blobs
                foreach (var blob in helperKMLParse.Blobs)
                {
                    var blobName = $"{kMLInfo.groupid}/{kMLInfo.id}/{blob.BlobName}.kml";
                    await helperKMLParse.RemoveBlobAsync(blobName, blobClient);
                }
            }
            return(new OkObjectResult(IsAuthenticated));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req,
            [CosmosDB(
                 databaseName: "FreeCosmosDB",
                 collectionName: "TrackMe",
                 ConnectionStringSetting = "CosmosDBForFree"
                 )]
            IAsyncCollector <KMLInfo> asyncCollectorKMLInfo,
            [CosmosDB(
                 databaseName: "FreeCosmosDB",
                 collectionName: "TrackMe",
                 ConnectionStringSetting = "CosmosDBForFree",
                 SqlQuery = "SELECT * FROM c WHERE c.groupid = 'user'"
                 )] IEnumerable <InReachUser> inReachUsers,
            ExecutionContext context
            )
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();
            var StorageContainerConnectionString = config["StorageContainerConnectionString"];

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageContainerConnectionString);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();

            ClaimsPrincipal Identities      = req.HttpContext.User;
            var             checkUser       = new HelperCheckUser();
            var             LoggedInUser    = checkUser.LoggedInUser(inReachUsers, Identities);
            var             IsAuthenticated = false;

            if (LoggedInUser.status == Status.ExistingUser)
            {
                IsAuthenticated = true;
            }

            if (IsAuthenticated)
            {
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                if (requestBody != "")
                {
                    var kMLFull = JsonConvert.DeserializeObject <KMLFull>(requestBody);

                    KMLInfo kMLInfo = new KMLInfo()
                    {
                        id                 = kMLFull.id,
                        Title              = kMLFull.Title,
                        d1                 = kMLFull.d1,
                        d2                 = kMLFull.d2,
                        InReachWebAddress  = kMLFull.InReachWebAddress,
                        InReachWebPassword = kMLFull.InReachWebPassword,
                        UserTimezone       = kMLFull.UserTimezone
                    };
                    var blobs = helperKMLParse.Blobs;
                    blobs.ForEach(x => x.BlobValue = "");
                    blobs.First(x => x.BlobName == "plannedtrack").BlobValue = kMLFull.PlannedTrack;

                    //1. replace ö->o ä->a etc
                    //2. first: UrlEncode is removing all weird charactes and spaces
                    //3. second: HttpUtility.UrlEncode is removing some not named weird characters, just in case
                    //4. third: UrlEncode again is removing possible %-marks
                    //setting id field only on initial track creation
                    if (string.IsNullOrEmpty(kMLInfo.id))
                    {
                        string id = RemoveDiacritics(kMLInfo.Title);
                        id         = UrlEncode(HttpUtility.UrlEncode(UrlEncode(id)));
                        kMLInfo.id = id;
                    }
                    kMLInfo.LastPointTimestamp = "";
                    kMLInfo.groupid            = LoggedInUser.userWebId;
                    kMLInfo.IsLongTrack        = false;

                    var      dateD1   = DateTime.Parse(kMLInfo.d1).AddHours(-kMLInfo.UserTimezone);
                    var      dateD2   = DateTime.Parse(kMLInfo.d2).AddDays(1).AddHours(-kMLInfo.UserTimezone);
                    TimeSpan timeSpan = dateD2 - dateD1;
                    //this setting affects of parsing all points (slow) or not. Depending on the duration of the track
                    if (timeSpan.TotalDays > 2)
                    {
                        kMLInfo.IsLongTrack = true;
                    }

                    kMLInfo.d1 = dateD1.ToString("yyyy-MM-ddTHH:mm:ssZ");
                    kMLInfo.d2 = dateD2.ToString("yyyy-MM-ddTHH:mm:ssZ");

                    HelperGetKMLFromGarmin helperGetKMLFromGarmin = new HelperGetKMLFromGarmin();
                    //get feed grom garmin
                    var kmlFeedresult = await helperGetKMLFromGarmin.GetKMLAsync(kMLInfo);

                    //parse and transform the feed and save to database
                    helperKMLParse.ParseKMLFile(kmlFeedresult, kMLInfo, blobs, new List <Emails>(), LoggedInUser);
                    await asyncCollectorKMLInfo.AddAsync(kMLInfo);

                    //save blobs
                    foreach (var blob in blobs)
                    {
                        var blobName = $"{kMLInfo.groupid}/{kMLInfo.id}/{blob.BlobName}.kml";
                        await helperKMLParse.AddToBlobAsync(blobName, blob.BlobValue, blobClient);
                    }
                }
            }
            return(new OkObjectResult(IsAuthenticated));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            [CosmosDB(
                 databaseName: "FreeCosmosDB",
                 collectionName: "TrackMe",
                 ConnectionStringSetting = "CosmosDBForFree",
                 SqlQuery = "SELECT * FROM c WHERE c.groupid = 'user'"
                 )] IEnumerable <InReachUser> inReachUsers,
            [CosmosDB(
                 databaseName: "FreeCosmosDB",
                 collectionName: "TrackMe",
                 ConnectionStringSetting = "CosmosDBForFree"
                 )] IAsyncCollector <InReachUser> asyncCollectorInReachUser,
            [CosmosDB(
                 databaseName: "FreeCosmosDB",
                 collectionName: "TrackMe",
                 ConnectionStringSetting = "CosmosDBForFree"
                 )] DocumentClient documentClient,
            [CosmosDB(
                 databaseName: "FreeCosmosDB",
                 collectionName: "TrackMe",
                 ConnectionStringSetting = "CosmosDBForFree"
                 )]
            IAsyncCollector <KMLInfo> asyncCollectorKMLInfo,
            ExecutionContext context
            )
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();
            var SendEmailFunctionKey             = config["SendEmailInReachFunctionKey"];
            var SendEmailFunctionUrl             = config["SendEmailFunctionUrl"];
            var WebSiteUrl                       = config["WebSiteUrl"];
            var TodayTrackId                     = config["TodayTrackId"];
            var StorageContainerConnectionString = config["StorageContainerConnectionString"];

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageContainerConnectionString);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();

            Uri             collectionUri = UriFactory.CreateDocumentCollectionUri("FreeCosmosDB", "TrackMe");
            ClaimsPrincipal Identities    = req.HttpContext.User;
            var             checkUser     = new HelperCheckUser();
            var             LoggedInUser  = checkUser.LoggedInUser(inReachUsers, Identities);
            var             IsUserExist   = false;

            if (LoggedInUser.status != Status.UserMissing)
            {
                IsUserExist = true;
            }

            if (IsUserExist)
            {
                //this part is for changing of existing user
                string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
                if (requestBody != "")
                {
                    var userDataFromWeb = JsonConvert.DeserializeObject <InReachUser>(requestBody);
                    if (userDataFromWeb.userWebId != LoggedInUser.userWebId)
                    {
                        await ChangePartitionAsync(LoggedInUser.userWebId, userDataFromWeb.userWebId, asyncCollectorKMLInfo, documentClient, collectionUri, blobClient); //change partitionIDs
                    }
                    LoggedInUser.InReachWebAddress  = userDataFromWeb.InReachWebAddress;
                    LoggedInUser.InReachWebPassword = userDataFromWeb.InReachWebPassword;
                    LoggedInUser.userWebId          = userDataFromWeb.userWebId.ToLower();
                    LoggedInUser.Active             = userDataFromWeb.Active;
                    LoggedInUser.UserTimezone       = userDataFromWeb.UserTimezone;
                    await ManageTodayTrack(LoggedInUser, asyncCollectorKMLInfo, documentClient, collectionUri, TodayTrackId, SendEmailFunctionUrl, SendEmailFunctionKey, WebSiteUrl, blobClient);
                }
                await asyncCollectorInReachUser.AddAsync(LoggedInUser);
            }
            return(new OkObjectResult(LoggedInUser));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "GetKMLFeedMetadata/{GroupId}/{id}")] HttpRequest req,
            string GroupId,
            [CosmosDB(
                 databaseName: "FreeCosmosDB",
                 collectionName: "TrackMe",
                 ConnectionStringSetting = "CosmosDBForFree",
                 PartitionKey = "{GroupId}",
                 Id = "{id}"
                 )]
            KMLInfo kMLInfo,
            [CosmosDB(
                 databaseName: "FreeCosmosDB",
                 collectionName: "TrackMe",
                 ConnectionStringSetting = "CosmosDBForFree",
                 SqlQuery = "SELECT * FROM c WHERE c.groupid = 'user'"
                 )] IEnumerable <InReachUser> inReachUsers,
            ExecutionContext context)
        {
            var config = new ConfigurationBuilder()
                         .SetBasePath(context.FunctionAppDirectory)
                         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                         .AddEnvironmentVariables()
                         .Build();
            var StorageContainerConnectionString = config["StorageContainerConnectionString"];

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(StorageContainerConnectionString);
            CloudBlobClient     blobClient     = storageAccount.CreateCloudBlobClient();

            ClaimsPrincipal Identities      = req.HttpContext.User;
            var             checkUser       = new HelperCheckUser();
            var             LoggedInUser    = checkUser.LoggedInUser(inReachUsers, Identities);
            var             IsAuthenticated = false;

            if (LoggedInUser.status == Status.ExistingUser)
            {
                IsAuthenticated = true;
            }

            KMLData kMLData = new KMLData()
            {
                id                 = kMLInfo.id,
                d1                 = kMLInfo.d1,
                d2                 = kMLInfo.d2,
                Title              = kMLInfo.Title,
                InReachWebAddress  = kMLInfo.InReachWebAddress,
                InReachWebPassword = kMLInfo.InReachWebPassword
            };
            var blobName = $"{kMLInfo.groupid}/{kMLInfo.id}/plannedtrack.kml";

            kMLData.PlannedTrack = await helperKMLParse.GetFromBlobAsync(blobName, blobClient);

            if (IsAuthenticated)
            {
                if (GroupId == LoggedInUser.userWebId)
                {
                    return(new OkObjectResult(kMLData));
                }
                else
                {
                    return(new OkObjectResult("Not your track"));
                }
            }
            return(new OkObjectResult(IsAuthenticated));
        }