Compare commits

..

No commits in common. "5ca2ad379b9689a757764e50551fb055712d65a1" and "a7982c370365e09526612db77c51e18e46385709" have entirely different histories.

6 changed files with 25 additions and 146 deletions

View File

@ -1,23 +1,15 @@
using System.Text.Json;
namespace AcaMate.Common.Models;
public class APIResponseStatus<T>
{
public Status status { get; set; }
public T? data { get; set; }
public string JsonToString()
{
return JsonSerializer.Serialize(this);
}
public T data { get; set; }
}
public class Status
{
public string code { get; set; }
public string message { get; set; }
}
public static class DefaultResponse
@ -30,7 +22,7 @@ public static class DefaultResponse
// // 외부 초기화 방지
// }
public static APIResponseStatus<string> Success = new APIResponseStatus<string>
public static readonly APIResponseStatus<string> Success = new APIResponseStatus<string>
{
status = new Status()
{
@ -39,7 +31,7 @@ public static class DefaultResponse
}
};
public static APIResponseStatus<string> InvalidInputError = new APIResponseStatus<string>
public static readonly APIResponseStatus<string> InvalidInputError = new APIResponseStatus<string>
{
status = new Status()
{
@ -48,7 +40,7 @@ public static class DefaultResponse
}
};
public static APIResponseStatus<string> NotFoundError = new APIResponseStatus<string>
public static readonly APIResponseStatus<string> NotFoundError = new APIResponseStatus<string>
{
status = new Status()
{
@ -57,9 +49,9 @@ public static class DefaultResponse
}
};
public static APIResponseStatus<string> InternalSeverError = new APIResponseStatus<string>
public static readonly APIResponseStatus<string> InternalSeverError = new APIResponseStatus<string>
{
status = new Status
status = new Status()
{
code = "003",
message = "통신에 오류가 발생하였습니다."
@ -67,7 +59,7 @@ public static class DefaultResponse
};
public static APIResponseStatus<string> UnknownError = new APIResponseStatus<string>
public static readonly APIResponseStatus<string> UnknownError = new APIResponseStatus<string>
{
status = new Status()
{

View File

@ -56,8 +56,7 @@ public class AppController : ControllerBase
string jsonString = JsonSerializer.Serialize(response);
// return Ok(jsonString);
return Ok(response.JsonToString());
return Ok(jsonString);
}
catch (Exception ex)
{

View File

@ -1,4 +1,3 @@
using AcaMate.Common.Models;
using AcaMate.V1.Models;
using Microsoft.AspNetCore.Mvc;
@ -13,58 +12,32 @@ namespace AcaMate.V1.Controllers;
[ApiExplorerSettings(GroupName = "공통")]
public class PushController : ControllerBase
{
private readonly IWebHostEnvironment _env;
public PushController(IWebHostEnvironment env)
{
_env = env;
}
[HttpGet()]
[CustomOperation("푸시 확인", "저장된 양식을 확인 할 수 있다..", "푸시")]
public IActionResult GetPushData()
{
return Ok("SEND");
}
/// <summary>
/// Sends a push notification to the specified device token with the provided payload.
/// </summary>
/// <param name="deviceToken">The device token to send the notification to.</param>
/// <param name="payload">The payload of the push notification.</param>
/// <returns>An IActionResult indicating the result of the operation.</returns>
/// <response code="200">Push notification sent successfully.</response>
/// <response code="400">Invalid input parameters.</response>
/// <response code="500">Internal server error occurred.</response>
/// <response code="999">Service unavailable.</response>
[HttpPost("send")]
[CustomOperation("푸시전송", "저장된 양식으로, 사용자에게 푸시를 전송한다.", "푸시")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(APIResponseStatus<object>))]
public async Task<IActionResult> SendPush(string deviceToken, [FromBody] Payload? payload)
// public async Task<IActionResult> SendPush(string deviceToken, string title, string body, int badge)
public async Task<IActionResult> SendPush(string deviceToken, [FromBody] Payload payload)
{
if (string.IsNullOrWhiteSpace(deviceToken))
{
var inputError = DefaultResponse.InvalidInputError;
inputError.status.message = "Deviece Toekn 오류";
return StatusCode(500,inputError);
}
if (payload == null)
{
var inputError = DefaultResponse.InvalidInputError;
inputError.status.message = "payload 입력 오류";
return StatusCode(500,inputError);
}
string uri = "";
string p12Path = "";
string p12PWPath = "/src/private/appleKeys.json";
// string p12PWPath = "private/appleKeys.json";
string apnsTopic = "me.myds.ipstein.acamate.AcaMate";
string uri = "";
if (_env.IsDevelopment())
{
@ -83,23 +56,7 @@ public class PushController : ControllerBase
var pushService = new ApnsPushService(uri, p12Path, p12PWPath, apnsTopic);
// 푸시 알림 전송
var result = await pushService.SendPushNotificationAsync(deviceToken, payload);
if (result.Success)
{
return Ok(DefaultResponse.Success.JsonToString());
}
else
{
var apnsError = DefaultResponse.InternalSeverError;
apnsError.status.message = $"{result.Message}";
return result.Code switch
{
"002" => StatusCode(002, apnsError),
"003" => StatusCode(003, apnsError),
"999" => StatusCode(999, apnsError)
};
}
await pushService.SendPushNotificationAsync(deviceToken, payload);
return Ok("done");
}
}

View File

@ -1,15 +0,0 @@
using System.Text.Json;
namespace AcaMate.V1.Models;
public class APIResult
{
public bool Success { get; set; }
public string Code { get; set; }
public string Message { get; set; }
public string JsonToString()
{
return JsonSerializer.Serialize(this);
}
}

View File

@ -1,4 +1,3 @@
using System.ComponentModel.DataAnnotations;
using System.Security.Cryptography.X509Certificates;
namespace AcaMate.V1.Models;
@ -21,10 +20,7 @@ public class Aps
sound = "default";
content_available = 1;
}
[Required(ErrorMessage = "필수 입력 누락 (alert)")]
public Alert alert { get; set; }
[Required(ErrorMessage = "필수 입력 누락 (badge")]
public int badge { get; set; } // 앱 아이콘 표시 배지 숫자 설정
public string sound { get; set; } // 사운드 파일 이름 default = "default"
public int content_available { get; set; } // 백그라운드 알림 활성화: 필수 (1)
@ -33,9 +29,7 @@ public class Aps
public class Alert
{
[Required(ErrorMessage = "필수 입력 누락 (title")]
public string title { get; set; } // 제목
[Required(ErrorMessage = "필수 입력 누락 (body)")]
public string body { get; set; } // 내용
public string? subtitle { get; set; } // 부제목 (선택)
}

View File

@ -1,6 +1,5 @@
using System;
using System.Net.Http;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.Json;
@ -23,32 +22,20 @@ public class ApnsPushService
_apnsTopic = apnsTopic ?? throw new ArgumentNullException(nameof(apnsTopic));
}
public async Task<APIResult> SendPushNotificationAsync(string deviceToken, Payload payload)
public async Task SendPushNotificationAsync(string deviceToken, Payload payload)
{
// 존재 안하면 예외 던져 버리는거
if (!File.Exists(_p12PWPath))
{
Console.WriteLine($"File not found: {_p12PWPath}");
return new APIResult
{
Success = false,
Code = "003",
Message = "서버 오류 : p12 PW 파일 확인 필요"
};
}
var jsonPayload = JsonSerializer.Serialize(payload);
var keys = JsonSerializer.Deserialize<Dictionary<string, string>>(File.ReadAllText(_p12PWPath));
var p12Password = keys["Password"];
try
{
var certificate = new X509Certificate2(_p12Path, p12Password);
Console.WriteLine($"Certificate Subject: {certificate.Subject}");
Console.WriteLine($"Certificate Issuer: {certificate.Issuer}");
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(certificate);
handler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12;
@ -69,58 +56,23 @@ public class ApnsPushService
request.Headers.Add("apns-topic", _apnsTopic);
request.Headers.Add("apns-push-type", "alert");
Console.WriteLine($"Send -> Payload: {jsonPayload}");
Console.WriteLine("Sending push notification...");
Console.WriteLine($"Payload: {jsonPayload}");
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
return new APIResult
{
Success = true
};
Console.WriteLine("Push notification sent successfully.");
}
else
{
var errorContent = await response.Content.ReadAsStringAsync();
return new APIResult
{
Success = false,
Code = "003",
Message = $"APN 통신 실패 = {response.StatusCode} : {errorContent}"
};
Console.WriteLine($"Failed. Status Code: {response.StatusCode}, Error: {errorContent}");
}
}
catch (HttpRequestException httpEx)
{
Console.WriteLine($"HttpRequestException: {httpEx.Message}");
return new APIResult
{
Success = false,
Code = "003",
Message = $"통신 실패 : {httpEx.Message}"
};
}
catch (CryptographicException ex)
{
return new APIResult
{
Success = false,
Code = "999",
Message = $"오류 발생 : {ex.Message}"
};
}
catch (Exception ex)
{
return new APIResult
{
Success = false,
Code = "999",
Message = $"오류 발생 : {ex.Message}"
};
Console.WriteLine($"Error sending push notification: {ex.Message}");
}
}
}