using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace DbxNotifier
{
internal sealed class Alert
{
public long Id;
public string Type = "";
public string Title = "";
public string Body = "";
public string Actor = "";
public long TaskId;
public long ProjectId;
public bool IsMention => Type == "mention";
/// 제목 앞 "나를 태그함: " / "작업 배정: " 은 배지로 보여 주므로 뗀다(웹 팝업과 같게).
public string CleanTitle
{
get
{
foreach (string p in new[] { "나를 태그함:", "작업 배정:" })
if (Title.StartsWith(p, StringComparison.Ordinal)) return Title.Substring(p.Length).Trim();
return Title;
}
}
/// 둘째 줄 — "본문 · 보낸 사람 아이디"(웹 팝업과 같게).
public string SubLine
{
get
{
string who = Actor;
int at = who.IndexOf('@');
if (at > 0) who = who.Substring(0, at);
if (who.Length > 0) who = char.ToUpperInvariant(who[0]) + who.Substring(1);
if (Body.Length > 0 && who.Length > 0) return Body + " · " + who;
return Body.Length > 0 ? Body : who;
}
}
// 작업 알림은 공유 링크(/project/t/{id}) — 서버가 지금 권한으로 열 수 있는 프로젝트(연결된 프로젝트 포함)로
// 보낸다. 원 소속 주소로 열면 연결된 프로젝트에서만 읽을 수 있는 사람에게 403 이 났다.
public string Path => TaskId > 0
? "/project/t/" + TaskId
: ProjectId > 0 ? "/project/p/" + ProjectId : "/project/inbox";
}
internal sealed class AlertResult
{
public string Name = "";
public long LatestId;
public List Alerts = new List();
}
internal sealed class ApiException : Exception
{
public readonly int Status;
public ApiException(int status, string message) : base(message) { Status = status; }
}
/// ERP 서버 호출 — HTTPS 로 우리 서버(설정한 주소)만 부른다. 토큰은 Authorization 헤더로만 보낸다.
internal sealed class Api : IDisposable
{
private readonly HttpClient _http;
private static readonly JavaScriptSerializer Json = new JavaScriptSerializer();
public Api()
{
_http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
_http.DefaultRequestHeaders.UserAgent.ParseAdd("DBXNotifier/" + typeof(Api).Assembly.GetName().Version.ToString(3));
}
public void Dispose() => _http.Dispose();
/// 서버 주소 검사 — https 만(개발용 http://localhost·127.0.0.1 예외).
public static string NormalizeServer(string raw)
{
string s = (raw ?? "").Trim().TrimEnd('/');
if (!Uri.TryCreate(s, UriKind.Absolute, out Uri u) || (u.AbsolutePath != "/" && u.AbsolutePath.Length > 0))
throw new ArgumentException("ERP 주소가 올바르지 않습니다. 예: " + Settings.DefaultServer);
bool local = u.Host == "localhost" || u.Host == "127.0.0.1";
if (u.Scheme != Uri.UriSchemeHttps && !(local && u.Scheme == Uri.UriSchemeHttp))
throw new ArgumentException("ERP 주소는 https:// 로 시작해야 합니다.");
return u.GetLeftPart(UriPartial.Authority);
}
private async Task> Send(HttpMethod method, string url, string token, object body)
{
using (var req = new HttpRequestMessage(method, url))
{
if (!string.IsNullOrEmpty(token)) req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
if (body != null) req.Content = new StringContent(Json.Serialize(body), Encoding.UTF8, "application/json");
using (HttpResponseMessage res = await _http.SendAsync(req).ConfigureAwait(false))
{
string text = await res.Content.ReadAsStringAsync().ConfigureAwait(false);
Dictionary d = null;
try { d = Json.Deserialize>(text); } catch { /* HTML 오류 화면 등 */ }
if (!res.IsSuccessStatusCode)
{
string detail = d != null && d.TryGetValue("detail", out var x) ? x as string : null;
throw new ApiException((int)res.StatusCode, detail ?? ("서버 오류 HTTP " + (int)res.StatusCode));
}
return d ?? new Dictionary();
}
}
}
private static string Str(Dictionary d, string key) =>
d.TryGetValue(key, out var v) && v != null ? Convert.ToString(v) : "";
private static long Num(Dictionary d, string key) =>
d.TryGetValue(key, out var v) && v != null ? Convert.ToInt64(v) : 0;
public async Task<(string Code, string Poll, string ApprovePath, int ExpiresIn)> StartLink(string server, string device)
{
var d = await Send(HttpMethod.Post, server + "/project/api/notifier/link/start", null, new { device }).ConfigureAwait(false);
return (Str(d, "code"), Str(d, "poll"), Str(d, "approve_path"), (int)Num(d, "expires_in"));
}
/// 연결 확인 — status: pending | expired | ok(token, email).
public async Task<(string Status, string Token, string Email)> PollLink(string server, string poll)
{
var d = await Send(HttpMethod.Post, server + "/project/api/notifier/link/poll", null, new { poll }).ConfigureAwait(false);
return (Str(d, "status"), Str(d, "token"), Str(d, "email"));
}
public async Task Alerts(string server, string token, long after)
{
var d = await Send(HttpMethod.Get, server + "/project/api/notifier/alerts?after=" + after, token, null).ConfigureAwait(false);
var r = new AlertResult { Name = Str(d, "name"), LatestId = Num(d, "latest_id") };
if (d.TryGetValue("alerts", out var list) && list is IEnumerable items)
{
foreach (object o in items)
{
if (!(o is Dictionary a)) continue;
r.Alerts.Add(new Alert
{
Id = Num(a, "id"),
Type = Str(a, "type"),
Title = Str(a, "title"),
Body = Str(a, "body"),
Actor = Str(a, "actor_email"),
TaskId = Num(a, "task_id"),
ProjectId = Num(a, "project_id"),
});
}
}
return r;
}
public Task MarkRead(string server, string token, long id) =>
Send(HttpMethod.Post, server + "/project/api/notifier/alerts/" + id + "/read", token, new { });
public Task Logout(string server, string token) =>
Send(HttpMethod.Post, server + "/project/api/notifier/logout", token, new { });
}
}