Skip to content

Commit

Permalink
sync code with SD 2
Browse files Browse the repository at this point in the history
  • Loading branch information
Dhiogo Acioli committed Jul 13, 2024
1 parent 71760d8 commit 5eb99a6
Show file tree
Hide file tree
Showing 98 changed files with 3,364 additions and 3,198 deletions.
7 changes: 6 additions & 1 deletion MM.API/Core/ApiStartup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ namespace MM.API.Core
public static class ApiStartup
{
private static readonly HttpClient _httpClient = new();
private static readonly HttpClient _httpClientPaddle = new();

private static CosmosClient _cosmosClient = default!;

public static HttpClient HttpClient => _httpClient;
public static HttpClient HttpClientPaddle => _httpClientPaddle;
public static CosmosClient CosmosClient => _cosmosClient;

public static void Startup(string conn)
Expand All @@ -18,7 +20,10 @@ public static void Startup(string conn)
SerializerOptions = new CosmosSerializationOptions()
{
PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
}
},

//https://learn.microsoft.com/en-us/azure/cosmos-db/nosql/sdk-connection-modes
//ConnectionMode = ConnectionMode.Gateway // ConnectionMode.Direct is the default
});
}
}
Expand Down
2 changes: 1 addition & 1 deletion MM.API/Core/IsolatedFunctionHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static class IsolatedFunctionHelper

