Files
dbx-main/desktop/notifier/Api.cs
T
king 89ad338024 fix(project): review fixes — access leaks, open paths, save safety, concurrency
- Subproject tasks via parent /tasks are re-filtered by current access (FULL/READ kept)
- PUT /api/projects/order: every id must be manageable; bad/duplicate ids -> 400, all-or-nothing
- Inbox, web alert popup, PC notifier open tasks via /project/t/{id}; embed=1 survives redirect;
  old /p/{home}?task= redirects READ users to the linked project
- Project page / snapshot / workload include the opened archived or sub project only
- Alerts: DB-side filters + oldest-first paging (no 50-row cut); badges counted without caps;
  my tasks keep every open task (completed capped)
- Meeting results: next-week meeting open, or own meeting open when no next meeting;
  header edits + result checks under row locks (FOR UPDATE / FOR SHARE)
- Inbox panel waits for the task window save (same retry/discard flow) before switching/closing;
  read failures stay unread
- Attachment upload removes only its own file on DB failure
- New project modal: create once, retry only failed member assignments
- update_task / update_project: locked-row validation in one transaction; completion hints from real transition
- Creator added as explicit member when another owner is chosen
- _once lock lifetime managed by refcount (no leak on failure)
- Section default assignee must still be a registered project user; follower add uses can_assign
- Docs (PROJECT_MODULE 6-15, help), tests (DB-less, real PostgreSQL, jsdom, Chrome)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-12 11:08:56 +09:00

167 lines
7.5 KiB
C#

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";
/// <summary>제목 앞 "나를 태그함: " / "작업 배정: " 은 배지로 보여 주므로 뗀다(웹 팝업과 같게).</summary>
public string CleanTitle
{
get
{
foreach (string p in new[] { "나를 태그함:", "작업 배정:" })
if (Title.StartsWith(p, StringComparison.Ordinal)) return Title.Substring(p.Length).Trim();
return Title;
}
}
/// <summary>둘째 줄 — "본문 · 보낸 사람 아이디"(웹 팝업과 같게).</summary>
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<Alert> Alerts = new List<Alert>();
}
internal sealed class ApiException : Exception
{
public readonly int Status;
public ApiException(int status, string message) : base(message) { Status = status; }
}
/// <summary>ERP 서버 호출 — HTTPS 로 우리 서버(설정한 주소)만 부른다. 토큰은 Authorization 헤더로만 보낸다.</summary>
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();
/// <summary>서버 주소 검사 — https 만(개발용 http://localhost·127.0.0.1 예외).</summary>
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<Dictionary<string, object>> 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<string, object> d = null;
try { d = Json.Deserialize<Dictionary<string, object>>(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<string, object>();
}
}
}
private static string Str(Dictionary<string, object> d, string key) =>
d.TryGetValue(key, out var v) && v != null ? Convert.ToString(v) : "";
private static long Num(Dictionary<string, object> 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"));
}
/// <summary>연결 확인 — status: pending | expired | ok(token, email).</summary>
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<AlertResult> 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<string, object> 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 { });
}
}