if (model is ProtectedMainDocument prot)
{
prot.Initialize(userId, userId);
prot.Initialize(userId);
}
else if (model is PrivateMainDocument priv)
{
Expand Down
217 changes: 98 additions & 119 deletions MM.API/Functions/CacheFunction.cs

Large diffs are not rendered by default.

31 changes: 22 additions & 9 deletions MM.API/Functions/ExternalFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,37 @@

namespace VerusDate.Api.Function
{
public class ExternalFunction
public class ExternalFunction(IConfiguration config)
{
public string HereApiKey { get; set; }
public string HereApiKey { get; set; } = config.GetValue<string>("Here_ApiKey");
public string GoogleApiKey { get; set; } = config.GetValue<string>("Google_ApiKey");

public ExternalFunction(IConfiguration config)
[Function("GetLocationHere")]
public async Task<HereJson?> GetLocationHere(
[HttpTrigger(AuthorizationLevel.Function, Method.GET, Route = "location/here/{latitude}/{longitude}")] HttpRequestData req,
string latitude, string longitude, CancellationToken cancellationToken)
{
HereApiKey = config.GetValue<string>("Here_ApiKey");
try
{
using var http = new HttpClient();
return await http.Get<HereJson>($"https://browse.search.hereapi.com/v1/browse?at={latitude},{longitude}&lang=en-US&limit=1&apiKey={HereApiKey}", cancellationToken);
}
catch (Exception ex)
{
req.ProcessException(ex);
throw new UnhandledException(ex.BuildException());
}
}

[Function("ExternalGetLocation")]
public async Task<HereJson?> GetLocation(
[HttpTrigger(AuthorizationLevel.Function, Method.GET, Route = "External/GetLocation/{latitude}/{longitude}")] HttpRequestData req,
string latitude, string longitude, CancellationToken cancellationToken)
[Function("GetLocationGoogle")]
public async Task<GoogleJson?> GetLocationGoogle(
[HttpTrigger(AuthorizationLevel.Function, Method.GET, Route = "location/google/{latitude}/{longitude}")] HttpRequestData req,
string latitude, string longitude, CancellationToken cancellationToken)
{
try
{
using var http = new HttpClient();
return await http.Get<HereJson>($"https://browse.search.hereapi.com/v1/browse?at={latitude},{longitude}&lang=en-US&limit=1&apiKey={HereApiKey}", cancellationToken);
return await http.Get<GoogleJson>($"https://maps.googleapis.com/maps/api/geocode/json?latlng={latitude},{longitude}&language=en&key={GoogleApiKey}", cancellationToken);
}
catch (Exception ex)
{
Expand Down
8 changes: 3 additions & 5 deletions MM.API/Functions/InviteFunction.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using MM.API.Repository.Core;
using MM.Shared.Models.Profile;

namespace VerusDate.Api.Function
{
public class InviteFunction
{
private readonly IRepository _repo;
private readonly CosmosRepository _repo;

public InviteFunction(IRepository repo)
public InviteFunction(CosmosRepository repo)
{
_repo = repo;
}
Expand All @@ -23,7 +21,7 @@ public InviteFunction(IRepository repo)
{
var userId = req.GetUserId();

return await _repo.Get<InviteModel>(DocumentType.Invite + ":" + userId, new PartitionKey(userId), cancellationToken);
return await _repo.Get<InviteModel>(DocumentType.Invite, userId, cancellationToken);
}
catch (Exception ex)
{
Expand Down
7 changes: 3 additions & 4 deletions MM.API/Functions/LoginFunction.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using MM.API.Repository.Core;
using MM.Shared.Models.Auth;

namespace MM.API.Functions
{
public class LoginFunction(IRepository repo)
public class LoginFunction(CosmosRepository repo)
{
//[OpenApiOperation("LoginAdd", "Azure (Cosmos DB)")]
//[OpenApiResponseWithBody(HttpStatusCode.OK, "application/json", typeof(void))]
Expand All @@ -20,7 +19,7 @@ public async Task Add(
if (platform.Empty()) platform = "webapp";
var userId = req.GetUserId();
if (string.IsNullOrEmpty(userId)) throw new InvalidOperationException("unauthenticated user");
var login = await repo.Get<ClienteLogin>(DocumentType.Login + ":" + userId, new PartitionKey(userId), cancellationToken);
var login = await repo.Get<ClienteLogin>(DocumentType.Login, userId, cancellationToken);

if (login == null)
{
Expand All @@ -33,7 +32,7 @@ public async Task Add(
{
if (Array.Exists(login.Platforms, a => a == platform))
{
await repo.PatchItem<ClienteLogin>(nameof(DocumentType.Login) + ":" + userId, new PartitionKey(userId),
await repo.PatchItem<ClienteLogin>(DocumentType.Login, userId,
[
PatchOperation.Add("/logins/-", DateTimeOffset.Now),
], cancellationToken);
Expand Down
13 changes: 6 additions & 7 deletions MM.API/Functions/PaddleFunction.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Configuration;
using MM.API.Repository.Core;
using MM.Shared.Models.Auth;
using MM.Shared.Models.Subscription;
using System.Net.Http.Headers;
using System.Net.Http.Json;

namespace MM.API.Functions
{
public class PaddleFunction(IRepository repo, IConfiguration configuration)
public class PaddleFunction(CosmosRepository repo, IConfiguration configuration)
{
[Function("GetSubscription")]
public async Task<RootSubscription?> GetSubscription(
Expand All @@ -22,11 +21,11 @@ public class PaddleFunction(IRepository repo, IConfiguration configuration)
var endpoint = configuration.GetValue<string>("Paddle_Endpoint");
var key = configuration.GetValue<string>("Paddle_Key");

ApiStartup.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);
ApiStartup.HttpClientPaddle.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);

using var request = new HttpRequestMessage(HttpMethod.Get, $"{endpoint}subscriptions/{id}");

var response = await ApiStartup.HttpClient.SendAsync(request, cancellationToken);
var response = await ApiStartup.HttpClientPaddle.SendAsync(request, cancellationToken);

if (!response.IsSuccessStatusCode) throw new NotificationException(response.ReasonPhrase);

Expand All @@ -50,11 +49,11 @@ public class PaddleFunction(IRepository repo, IConfiguration configuration)
var endpoint = configuration.GetValue<string>("Paddle_Endpoint");
var key = configuration.GetValue<string>("Paddle_Key");

ApiStartup.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);
ApiStartup.HttpClientPaddle.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", key);

using var request = new HttpRequestMessage(HttpMethod.Get, $"{endpoint}subscriptions/{id}/update-payment-method-transaction");

var response = await ApiStartup.HttpClient.SendAsync(request, cancellationToken);
var response = await ApiStartup.HttpClientPaddle.SendAsync(request, cancellationToken);

if (!response.IsSuccessStatusCode) throw new NotificationException(response.ReasonPhrase);

Expand All @@ -80,7 +79,7 @@ public async Task PostSubscription(
var body = await req.GetPublicBody<RootEvent>(cancellationToken) ?? throw new NotificationException("body null");
if (body.data == null) throw new NotificationException("body.data null");

var result = await repo.Query<ClientePrincipal>(x => x.ClientePaddle != null && x.ClientePaddle.CustomerId == body.data.customer_id, null, DocumentType.Principal, cancellationToken) ?? throw new NotificationException("ClientePrincipal null");
var result = await repo.Query<ClientePrincipal>(x => x.ClientePaddle != null && x.ClientePaddle.CustomerId == body.data.customer_id, DocumentType.Principal, cancellationToken) ?? throw new NotificationException("ClientePrincipal null");
var client = result.FirstOrDefault() ?? throw new NotificationException("client null");
if (client.ClientePaddle == null) throw new NotificationException("client.ClientePaddle null");

Expand Down
30 changes: 11 additions & 19 deletions MM.API/Functions/PrincipalFunction.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using MM.API.Repository.Core;
using MM.Shared.Models.Auth;

namespace MM.API.Functions
{
public class PrincipalFunction(IRepository repo)
public class PrincipalFunction(CosmosRepository repo)
{
//[OpenApiOperation("PrincipalGet", "Azure (Cosmos DB)")]
//[OpenApiResponseWithBody(HttpStatusCode.OK, "application/json", typeof(ClientePrincipal))]
Expand All @@ -18,7 +16,7 @@ public class PrincipalFunction(IRepository repo)
{
var userId = req.GetUserId();

return await repo.Get<ClientePrincipal>(DocumentType.Principal + ":" + userId, new PartitionKey(userId), cancellationToken);
return await repo.Get<ClientePrincipal>(DocumentType.Principal, userId, cancellationToken);
}
catch (Exception ex)
{
Expand All @@ -35,7 +33,7 @@ public class PrincipalFunction(IRepository repo)
{
var token = req.GetQueryParameters()["token"];

var principal = await repo.Get<ClientePrincipal>(DocumentType.Principal + ":" + token, new PartitionKey(token), cancellationToken);
var principal = await repo.Get<ClientePrincipal>(DocumentType.Principal, token, cancellationToken);
return principal?.Email;
}
catch (Exception ex)
Expand Down Expand Up @@ -72,7 +70,7 @@ public async Task<ClientePrincipal> Paddle(
{
var userId = req.GetUserId();

var Client = await repo.Get<ClientePrincipal>(DocumentType.Principal + ":" + userId, new PartitionKey(userId), cancellationToken) ?? throw new NotificationException("Client null");
var Client = await repo.Get<ClientePrincipal>(DocumentType.Principal, userId, cancellationToken) ?? throw new NotificationException("Client null");
var body = await req.GetBody<ClientePrincipal>(cancellationToken);

Client.ClientePaddle = body.ClientePaddle;
Expand All @@ -94,31 +92,25 @@ public async Task Remove(
{
var userId = req.GetUserId();

var myPrincipal = await repo.Get<ClientePrincipal>(DocumentType.Principal + ":" + userId, new PartitionKey(userId), cancellationToken);
var myPrincipal = await repo.Get<ClientePrincipal>(DocumentType.Principal, userId, cancellationToken);
if (myPrincipal != null) await repo.Delete(myPrincipal, cancellationToken);

//var myProviders = await repo.Get<MyProviders>(DocumentType.MyProvider + ":" + userId, new PartitionKey(userId), cancellationToken);
//var myProviders = await repo.Get<MyProviders>(DocumentType.MyProvider, userId, cancellationToken);
//if (myProviders != null) await repo.Delete(myProviders, cancellationToken);

var myLogins = await repo.Get<ClienteLogin>(DocumentType.Login + ":" + userId, new PartitionKey(userId), cancellationToken);
var myLogins = await repo.Get<ClienteLogin>(DocumentType.Login, userId, cancellationToken);
if (myLogins != null) await repo.Delete(myLogins, cancellationToken);

//var mySuggestions = await repo.Get<MySuggestions>(DocumentType.MySuggestions + ":" + userId, new PartitionKey(userId), cancellationToken);
//var mySuggestions = await repo.Get<MySuggestions>(DocumentType.MySuggestions, userId, cancellationToken);
//if (mySuggestions != null) await repo.Delete(mySuggestions, cancellationToken);

//var myVotes = await repo.Query<TicketVoteModel>(x => x.IdVotedUser == userId, null, DocumentType.TicketVote, cancellationToken);
//foreach (var vote in myVotes)
//{
// if (vote != null) await repo.Delete(vote, cancellationToken);
//}

//var myWatched = await repo.Get<WatchedList>(DocumentType.WatchedList + ":" + userId, new PartitionKey(userId), cancellationToken);
//var myWatched = await repo.Get<WatchedList>(DocumentType.WatchedList, userId, cancellationToken);
//if (myWatched != null) await repo.Delete(myWatched, cancellationToken);

//var myWatching = await repo.Get<WatchingList>(DocumentType.WatchingList + ":" + userId, new PartitionKey(userId), cancellationToken);
//var myWatching = await repo.Get<WatchingList>(DocumentType.WatchingList, userId, cancellationToken);
//if (myWatching != null) await repo.Delete(myWatching, cancellationToken);

//var myWish = await repo.Get<WishList>(DocumentType.WishList + ":" + userId, new PartitionKey(userId), cancellationToken);
//var myWish = await repo.Get<WishList>(DocumentType.WishList, userId, cancellationToken);
//if (myWish != null) await repo.Delete(myWish, cancellationToken);
}
catch (Exception ex)
Expand Down
58 changes: 31 additions & 27 deletions MM.API/Functions/ProfileFunction.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,13 @@
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using MM.API.Repository.Core;
using MM.Shared.Models.Profile;

namespace VerusDate.Api.Function
{
public class ProfileFunction
public class ProfileFunction(CosmosRepository repo)
{
private readonly IRepository _repo;

public ProfileFunction(IRepository repo)
{
_repo = repo;
}
private readonly CosmosRepository _repo = repo;

[Function("ProfileGet")]
public async Task<ProfileModel?> Get(
Expand All @@ -23,7 +17,7 @@ public ProfileFunction(IRepository repo)
{
var userId = req.GetUserId();

return await _repo.Get<ProfileModel>(DocumentType.Profile + ":" + userId, new PartitionKey(userId), cancellationToken);
return await _repo.Get<ProfileModel>(DocumentType.Profile, userId, cancellationToken);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -109,7 +103,7 @@ public async Task<ProfileModel> UpdateLooking(
PatchOperation.Add("/dtUpdate", DateTime.UtcNow)
};

return await _repo.PatchItem<ProfileModel>(DocumentType.Profile + ":" + userId, new PartitionKey(userId), operations, cancellationToken);
return await _repo.PatchItem<ProfileModel>(DocumentType.Profile, userId, operations, cancellationToken);
}
catch (Exception ex)
{
Expand All @@ -118,24 +112,34 @@ public async Task<ProfileModel> UpdateLooking(
}
}

//[Function("ProfileViewUpdatePatner")]
//public async Task<IActionResult> UpdatePatner(
// [HttpTrigger(AuthorizationLevel.Function, Method.PUT, Route = "Profile/UpdatePatner")] HttpRequestData req, CancellationToken cancellationToken)
//{
// try
// {
// var request = await req.BuildRequestCommand<ProfileUpdatePartnerCommand>(source.Token, false);
// request.LoggedUserId = req.GetUserId();
[Function("ProfileViewUpdatePatner")]
public async Task<ProfileModel?> UpdatePatner(
[HttpTrigger(AuthorizationLevel.Function, Method.PUT, Route = "profile/update-partner")] HttpRequestData req, CancellationToken cancellationToken)
{
try
{
//var request = await req.BuildRequestCommand<ProfileUpdatePartnerCommand>(source.Token, false);
//request.LoggedUserId = req.GetUserId();

// var result = await _mediator.Send(request, source.Token);
//var result = await _mediator.Send(request, source.Token);

// return new OkObjectResult(result);
// }
// catch (Exception ex)
// {
// req.ProcessException(ex);
// throw new UnhandledException(ex.BuildException());
// }
//}
//return new OkObjectResult(result);

var id = req.GetQueryParameters()["id"];
var email = req.GetQueryParameters()["email"];
var userId = req.GetUserId();

var obj = await _repo.Get<ProfileModel>(DocumentType.Profile, userId, cancellationToken);

obj?.UpdatePartner(id, email);

return await _repo.Upsert(obj, cancellationToken);
}
catch (Exception ex)
{
req.ProcessException(ex);
throw new UnhandledException(ex.BuildException());
}
}
}
}
4 changes: 2 additions & 2 deletions MM.API/Functions/SendgridFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public async Task EmailUpdate(
{
var Email = await req.GetPublicBody<EmailDocument>(cancellationToken);

await repo.Upsert(Email, cancellationToken);
await repo.UpsertItemAsync(Email, cancellationToken);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -65,7 +65,7 @@ public async Task SendgridInbound(
SenderIp = inboundMail.SenderIp
};

await repo.Upsert(model, cancellationToken);
await repo.CreateItemAsync(model, cancellationToken);
}
catch (Exception ex)
{
Expand Down
Loading

0 comments on commit 5eb99a6

Please sign in to comment.