Spaces:
Sleeping
feat: remove AI assistant, Free/Plus plans, user templates API, security fixes
Browse files- Remove built-in AI (AIController, AIService, Gemini bridge, DeepSeek proxy, Node in Docker)
- Plans: only Free (small creation limits) and Plus (no limits); migrate Pro/Ultra to Plus
- New /api/templates for user templates; old built-in TemplateLibrary removed
- Security: auth + ownership checks on nodes/edges/habits/users/sync, remove anonymous
agent token and public user list, PBKDF2 password hashing with legacy upgrade,
CORS restricted to the web client, change-tier requires auth (Plus upgrade gated
by Payments:AllowFreeUpgrade), Stripe webhook disabled until signature check exists
- Hub only relays to connections that joined the board
- Clear stale SQLite lock files before opening the DB, add /api/health
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Dockerfile +0 -9
- FlowAPI.Application/DTOs/AI/AIDtos.cs +0 -44
- FlowAPI.Application/DTOs/Graph/GraphDtos.cs +0 -10
- FlowAPI.Application/DTOs/Template/TemplateDtos.cs +36 -0
- FlowAPI.Application/DTOs/User/UserDtos.cs +0 -3
- FlowAPI.Application/Interfaces/IAIService.cs +0 -12
- FlowAPI.Application/Interfaces/ICustomTemplateRepository.cs +3 -0
- FlowAPI.Application/Interfaces/IGeminiBridgeManager.cs +0 -9
- FlowAPI.Application/Interfaces/IGraphService.cs +0 -3
- FlowAPI.Application/Interfaces/ITemplateService.cs +16 -0
- FlowAPI.Application/Services/AIService.cs +0 -940
- FlowAPI.Application/Services/GeminiBridgeManager.cs +0 -203
- FlowAPI.Application/Services/GraphService.cs +13 -180
- FlowAPI.Application/Services/HabitService.cs +3 -6
- FlowAPI.Application/Services/Plans.cs +30 -0
- FlowAPI.Application/Services/TemplateLibrary.cs +0 -353
- FlowAPI.Application/Services/TemplateService.cs +126 -0
- FlowAPI.Application/Services/UserService.cs +43 -10
- FlowAPI.Infrastructure/Migrations/20261017120000_MergeTiersIntoPlus.cs +28 -0
- FlowAPI.Infrastructure/Repositories/CustomTemplateRepository.cs +21 -0
- FlowAPI/Controllers/AIController.cs +0 -77
- FlowAPI/Controllers/AchievementsController.cs +0 -1
- FlowAPI/Controllers/AgentCanvasController.cs +0 -32
- FlowAPI/Controllers/EdgesController.cs +28 -6
- FlowAPI/Controllers/GraphsController.cs +0 -51
- FlowAPI/Controllers/HabitsController.cs +13 -6
- FlowAPI/Controllers/HealthController.cs +15 -0
- FlowAPI/Controllers/PaymentsController.cs +41 -31
- FlowAPI/Controllers/SyncController.cs +2 -0
- FlowAPI/Controllers/TaskNodesController.cs +38 -11
- FlowAPI/Controllers/TemplatesController.cs +78 -0
- FlowAPI/Controllers/UsersController.cs +22 -9
- FlowAPI/FlowAPI.csproj +0 -6
- FlowAPI/FreeDeepseekAPI/package.json +0 -6
- FlowAPI/FreeDeepseekAPI/server.js +0 -1400
- FlowAPI/Hubs/BoardHub.cs +14 -8
- FlowAPI/Program.cs +36 -86
- FlowAPI/appsettings.json +0 -7
- FlowAPI/gemini_bridge.py +0 -473
|
@@ -24,17 +24,8 @@ EXPOSE 7860
|
|
| 24 |
# Create persistent data directory for SQLite
|
| 25 |
RUN mkdir -p /data/data
|
| 26 |
|
| 27 |
-
# Install Node.js 20
|
| 28 |
-
RUN apt-get update && apt-get install -y curl && \
|
| 29 |
-
curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
|
| 30 |
-
apt-get install -y nodejs && \
|
| 31 |
-
rm -rf /var/lib/apt/lists/*
|
| 32 |
-
|
| 33 |
# Copy published .NET app
|
| 34 |
COPY --from=build /app/publish .
|
| 35 |
|
| 36 |
-
# Copy FreeDeepseekAPI proxy
|
| 37 |
-
COPY FlowAPI/FreeDeepseekAPI ./FreeDeepseekAPI
|
| 38 |
-
|
| 39 |
# Set entrypoint
|
| 40 |
ENTRYPOINT ["dotnet", "FlowAPI.dll"]
|
|
|
|
| 24 |
# Create persistent data directory for SQLite
|
| 25 |
RUN mkdir -p /data/data
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
# Copy published .NET app
|
| 28 |
COPY --from=build /app/publish .
|
| 29 |
|
|
|
|
|
|
|
|
|
|
| 30 |
# Set entrypoint
|
| 31 |
ENTRYPOINT ["dotnet", "FlowAPI.dll"]
|
|
@@ -1,44 +0,0 @@
|
|
| 1 |
-
using FlowAPI.Application.DTOs.TaskNode;
|
| 2 |
-
using FlowAPI.Application.DTOs.Edge;
|
| 3 |
-
using FlowAPI.Application.DTOs.Graph;
|
| 4 |
-
|
| 5 |
-
namespace FlowAPI.Application.DTOs.AI
|
| 6 |
-
{
|
| 7 |
-
public class GenerateAlternativeRequestDto
|
| 8 |
-
{
|
| 9 |
-
public Guid GraphId { get; set; }
|
| 10 |
-
public Guid FailedNodeId { get; set; }
|
| 11 |
-
}
|
| 12 |
-
|
| 13 |
-
public class AIPathResponseDto
|
| 14 |
-
{
|
| 15 |
-
public List<TaskNodeResponseDto> SuggestedNodes { get; set; } = new();
|
| 16 |
-
public List<EdgeResponseDto> SuggestedEdges { get; set; } = new();
|
| 17 |
-
}
|
| 18 |
-
|
| 19 |
-
public class GenerateGoalGraphRequestDto
|
| 20 |
-
{
|
| 21 |
-
public Guid UserId { get; set; }
|
| 22 |
-
public string Goal { get; set; } = string.Empty;
|
| 23 |
-
}
|
| 24 |
-
|
| 25 |
-
public class AIChatMessageDto
|
| 26 |
-
{
|
| 27 |
-
public string Role { get; set; } = string.Empty; // "user" or "model"
|
| 28 |
-
public string Text { get; set; } = string.Empty;
|
| 29 |
-
}
|
| 30 |
-
|
| 31 |
-
public class AICanvasAssistRequestDto
|
| 32 |
-
{
|
| 33 |
-
public Guid GraphId { get; set; }
|
| 34 |
-
public string UserPrompt { get; set; } = string.Empty;
|
| 35 |
-
public List<AIChatMessageDto> History { get; set; } = new();
|
| 36 |
-
}
|
| 37 |
-
|
| 38 |
-
public class AICanvasAssistResponseDto
|
| 39 |
-
{
|
| 40 |
-
public string Explanation { get; set; } = string.Empty;
|
| 41 |
-
public List<NodeDto> NewNodes { get; set; } = new();
|
| 42 |
-
public List<EdgeDto> NewEdges { get; set; } = new();
|
| 43 |
-
}
|
| 44 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -48,16 +48,6 @@ namespace FlowAPI.Application.DTOs.Graph
|
|
| 48 |
{
|
| 49 |
public string Title { get; set; } = string.Empty;
|
| 50 |
public string? Description { get; set; }
|
| 51 |
-
public string? TemplateKey { get; set; }
|
| 52 |
-
}
|
| 53 |
-
|
| 54 |
-
public class TemplateInfoDto
|
| 55 |
-
{
|
| 56 |
-
public string Key { get; set; } = string.Empty;
|
| 57 |
-
public string Title { get; set; } = string.Empty;
|
| 58 |
-
public string Description { get; set; } = string.Empty;
|
| 59 |
-
public string Icon { get; set; } = string.Empty;
|
| 60 |
-
public string Category { get; set; } = string.Empty;
|
| 61 |
}
|
| 62 |
|
| 63 |
public class UpdateGraphDto
|
|
|
|
| 48 |
{
|
| 49 |
public string Title { get; set; } = string.Empty;
|
| 50 |
public string? Description { get; set; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
}
|
| 52 |
|
| 53 |
public class UpdateGraphDto
|
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
using System;
|
| 2 |
+
|
| 3 |
+
namespace FlowAPI.Application.DTOs.Template
|
| 4 |
+
{
|
| 5 |
+
/// <summary>
|
| 6 |
+
/// A user template. Content is an opaque JSON document produced by the web client:
|
| 7 |
+
/// { "version": 2, "nodes": [...], "edges": [...] } in React Flow format.
|
| 8 |
+
/// </summary>
|
| 9 |
+
public class TemplateDto
|
| 10 |
+
{
|
| 11 |
+
public Guid Id { get; set; }
|
| 12 |
+
public string Title { get; set; } = string.Empty;
|
| 13 |
+
public string Description { get; set; } = string.Empty;
|
| 14 |
+
public string Category { get; set; } = string.Empty;
|
| 15 |
+
public string Icon { get; set; } = string.Empty;
|
| 16 |
+
public string Content { get; set; } = string.Empty;
|
| 17 |
+
public DateTime CreatedAt { get; set; }
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
public class CreateTemplateDto
|
| 21 |
+
{
|
| 22 |
+
public string Title { get; set; } = string.Empty;
|
| 23 |
+
public string? Description { get; set; }
|
| 24 |
+
public string? Category { get; set; }
|
| 25 |
+
public string? Icon { get; set; }
|
| 26 |
+
public string Content { get; set; } = string.Empty;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
public class UpdateTemplateDto
|
| 30 |
+
{
|
| 31 |
+
public string? Title { get; set; }
|
| 32 |
+
public string? Description { get; set; }
|
| 33 |
+
public string? Category { get; set; }
|
| 34 |
+
public string? Icon { get; set; }
|
| 35 |
+
}
|
| 36 |
+
}
|
|
@@ -10,10 +10,8 @@ namespace FlowAPI.Application.DTOs.User
|
|
| 10 |
public class UpdateUserDto
|
| 11 |
{
|
| 12 |
public string? DisplayName { get; set; }
|
| 13 |
-
public bool? IsPremium { get; set; }
|
| 14 |
public string? AvatarUrl { get; set; }
|
| 15 |
public string? Password { get; set; }
|
| 16 |
-
public string? SubscriptionTier { get; set; }
|
| 17 |
}
|
| 18 |
|
| 19 |
public class LoginDto
|
|
@@ -31,7 +29,6 @@ namespace FlowAPI.Application.DTOs.User
|
|
| 31 |
public string? AvatarUrl { get; set; }
|
| 32 |
public DateTime CreatedAt { get; set; }
|
| 33 |
public string SubscriptionTier { get; set; } = "Free";
|
| 34 |
-
public int DailyAiGenerationsCount { get; set; }
|
| 35 |
}
|
| 36 |
|
| 37 |
public class AuthResponseDto
|
|
|
|
| 10 |
public class UpdateUserDto
|
| 11 |
{
|
| 12 |
public string? DisplayName { get; set; }
|
|
|
|
| 13 |
public string? AvatarUrl { get; set; }
|
| 14 |
public string? Password { get; set; }
|
|
|
|
| 15 |
}
|
| 16 |
|
| 17 |
public class LoginDto
|
|
|
|
| 29 |
public string? AvatarUrl { get; set; }
|
| 30 |
public DateTime CreatedAt { get; set; }
|
| 31 |
public string SubscriptionTier { get; set; } = "Free";
|
|
|
|
| 32 |
}
|
| 33 |
|
| 34 |
public class AuthResponseDto
|
|
@@ -1,12 +0,0 @@
|
|
| 1 |
-
using FlowAPI.Application.DTOs.AI;
|
| 2 |
-
using FlowAPI.Application.DTOs.Graph;
|
| 3 |
-
|
| 4 |
-
namespace FlowAPI.Application.Interfaces
|
| 5 |
-
{
|
| 6 |
-
public interface IAIService
|
| 7 |
-
{
|
| 8 |
-
Task<AIPathResponseDto> GenerateAlternativePathAsync(GenerateAlternativeRequestDto request);
|
| 9 |
-
Task<FullGraphResponseDto> GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request);
|
| 10 |
-
Task<AICanvasAssistResponseDto> CanvasAssistAsync(AICanvasAssistRequestDto request);
|
| 11 |
-
}
|
| 12 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -10,5 +10,8 @@ namespace FlowAPI.Application.Interfaces
|
|
| 10 |
Task<CustomTemplate?> GetByIdAsync(Guid id);
|
| 11 |
Task<IEnumerable<CustomTemplate>> GetByUserIdAsync(Guid userId);
|
| 12 |
Task<CustomTemplate> CreateAsync(CustomTemplate template);
|
|
|
|
|
|
|
|
|
|
| 13 |
}
|
| 14 |
}
|
|
|
|
| 10 |
Task<CustomTemplate?> GetByIdAsync(Guid id);
|
| 11 |
Task<IEnumerable<CustomTemplate>> GetByUserIdAsync(Guid userId);
|
| 12 |
Task<CustomTemplate> CreateAsync(CustomTemplate template);
|
| 13 |
+
Task<CustomTemplate> UpdateAsync(CustomTemplate template);
|
| 14 |
+
Task<bool> DeleteAsync(Guid id);
|
| 15 |
+
Task<int> CountByUserIdAsync(Guid userId);
|
| 16 |
}
|
| 17 |
}
|
|
@@ -1,9 +0,0 @@
|
|
| 1 |
-
using System.Threading.Tasks;
|
| 2 |
-
|
| 3 |
-
namespace FlowAPI.Application.Interfaces
|
| 4 |
-
{
|
| 5 |
-
public interface IGeminiBridgeManager
|
| 6 |
-
{
|
| 7 |
-
Task<string> SendPromptAsync(string prompt, bool isNewChat, int timeoutSeconds = 120);
|
| 8 |
-
}
|
| 9 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -15,8 +15,5 @@ namespace FlowAPI.Application.Interfaces
|
|
| 15 |
Task<GraphResponseDto?> ShareGraphAsync(Guid graphId, Guid ownerId, ShareGraphRequestDto dto);
|
| 16 |
Task<IEnumerable<SharedUserResponseDto>> GetSharedUsersAsync(Guid graphId, Guid ownerId);
|
| 17 |
Task<bool> RevokeShareAsync(Guid graphId, Guid ownerId, Guid shareId);
|
| 18 |
-
|
| 19 |
-
Task<FlowAPI.Domain.Entities.CustomTemplate> SaveAsTemplateAsync(Guid graphId, Guid userId, string title, string description);
|
| 20 |
-
Task<IEnumerable<FlowAPI.Domain.Entities.CustomTemplate>> GetCustomTemplatesAsync(Guid userId);
|
| 21 |
}
|
| 22 |
}
|
|
|
|
| 15 |
Task<GraphResponseDto?> ShareGraphAsync(Guid graphId, Guid ownerId, ShareGraphRequestDto dto);
|
| 16 |
Task<IEnumerable<SharedUserResponseDto>> GetSharedUsersAsync(Guid graphId, Guid ownerId);
|
| 17 |
Task<bool> RevokeShareAsync(Guid graphId, Guid ownerId, Guid shareId);
|
|
|
|
|
|
|
|
|
|
| 18 |
}
|
| 19 |
}
|
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
using FlowAPI.Application.DTOs.Template;
|
| 2 |
+
using System;
|
| 3 |
+
using System.Collections.Generic;
|
| 4 |
+
using System.Threading.Tasks;
|
| 5 |
+
|
| 6 |
+
namespace FlowAPI.Application.Interfaces
|
| 7 |
+
{
|
| 8 |
+
public interface ITemplateService
|
| 9 |
+
{
|
| 10 |
+
Task<IEnumerable<TemplateDto>> GetMineAsync(Guid userId);
|
| 11 |
+
Task<TemplateDto?> GetAsync(Guid id, Guid userId);
|
| 12 |
+
Task<TemplateDto> CreateAsync(CreateTemplateDto dto, Guid userId);
|
| 13 |
+
Task<TemplateDto?> UpdateAsync(Guid id, UpdateTemplateDto dto, Guid userId);
|
| 14 |
+
Task<bool> DeleteAsync(Guid id, Guid userId);
|
| 15 |
+
}
|
| 16 |
+
}
|
|
@@ -1,940 +0,0 @@
|
|
| 1 |
-
using System;
|
| 2 |
-
using System.Collections.Generic;
|
| 3 |
-
using System.Diagnostics;
|
| 4 |
-
using System.IO;
|
| 5 |
-
using System.Linq;
|
| 6 |
-
using System.Text;
|
| 7 |
-
using System.Text.Json;
|
| 8 |
-
using System.Text.Encodings.Web;
|
| 9 |
-
using System.Text.Unicode;
|
| 10 |
-
using System.Text.RegularExpressions;
|
| 11 |
-
using System.Threading.Tasks;
|
| 12 |
-
using System.Net.Http;
|
| 13 |
-
using FlowAPI.Application.DTOs.AI;
|
| 14 |
-
using FlowAPI.Application.DTOs.Graph;
|
| 15 |
-
using FlowAPI.Application.DTOs.TaskNode;
|
| 16 |
-
using FlowAPI.Application.DTOs.Edge;
|
| 17 |
-
using FlowAPI.Application.Interfaces;
|
| 18 |
-
using Microsoft.Extensions.Configuration;
|
| 19 |
-
|
| 20 |
-
namespace FlowAPI.Application.Services
|
| 21 |
-
{
|
| 22 |
-
public class AIService : IAIService
|
| 23 |
-
{
|
| 24 |
-
private readonly IUserRepository _userRepo;
|
| 25 |
-
private readonly IGraphRepository _graphRepo;
|
| 26 |
-
private readonly IConfiguration _config;
|
| 27 |
-
private readonly IGraphService _graphService;
|
| 28 |
-
private readonly IGeminiBridgeManager _bridgeManager;
|
| 29 |
-
|
| 30 |
-
private const string GoalResponseSchema = @"
|
| 31 |
-
{
|
| 32 |
-
""type"": ""object"",
|
| 33 |
-
""properties"": {
|
| 34 |
-
""title"": { ""type"": ""string"" },
|
| 35 |
-
""description"": { ""type"": ""string"" },
|
| 36 |
-
""explanation"": { ""type"": ""string"" },
|
| 37 |
-
""nodes"": {
|
| 38 |
-
""type"": ""array"",
|
| 39 |
-
""items"": {
|
| 40 |
-
""type"": ""object"",
|
| 41 |
-
""properties"": {
|
| 42 |
-
""id"": { ""type"": ""string"" },
|
| 43 |
-
""label"": { ""type"": ""string"" },
|
| 44 |
-
""description"": { ""type"": ""string"" },
|
| 45 |
-
""type"": { ""type"": ""string"", ""enum"": [""sketch"", ""condition"", ""habit""] },
|
| 46 |
-
""decision"": { ""type"": ""string"" },
|
| 47 |
-
""dependsOn"": { ""type"": ""string"" },
|
| 48 |
-
""color"": { ""type"": ""string"", ""enum"": [""default"", ""yellow"", ""blue"", ""green"", ""pink"", ""purple"", ""orange"", ""white""] }
|
| 49 |
-
},
|
| 50 |
-
""required"": [""id"", ""label"", ""description"", ""type""]
|
| 51 |
-
}
|
| 52 |
-
},
|
| 53 |
-
""edges"": {
|
| 54 |
-
""type"": ""array"",
|
| 55 |
-
""items"": {
|
| 56 |
-
""type"": ""object"",
|
| 57 |
-
""properties"": {
|
| 58 |
-
""from"": { ""type"": ""string"" },
|
| 59 |
-
""to"": { ""type"": ""string"" },
|
| 60 |
-
""relationship"": { ""type"": ""string"", ""enum"": [""sequential"", ""subgoal""] },
|
| 61 |
-
""condition"": { ""type"": ""string"" }
|
| 62 |
-
},
|
| 63 |
-
""required"": [""from"", ""to"", ""relationship""]
|
| 64 |
-
}
|
| 65 |
-
}
|
| 66 |
-
},
|
| 67 |
-
""required"": [""title"", ""description"", ""explanation"", ""nodes"", ""edges""]
|
| 68 |
-
}";
|
| 69 |
-
|
| 70 |
-
private const string AssistResponseSchema = @"
|
| 71 |
-
{
|
| 72 |
-
""type"": ""object"",
|
| 73 |
-
""properties"": {
|
| 74 |
-
""explanation"": { ""type"": ""string"" },
|
| 75 |
-
""newNodes"": {
|
| 76 |
-
""type"": ""array"",
|
| 77 |
-
""items"": {
|
| 78 |
-
""type"": ""object"",
|
| 79 |
-
""properties"": {
|
| 80 |
-
""id"": { ""type"": ""string"" },
|
| 81 |
-
""label"": { ""type"": ""string"" },
|
| 82 |
-
""description"": { ""type"": ""string"" },
|
| 83 |
-
""type"": { ""type"": ""string"", ""enum"": [""sketch"", ""condition"", ""habit""] },
|
| 84 |
-
""decision"": { ""type"": ""string"" },
|
| 85 |
-
""color"": { ""type"": ""string"", ""enum"": [""default"", ""yellow"", ""blue"", ""green"", ""pink"", ""purple"", ""orange"", ""white""] }
|
| 86 |
-
},
|
| 87 |
-
""required"": [""id"", ""label"", ""description"", ""type""]
|
| 88 |
-
}
|
| 89 |
-
},
|
| 90 |
-
""newEdges"": {
|
| 91 |
-
""type"": ""array"",
|
| 92 |
-
""items"": {
|
| 93 |
-
""type"": ""object"",
|
| 94 |
-
""properties"": {
|
| 95 |
-
""from"": { ""type"": ""string"" },
|
| 96 |
-
""to"": { ""type"": ""string"" },
|
| 97 |
-
""relationship"": { ""type"": ""string"", ""enum"": [""sequential"", ""subgoal""] },
|
| 98 |
-
""condition"": { ""type"": ""string"" }
|
| 99 |
-
},
|
| 100 |
-
""required"": [""from"", ""to"", ""relationship""]
|
| 101 |
-
}
|
| 102 |
-
}
|
| 103 |
-
},
|
| 104 |
-
""required"": [""explanation"", ""newNodes"", ""newEdges""]
|
| 105 |
-
}";
|
| 106 |
-
|
| 107 |
-
public AIService(IUserRepository userRepo, IGraphRepository graphRepo, IConfiguration config, IGraphService graphService, IGeminiBridgeManager bridgeManager)
|
| 108 |
-
{
|
| 109 |
-
_userRepo = userRepo;
|
| 110 |
-
_graphRepo = graphRepo;
|
| 111 |
-
_config = config;
|
| 112 |
-
_graphService = graphService;
|
| 113 |
-
_bridgeManager = bridgeManager;
|
| 114 |
-
}
|
| 115 |
-
|
| 116 |
-
private async Task<string> CallGeminiApiAsync(string prompt, string? systemInstruction = null, string? responseSchemaJson = null)
|
| 117 |
-
{
|
| 118 |
-
var parts = new[] { new { text = prompt } };
|
| 119 |
-
var contents = new[] { new { parts = parts } };
|
| 120 |
-
return await CallGeminiApiAsync(contents, systemInstruction, responseSchemaJson);
|
| 121 |
-
}
|
| 122 |
-
|
| 123 |
-
private async Task<string> CallGeminiApiAsync(object[] contents, string? systemInstruction = null, string? responseSchemaJson = null)
|
| 124 |
-
{
|
| 125 |
-
var deepseekToken = Environment.GetEnvironmentVariable("DEEPSEEK_TOKEN");
|
| 126 |
-
var deepseekCookie = Environment.GetEnvironmentVariable("DEEPSEEK_COOKIE");
|
| 127 |
-
if (!string.IsNullOrEmpty(deepseekToken) && !string.IsNullOrEmpty(deepseekCookie))
|
| 128 |
-
{
|
| 129 |
-
return await CallDeepSeekProxyApiAsync(contents, systemInstruction, responseSchemaJson);
|
| 130 |
-
}
|
| 131 |
-
|
| 132 |
-
var apiKey = _config["Gemini:ApiKey"] ?? Environment.GetEnvironmentVariable("GEMINI_API_KEY");
|
| 133 |
-
if (string.IsNullOrEmpty(apiKey))
|
| 134 |
-
{
|
| 135 |
-
throw new Exception("Gemini API key is not configured. Please add Gemini:ApiKey to appsettings.json or set GEMINI_API_KEY environment variable.");
|
| 136 |
-
}
|
| 137 |
-
|
| 138 |
-
var model = _config["Gemini:Model"] ?? "gemini-2.5-flash";
|
| 139 |
-
if (string.IsNullOrWhiteSpace(model) ||
|
| 140 |
-
model.StartsWith("AIzaSy", StringComparison.OrdinalIgnoreCase) ||
|
| 141 |
-
model.StartsWith("AQ.Ab", StringComparison.OrdinalIgnoreCase) ||
|
| 142 |
-
model.Length > 30 ||
|
| 143 |
-
!model.Contains("gemini", StringComparison.OrdinalIgnoreCase))
|
| 144 |
-
{
|
| 145 |
-
model = "gemini-2.5-flash";
|
| 146 |
-
}
|
| 147 |
-
|
| 148 |
-
if (model.StartsWith("models/"))
|
| 149 |
-
{
|
| 150 |
-
model = model.Substring("models/".Length);
|
| 151 |
-
}
|
| 152 |
-
var url = $"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={apiKey}";
|
| 153 |
-
|
| 154 |
-
object? generationConfig = null;
|
| 155 |
-
if (responseSchemaJson != null)
|
| 156 |
-
{
|
| 157 |
-
generationConfig = new
|
| 158 |
-
{
|
| 159 |
-
responseMimeType = "application/json",
|
| 160 |
-
responseSchema = JsonSerializer.Deserialize<object>(responseSchemaJson)
|
| 161 |
-
};
|
| 162 |
-
}
|
| 163 |
-
else
|
| 164 |
-
{
|
| 165 |
-
generationConfig = new
|
| 166 |
-
{
|
| 167 |
-
responseMimeType = "application/json"
|
| 168 |
-
};
|
| 169 |
-
}
|
| 170 |
-
|
| 171 |
-
object requestBody;
|
| 172 |
-
if (!string.IsNullOrEmpty(systemInstruction))
|
| 173 |
-
{
|
| 174 |
-
requestBody = new
|
| 175 |
-
{
|
| 176 |
-
contents = contents,
|
| 177 |
-
systemInstruction = new { parts = new[] { new { text = systemInstruction } } },
|
| 178 |
-
generationConfig = generationConfig
|
| 179 |
-
};
|
| 180 |
-
}
|
| 181 |
-
else
|
| 182 |
-
{
|
| 183 |
-
requestBody = new
|
| 184 |
-
{
|
| 185 |
-
contents = contents,
|
| 186 |
-
generationConfig = generationConfig
|
| 187 |
-
};
|
| 188 |
-
}
|
| 189 |
-
|
| 190 |
-
using var httpClient = new HttpClient();
|
| 191 |
-
httpClient.Timeout = TimeSpan.FromSeconds(5);
|
| 192 |
-
var jsonPayload = JsonSerializer.Serialize(requestBody);
|
| 193 |
-
|
| 194 |
-
HttpResponseMessage? response = null;
|
| 195 |
-
string responseString = string.Empty;
|
| 196 |
-
|
| 197 |
-
int maxRetries = 3;
|
| 198 |
-
int delayMs = 1500; // 1.5s base delay
|
| 199 |
-
|
| 200 |
-
for (int attempt = 1; attempt <= maxRetries; attempt++)
|
| 201 |
-
{
|
| 202 |
-
using var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
|
| 203 |
-
response = await httpClient.PostAsync(url, content);
|
| 204 |
-
responseString = await response.Content.ReadAsStringAsync();
|
| 205 |
-
|
| 206 |
-
if (response.IsSuccessStatusCode)
|
| 207 |
-
{
|
| 208 |
-
break;
|
| 209 |
-
}
|
| 210 |
-
|
| 211 |
-
int statusCode = (int)response.StatusCode;
|
| 212 |
-
if (attempt < maxRetries && (statusCode == 503 || statusCode == 429 || statusCode == 500))
|
| 213 |
-
{
|
| 214 |
-
await Task.Delay(delayMs * attempt);
|
| 215 |
-
continue;
|
| 216 |
-
}
|
| 217 |
-
|
| 218 |
-
throw new Exception($"Gemini API error (Status {response.StatusCode}): {responseString}");
|
| 219 |
-
}
|
| 220 |
-
|
| 221 |
-
using var doc = JsonDocument.Parse(responseString);
|
| 222 |
-
var textResponse = doc.RootElement
|
| 223 |
-
.GetProperty("candidates")[0]
|
| 224 |
-
.GetProperty("content")
|
| 225 |
-
.GetProperty("parts")[0]
|
| 226 |
-
.GetProperty("text")
|
| 227 |
-
.GetString();
|
| 228 |
-
|
| 229 |
-
if (string.IsNullOrEmpty(textResponse))
|
| 230 |
-
{
|
| 231 |
-
throw new Exception("Empty response received from Gemini API.");
|
| 232 |
-
}
|
| 233 |
-
|
| 234 |
-
return textResponse;
|
| 235 |
-
}
|
| 236 |
-
|
| 237 |
-
public async Task<AIPathResponseDto> GenerateAlternativePathAsync(GenerateAlternativeRequestDto request)
|
| 238 |
-
{
|
| 239 |
-
var graph = await _graphRepo.GetByIdWithDetailsAsync(request.GraphId);
|
| 240 |
-
if (graph == null)
|
| 241 |
-
{
|
| 242 |
-
throw new Exception("Graph not found.");
|
| 243 |
-
}
|
| 244 |
-
await CheckAndIncrementAiGenerationsLimitAsync(graph.UserId);
|
| 245 |
-
|
| 246 |
-
var failedNode = graph.Nodes.FirstOrDefault(n => n.Id == request.FailedNodeId);
|
| 247 |
-
if (failedNode == null)
|
| 248 |
-
{
|
| 249 |
-
throw new Exception("Target node not found.");
|
| 250 |
-
}
|
| 251 |
-
|
| 252 |
-
var prompt = $"В нашей дорожной карте произошел сбой на шаге: \"{failedNode.Label}\" (Описание: \"{failedNode.Description}\").\n" +
|
| 253 |
-
$"Предложи альтернативный обходной путь из 2-3 шагов, чтобы пользователь мог ��родолжить движение к цели.\n" +
|
| 254 |
-
$"Предоставь только новые шаги (NewNodes) и новые связи (NewEdges) для их интеграции.";
|
| 255 |
-
|
| 256 |
-
var systemInstruction = "You are a Roadmap Strategist AI Agent. You design failover alternative paths for failed tasks in a roadmap.";
|
| 257 |
-
var responseJson = await CallGeminiApiAsync(prompt, systemInstruction, AssistResponseSchema);
|
| 258 |
-
responseJson = CleanJson(responseJson);
|
| 259 |
-
|
| 260 |
-
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
| 261 |
-
var rawAssist = JsonSerializer.Deserialize<GeminiAssistResponse>(responseJson, options)
|
| 262 |
-
?? throw new Exception("Failed to deserialize AI alternative path response from Gemini.");
|
| 263 |
-
|
| 264 |
-
var idMap = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
|
| 265 |
-
idMap[failedNode.Id.ToString()] = failedNode.Id;
|
| 266 |
-
|
| 267 |
-
foreach (var node in rawAssist.NewNodes)
|
| 268 |
-
{
|
| 269 |
-
if (!idMap.ContainsKey(node.Id))
|
| 270 |
-
{
|
| 271 |
-
idMap[node.Id] = Guid.NewGuid();
|
| 272 |
-
}
|
| 273 |
-
}
|
| 274 |
-
|
| 275 |
-
var mappedNodes = rawAssist.NewNodes.Select(node => new TaskNodeResponseDto
|
| 276 |
-
{
|
| 277 |
-
Id = idMap[node.Id],
|
| 278 |
-
Label = node.Label,
|
| 279 |
-
PosX = failedNode.PosX + 300,
|
| 280 |
-
PosY = failedNode.PosY + 150,
|
| 281 |
-
State = FlowAPI.Domain.Enums.NodeState.Pending,
|
| 282 |
-
CreatedAt = DateTime.UtcNow
|
| 283 |
-
}).ToList();
|
| 284 |
-
|
| 285 |
-
var mappedEdges = new List<EdgeResponseDto>();
|
| 286 |
-
foreach (var edge in rawAssist.NewEdges)
|
| 287 |
-
{
|
| 288 |
-
if (idMap.TryGetValue(edge.From, out var fromGuid) && idMap.TryGetValue(edge.To, out var toGuid))
|
| 289 |
-
{
|
| 290 |
-
mappedEdges.Add(new EdgeResponseDto
|
| 291 |
-
{
|
| 292 |
-
Id = Guid.NewGuid(),
|
| 293 |
-
FromNodeId = fromGuid,
|
| 294 |
-
ToNodeId = toGuid,
|
| 295 |
-
Condition = edge.Relationship == "subgoal" ? "subgoals-source-right" : "True"
|
| 296 |
-
});
|
| 297 |
-
}
|
| 298 |
-
}
|
| 299 |
-
|
| 300 |
-
return new AIPathResponseDto
|
| 301 |
-
{
|
| 302 |
-
SuggestedNodes = mappedNodes,
|
| 303 |
-
SuggestedEdges = mappedEdges
|
| 304 |
-
};
|
| 305 |
-
}
|
| 306 |
-
|
| 307 |
-
public async Task<FullGraphResponseDto> GenerateGoalGraphAsync(GenerateGoalGraphRequestDto request)
|
| 308 |
-
{
|
| 309 |
-
await CheckAndIncrementAiGenerationsLimitAsync(request.UserId);
|
| 310 |
-
|
| 311 |
-
if (string.IsNullOrWhiteSpace(request.Goal))
|
| 312 |
-
{
|
| 313 |
-
throw new ArgumentException("Goal description cannot be empty.");
|
| 314 |
-
}
|
| 315 |
-
|
| 316 |
-
// 1. Build prompt for Gemini
|
| 317 |
-
var prompt = $"������������ ����� ������� ��������� ����: \"{request.Goal}\". " +
|
| 318 |
-
"������� ��������� ������������� �������� �����.\n" +
|
| 319 |
-
"������� ���������� ������ � ��������� (�������������, ����������� � ������������������):\n" +
|
| 320 |
-
"- � ��� ���� ��� ���� ������:\n" +
|
| 321 |
-
" 1. 'relationship': 'sequential' � ���������������� ���� / ����. ������������ ��� �������� ���������, ��������� ����� ������� ������ ������ ����������, � ����� ��� ���������� ����� ������ ������� ������������ ���� � ������. ��������� ���� ��� ��� �����, ������� ������ �������������� ������� ���� �� ����� (��������: ����������� ���� -> �������� ����� -> ������ ����).\n" +
|
| 322 |
-
" 2. 'relationship': 'subgoal' � ������������ � �������. ������������ ��� ���������� ������� ���� �� ������ ������ �����.\n" +
|
| 323 |
-
"- ������� ����������� ������������:\n" +
|
| 324 |
-
" * ����� ������� ���� �� ����� ������ ����� ���� ���������������. ���� ������� �������, ������ � �� � ����������� ������� (subgoals) � ���������������� ����.\n" +
|
| 325 |
-
" * �� ������������� ����� ������� ��������. ������� �������� ������ (��������: ������� ���� -> ������� A -> ������� A.1 -> ������� A.1.1) � ��� ��������� � ��������������.\n" +
|
| 326 |
-
"- ��� ��������� ������� ������������ � ��������-������������ ����� (����������):\n" +
|
| 327 |
-
" * �� ����� ��� ��������� �������������! ���� ���� ������ ������� ������ ����������� ������ ���� �� ������ (���� ��������������� �����������), �� ������ ������� ������������ ���� ������ 'subgoal' ������ � ����� ������ ����� �������. ��� ����������� ���� ���� ������� �������� ��������������� ���� � ������ ����� 'sequential'.\n" +
|
| 328 |
-
" * ��������� ��������� ����� �������� � �������� ����� 'subgoal' (�����������) ������ ���� ��� ������ ���������� ���� �� ����� � �� ����� ������ ������������ ��� � ����� ������� (��������: ���� ingredients � ���������� ������).\n" +
|
| 329 |
-
" * �� ��������� ������������ �������� ��� ���������������� �����. ������� �� ����������������� ������ / ������. ������� ��������� / ����������� ������ �������� ������������.\n" +
|
| 330 |
-
"- ���������� ������ �������� �����:\n" +
|
| 331 |
-
" * ���� ���� ������� (��������, �������� ���, ������ ������), ������� ���������� ����� �� 3-5 �����.\n" +
|
| 332 |
-
" * ���� ���� ������� (������� �����, �������� ����������������), ���������� ����������� ����� �� 8-15+ �����, ������������ ��� ������ ���� � �� ���������.\n" +
|
| 333 |
-
"- ������� ��� ����� ����� (����������):\n" +
|
| 334 |
-
" * 'sketch' � ����������� ���/���� (��������� � 99% �������). ����� ������� �������� ���, ���� ���� �� �������� ��������, ����� �������� (��������, '�������� 30 �����', '��������� 1 ���') ��� �������� ��������, ������ ����� ��� 'sketch'!\n" +
|
| 335 |
-
" * 'habit' (��������) � ��������� ������ ������ ���� ������������ ����� ������ ���������� ����������, ���������/����������� ������������� �������� ��� ������������ �������� (��������, '������ ���� ���� ����'). ������� �� ��������� ��� ��� ������� ����� ��������!\n" +
|
| 336 |
-
" * 'condition' (�������) � ��������� ������ ������ ��� ����� ���������� ���������, �������� � ������ (��������, '���� X, �� Y, ����� Z'). ������� �� ��������� ��� ��� ������� ����� � ���������� ����������, ���� ��� ��������� ����!\n" +
|
| 337 |
-
"������� ���� ��� �������� �������� �������� (label) � ��������� �������� (description).\n" +
|
| 338 |
-
"� ���� 'explanation' ������ �����, ������, ����������� � ������������� ����� �� ���� ����������� ������-��������. ������� � ������������� �� ������� ������������ �����, ��� ���������� ���������. ������� ����� ������ ������������ �����, ������ ������������ ����� ����������� �����������, � ������ ���������������, � ��� ������ ������������ ������ �� ���������� ����.";
|
| 339 |
-
|
| 340 |
-
// 2. Call Gemini API
|
| 341 |
-
var systemInstruction = "You are a warm, friendly, and highly professional Roadmap Strategist AI Agent. You design roadmaps represented as graphs (nodes and edges). You break down complex goals into hierarchical, deeply nested subgoals (recursive subgoals, where subgoals can have their own subgoals). You connect a parent to multiple parallel subgoals using 'subgoal' relationship ONLY if they can be done in parallel or in any order. If subgoals have chronological dependencies, connect the parent to the first subgoal in the sequence using 'subgoal' and chain the remaining subgoals using 'sequential' relationship. Node types MUST follow these rules: 'sketch' for 99% of regular tasks (including tasks with durations/wait times); 'habit' ONLY for repeating daily/weekly actions meant to form a routine, if explicitly requested; 'condition' ONLY for logical forks/branches with conditions. You adapt the graph size: 3-5 nodes for simple goals, 8-15+ nodes for complex goals. In the 'explanation' field, you write in a warm, direct, and conversational human tone, explaining the plan's logic and giving practical advice.";
|
| 342 |
-
var responseJson = await CallGeminiApiAsync(prompt, systemInstruction, GoalResponseSchema);
|
| 343 |
-
responseJson = CleanJson(responseJson);
|
| 344 |
-
|
| 345 |
-
// 3. Deserialize response
|
| 346 |
-
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
| 347 |
-
var rawGraph = JsonSerializer.Deserialize<GeminiGoalResponse>(responseJson, options)
|
| 348 |
-
?? throw new Exception("Failed to deserialize generated roadmap graph from Gemini.");
|
| 349 |
-
|
| 350 |
-
// 4. Create the Graph record in the database first
|
| 351 |
-
var createDto = new CreateGraphDto
|
| 352 |
-
{
|
| 353 |
-
Title = string.IsNullOrWhiteSpace(rawGraph.Title) ? request.Goal : rawGraph.Title,
|
| 354 |
-
Description = string.IsNullOrWhiteSpace(rawGraph.Description) ? "Дорожная карта, сгенерированная AI Агентом" : rawGraph.Description
|
| 355 |
-
};
|
| 356 |
-
var graphResponse = await _graphService.CreateAsync(createDto, request.UserId);
|
| 357 |
-
var graphId = graphResponse.Id;
|
| 358 |
-
|
| 359 |
-
// 5. Map Gemini string IDs to GUIDs
|
| 360 |
-
var idMap = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
|
| 361 |
-
foreach (var node in rawGraph.Nodes)
|
| 362 |
-
{
|
| 363 |
-
if (!idMap.ContainsKey(node.Id))
|
| 364 |
-
{
|
| 365 |
-
idMap[node.Id] = Guid.NewGuid();
|
| 366 |
-
}
|
| 367 |
-
}
|
| 368 |
-
|
| 369 |
-
// 6. Construct DTO lists
|
| 370 |
-
var mappedNodes = rawGraph.Nodes.Select(node => new NodeDto
|
| 371 |
-
{
|
| 372 |
-
Id = idMap[node.Id],
|
| 373 |
-
Label = node.Label,
|
| 374 |
-
PosX = 0,
|
| 375 |
-
PosY = 0,
|
| 376 |
-
Type = node.Type ?? "sketch",
|
| 377 |
-
State = 0, // Pending
|
| 378 |
-
Decision = node.Decision,
|
| 379 |
-
Description = node.Description,
|
| 380 |
-
Color = node.Color ?? "default",
|
| 381 |
-
IsPinned = false
|
| 382 |
-
}).ToList();
|
| 383 |
-
|
| 384 |
-
var mappedEdges = new List<EdgeDto>();
|
| 385 |
-
foreach (var edge in rawGraph.Edges)
|
| 386 |
-
{
|
| 387 |
-
if (idMap.TryGetValue(edge.From, out var fromGuid) && idMap.TryGetValue(edge.To, out var toGuid))
|
| 388 |
-
{
|
| 389 |
-
mappedEdges.Add(new EdgeDto
|
| 390 |
-
{
|
| 391 |
-
Id = Guid.NewGuid(),
|
| 392 |
-
FromNodeId = fromGuid,
|
| 393 |
-
ToNodeId = toGuid,
|
| 394 |
-
Condition = edge.Relationship == "subgoal"
|
| 395 |
-
? "subgoals-source-right"
|
| 396 |
-
: (string.IsNullOrWhiteSpace(edge.Condition) ? "True" : edge.Condition)
|
| 397 |
-
});
|
| 398 |
-
}
|
| 399 |
-
}
|
| 400 |
-
|
| 401 |
-
// 7. Calculate layouts
|
| 402 |
-
ApplyBeautifulLayout(mappedNodes, mappedEdges);
|
| 403 |
-
|
| 404 |
-
// 8. Save fully generated graph to DB
|
| 405 |
-
var fullGraphDto = new FullGraphResponseDto
|
| 406 |
-
{
|
| 407 |
-
Id = graphId,
|
| 408 |
-
UserId = request.UserId,
|
| 409 |
-
Title = createDto.Title,
|
| 410 |
-
Description = createDto.Description,
|
| 411 |
-
CreatedAt = DateTime.UtcNow,
|
| 412 |
-
Nodes = mappedNodes,
|
| 413 |
-
Edges = mappedEdges
|
| 414 |
-
};
|
| 415 |
-
|
| 416 |
-
await _graphService.SaveFullGraphAsync(graphId, fullGraphDto, request.UserId);
|
| 417 |
-
|
| 418 |
-
// 9. Update roadmap description with explanation from strategist
|
| 419 |
-
var graphEntity = await _graphRepo.GetByIdAsync(graphId);
|
| 420 |
-
if (graphEntity != null)
|
| 421 |
-
{
|
| 422 |
-
graphEntity.Description = rawGraph.Explanation;
|
| 423 |
-
await _graphRepo.UpdateAsync(graphEntity);
|
| 424 |
-
fullGraphDto.Description = rawGraph.Explanation;
|
| 425 |
-
}
|
| 426 |
-
|
| 427 |
-
return fullGraphDto;
|
| 428 |
-
}
|
| 429 |
-
|
| 430 |
-
public async Task<AICanvasAssistResponseDto> CanvasAssistAsync(AICanvasAssistRequestDto request)
|
| 431 |
-
{
|
| 432 |
-
var graph = await _graphRepo.GetByIdWithDetailsAsync(request.GraphId);
|
| 433 |
-
if (graph == null)
|
| 434 |
-
{
|
| 435 |
-
throw new Exception("Graph not found.");
|
| 436 |
-
}
|
| 437 |
-
await CheckAndIncrementAiGenerationsLimitAsync(graph.UserId);
|
| 438 |
-
|
| 439 |
-
// 1. Serialize existing nodes and edges for Gemini context
|
| 440 |
-
var existingNodesText = new StringBuilder();
|
| 441 |
-
existingNodesText.AppendLine("Текущие узлы на доске:");
|
| 442 |
-
foreach (var node in graph.Nodes)
|
| 443 |
-
{
|
| 444 |
-
existingNodesText.AppendLine($"- ID: \"{node.Id}\", Название: \"{node.Label}\", Тип: \"{node.Type}\", Состояние: \"{node.State}\", Описание: \"{node.Description}\"");
|
| 445 |
-
}
|
| 446 |
-
|
| 447 |
-
var existingEdgesText = new StringBuilder();
|
| 448 |
-
existingEdgesText.AppendLine("Текущие связи на доске:");
|
| 449 |
-
foreach (var edge in graph.Edges)
|
| 450 |
-
{
|
| 451 |
-
existingEdgesText.AppendLine($"- От: \"{edge.FromNodeId}\", К: \"{edge.ToNodeId}\", Условие: \"{edge.Condition}\"");
|
| 452 |
-
}
|
| 453 |
-
|
| 454 |
-
// 2. Build the prompt
|
| 455 |
-
var prompt = $"������������ ���������� � ���� (������-��������) �� ��������� ���������� ��� ��������:\n" +
|
| 456 |
-
$"������ ������������: \"{request.UserPrompt}\"\n\n" +
|
| 457 |
-
$"{existingNodesText}\n" +
|
| 458 |
-
$"{existingEdgesText}\n\n" +
|
| 459 |
-
"���� ������:\n" +
|
| 460 |
-
"1. ���� ������ ������������ ������� ���������� ����� ���������, ����������� ��� ���������� �����: ���������� ����� ���� (NewNodes) � ����� ����� (NewEdges). ��� ���� ������ ������ �������� ���������� ������:\n" +
|
| 461 |
-
" - � ��� ���� ��� ���� ������:\n" +
|
| 462 |
-
" * 'relationship': 'sequential' � ���������������� ���� / ����. ������������ ��� �������� ���������, ��������� ����� ������� ������ ������ ����������, � ����� ��� ���������� ����� ������ ������� ������������ ���� � ������. ��������� ���� ��� ��� �����, ������� ������ �������������� ������� ���� �� ����� (��������: ����������� ���� -> �������� ����� -> ������ ����).\n" +
|
| 463 |
-
" * 'relationship': 'subgoal' � ������������ � �������. ������������ ��� ���������� ������� ���� �� ������ ������ �����.\n" +
|
| 464 |
-
" - ������� ����������� ������������:\n" +
|
| 465 |
-
" * ����� ���� �� ����� ������ ����� ���� ���������������! ���� ������� ���� �� ���� �������, �� ������ ������� � �� � ����������� ������� (subgoals) � ���������������� ����.\n" +
|
| 466 |
-
" * �� ������������� ����� ������� ��������. ������� �������� ������ (��������: ������� ���� -> ������� A -> ������� A.1 -> ������� A.1.1) � ��� ��������� � ��������������.\n" +
|
| 467 |
-
" - ��� ��������� ������� ������������ � ��������-������������ ����� (����������):\n" +
|
| 468 |
-
" * �� ����� ��� ��������� �������������! ���� ���� ������ ������� ������ ����������� ������ ���� �� ������ (���� ��������������� �����������), �� ������ ������� ������������ ���� ������ 'subgoal' ������ � ����� ������ ����� �������. ��� ����������� ���� ���� ������� �������� ��������������� ���� � ������ ����� 'sequential'.\n" +
|
| 469 |
-
" * ��������� ��������� ����� �������� � �������� ����� 'subgoal' (�����������) ������ ���� ��� ������ ���������� ���� �� ����� � �� ����� ������ ������������ ��� � ����� �������.\n" +
|
| 470 |
-
" * �� ��������� ������������ �������� ��� ���������������� �����. ������� �� ����������������� ������ / ������. ������� ��������� / ����������� ������ �������� ������������.\n" +
|
| 471 |
-
" - ���������� ������ ����������:\n" +
|
| 472 |
-
" * ���� ������������ ������ �������� ������� �������� ��� ������ ���������, ������ 1-3 ����.\n" +
|
| 473 |
-
" * ���� ������������ ������ ��������� ��� ��������� ������� ����, ������ �����������, ������� � ��������� ���� �� 5-12 �����.\n" +
|
| 474 |
-
" - ������� ��� ����� ����� (����������):\n" +
|
| 475 |
-
" * 'sketch' � ����������� ���/���� (��������� � 99% �������). ����� ������� �������� ���, ���� ���� �� �������� ��������, ����� �������� (��������, '�������� 30 �����', '��������� 1 ���') ��� �������� ��������, ������ ����� ��� 'sketch'!\n" +
|
| 476 |
-
" * 'habit' (��������) � ��������� ������ ������ ���� ������������ ����� ������ ���������� ����������, ���������/����������� ������������� �������� ��� ������������ �������� (��������, '������ ���� ���� ����'). ������� �� ��������� ��� ��� ������� ����� ��������!\n" +
|
| 477 |
-
" * 'condition' (�������) � ��������� ������ ������ ��� ����� ���������� ���������, �������� � ������ (��������, '���� X, �� Y, ����� Z'). ������� �� ��������� ��� ��� ������� ����� � ���������� ����������, ���� ��� ��������� ����!\n" +
|
| 478 |
-
" - �������� ����� ���� � ������������� ��� ���� � ������ � ������� ���������� ��������� ID (��������, new_step_1).\n" +
|
| 479 |
-
"2. ���� ������ ������������ �� ������� ���������� ���������: ������ ������ 'NewNodes' � 'NewEdges' ������� ( [] ).\n" +
|
| 480 |
-
"3. � ���� 'explanation' ������ ������������, ������, ����� � ����������� ����� �� ���� ��������-����������. ������ �� ������� ������������, ����� ������ ��������� ��������� ��� ������� ������ ������������ ����� �� ������� ������������ �����.";
|
| 481 |
-
|
| 482 |
-
var systemInstruction = "You are a warm, friendly, and highly professional Roadmap Strategist AI Agent. You interact with the user, answer their questions, and help them design, extend, or analyze their roadmaps. If changes are needed, you return the new nodes and edges, breaking down complex tasks into hierarchical, deeply nested subgoals (recursive subgoals, where subgoals can have their own subgoals). You connect a parent to multiple parallel subgoals using 'subgoal' relationship ONLY if they can be done in parallel or in any order. If subgoals have chronological dependencies, connect the parent to the first subgoal in the sequence using 'subgoal' and chain the remaining subgoals using 'sequential' relationship. Node types MUST follow these rules: 'sketch' for 99% of regular tasks (including tasks with durations/wait times); 'habit' ONLY for repeating daily/weekly actions meant to form a routine, if explicitly requested; 'condition' ONLY for logical forks/branches with conditions. You never connect subgoals directly to unrelated nodes without a parent node. In the 'explanation' field, you write in a warm, direct, and conversational human tone, explaining your changes or answering user questions.";
|
| 483 |
-
var contentsList = new List<object>();
|
| 484 |
-
if (request.History != null)
|
| 485 |
-
{
|
| 486 |
-
foreach (var msg in request.History)
|
| 487 |
-
{
|
| 488 |
-
var role = msg.Role == "user" ? "user" : "model";
|
| 489 |
-
if (!string.IsNullOrWhiteSpace(msg.Text))
|
| 490 |
-
{
|
| 491 |
-
contentsList.Add(new
|
| 492 |
-
{
|
| 493 |
-
role = role,
|
| 494 |
-
parts = new[] { new { text = msg.Text } }
|
| 495 |
-
});
|
| 496 |
-
}
|
| 497 |
-
}
|
| 498 |
-
}
|
| 499 |
-
|
| 500 |
-
// Add the current user prompt (contains graph context + query)
|
| 501 |
-
contentsList.Add(new
|
| 502 |
-
{
|
| 503 |
-
role = "user",
|
| 504 |
-
parts = new[] { new { text = prompt } }
|
| 505 |
-
});
|
| 506 |
-
|
| 507 |
-
var responseJson = await CallGeminiApiAsync(contentsList.ToArray(), systemInstruction, AssistResponseSchema);
|
| 508 |
-
responseJson = CleanJson(responseJson);
|
| 509 |
-
|
| 510 |
-
// 3. Deserialize Gemini response
|
| 511 |
-
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
| 512 |
-
var rawAssist = JsonSerializer.Deserialize<GeminiAssistResponse>(responseJson, options)
|
| 513 |
-
?? throw new Exception("Failed to deserialize AI Assist response from Gemini.");
|
| 514 |
-
|
| 515 |
-
// 4. Map string IDs to Guids
|
| 516 |
-
var idMap = new Dictionary<string, Guid>(StringComparer.OrdinalIgnoreCase);
|
| 517 |
-
|
| 518 |
-
// Map existing node Guids to themselves so they remain stable
|
| 519 |
-
foreach (var node in graph.Nodes)
|
| 520 |
-
{
|
| 521 |
-
idMap[node.Id.ToString()] = node.Id;
|
| 522 |
-
}
|
| 523 |
-
|
| 524 |
-
// Generate new Guids for new node IDs
|
| 525 |
-
foreach (var node in rawAssist.NewNodes)
|
| 526 |
-
{
|
| 527 |
-
if (!idMap.ContainsKey(node.Id))
|
| 528 |
-
{
|
| 529 |
-
idMap[node.Id] = Guid.NewGuid();
|
| 530 |
-
}
|
| 531 |
-
}
|
| 532 |
-
|
| 533 |
-
// 5. Construct DTO nodes list
|
| 534 |
-
var mappedNewNodes = rawAssist.NewNodes.Select(node => new NodeDto
|
| 535 |
-
{
|
| 536 |
-
Id = idMap[node.Id],
|
| 537 |
-
Label = node.Label,
|
| 538 |
-
PosX = 0,
|
| 539 |
-
PosY = 0,
|
| 540 |
-
Type = node.Type ?? "sketch",
|
| 541 |
-
State = 0, // Pending
|
| 542 |
-
Decision = node.Decision,
|
| 543 |
-
Description = node.Description,
|
| 544 |
-
Color = node.Color ?? "default",
|
| 545 |
-
IsPinned = false
|
| 546 |
-
}).ToList();
|
| 547 |
-
|
| 548 |
-
// 6. Construct DTO edges list
|
| 549 |
-
var mappedNewEdges = new List<EdgeDto>();
|
| 550 |
-
foreach (var edge in rawAssist.NewEdges)
|
| 551 |
-
{
|
| 552 |
-
if (idMap.TryGetValue(edge.From, out var fromGuid) && idMap.TryGetValue(edge.To, out var toGuid))
|
| 553 |
-
{
|
| 554 |
-
mappedNewEdges.Add(new EdgeDto
|
| 555 |
-
{
|
| 556 |
-
Id = Guid.NewGuid(),
|
| 557 |
-
FromNodeId = fromGuid,
|
| 558 |
-
ToNodeId = toGuid,
|
| 559 |
-
Condition = edge.Relationship == "subgoal"
|
| 560 |
-
? "subgoals-source-right"
|
| 561 |
-
: (string.IsNullOrWhiteSpace(edge.Condition) ? "True" : edge.Condition)
|
| 562 |
-
});
|
| 563 |
-
}
|
| 564 |
-
}
|
| 565 |
-
|
| 566 |
-
// 7. Positioning/Layout:
|
| 567 |
-
// Find max PosY of existing nodes to place the new ones below
|
| 568 |
-
double maxPosY = 100;
|
| 569 |
-
if (graph.Nodes.Count > 0)
|
| 570 |
-
{
|
| 571 |
-
maxPosY = graph.Nodes.Max(n => n.PosY);
|
| 572 |
-
}
|
| 573 |
-
|
| 574 |
-
// Run layout engine on the new nodes/edges
|
| 575 |
-
ApplyBeautifulLayout(mappedNewNodes, mappedNewEdges);
|
| 576 |
-
|
| 577 |
-
// Shift all new nodes below the existing nodes
|
| 578 |
-
double shiftY = maxPosY + 250;
|
| 579 |
-
foreach (var node in mappedNewNodes)
|
| 580 |
-
{
|
| 581 |
-
node.PosY += shiftY;
|
| 582 |
-
}
|
| 583 |
-
|
| 584 |
-
return new AICanvasAssistResponseDto
|
| 585 |
-
{
|
| 586 |
-
Explanation = rawAssist.Explanation,
|
| 587 |
-
NewNodes = mappedNewNodes,
|
| 588 |
-
NewEdges = mappedNewEdges
|
| 589 |
-
};
|
| 590 |
-
}
|
| 591 |
-
|
| 592 |
-
private string CleanJson(string text)
|
| 593 |
-
{
|
| 594 |
-
text = text.Trim();
|
| 595 |
-
if (text.StartsWith("```"))
|
| 596 |
-
{
|
| 597 |
-
var lines = text.Split('\n');
|
| 598 |
-
var cleanLines = lines.Where(line => !line.Trim().StartsWith("```")).ToArray();
|
| 599 |
-
text = string.Join("\n", cleanLines).Trim();
|
| 600 |
-
}
|
| 601 |
-
return text;
|
| 602 |
-
}
|
| 603 |
-
|
| 604 |
-
private void ApplyBeautifulLayout(List<NodeDto> nodes, List<EdgeDto> edges)
|
| 605 |
-
{
|
| 606 |
-
if (nodes == null || nodes.Count == 0) return;
|
| 607 |
-
|
| 608 |
-
var inDegree = new Dictionary<Guid, int>();
|
| 609 |
-
var adj = new Dictionary<Guid, List<Guid>>();
|
| 610 |
-
|
| 611 |
-
foreach (var node in nodes)
|
| 612 |
-
{
|
| 613 |
-
inDegree[node.Id] = 0;
|
| 614 |
-
adj[node.Id] = new List<Guid>();
|
| 615 |
-
}
|
| 616 |
-
|
| 617 |
-
foreach (var edge in edges)
|
| 618 |
-
{
|
| 619 |
-
if (inDegree.ContainsKey(edge.ToNodeId) && inDegree.ContainsKey(edge.FromNodeId))
|
| 620 |
-
{
|
| 621 |
-
inDegree[edge.ToNodeId]++;
|
| 622 |
-
adj[edge.FromNodeId].Add(edge.ToNodeId);
|
| 623 |
-
}
|
| 624 |
-
}
|
| 625 |
-
|
| 626 |
-
var layers = new Dictionary<Guid, int>();
|
| 627 |
-
foreach (var node in nodes) { layers[node.Id] = 0; }
|
| 628 |
-
|
| 629 |
-
var queue = new Queue<Guid>();
|
| 630 |
-
foreach (var node in nodes)
|
| 631 |
-
{
|
| 632 |
-
if (inDegree[node.Id] == 0) { queue.Enqueue(node.Id); }
|
| 633 |
-
}
|
| 634 |
-
|
| 635 |
-
if (queue.Count == 0 && nodes.Count > 0)
|
| 636 |
-
{
|
| 637 |
-
queue.Enqueue(nodes[0].Id);
|
| 638 |
-
}
|
| 639 |
-
|
| 640 |
-
var processed = new HashSet<Guid>();
|
| 641 |
-
while (queue.Count > 0)
|
| 642 |
-
{
|
| 643 |
-
var curr = queue.Dequeue();
|
| 644 |
-
processed.Add(curr);
|
| 645 |
-
|
| 646 |
-
int currentLayer = layers[curr];
|
| 647 |
-
foreach (var neighbor in adj[curr])
|
| 648 |
-
{
|
| 649 |
-
layers[neighbor] = Math.Max(layers[neighbor], currentLayer + 1);
|
| 650 |
-
if (!processed.Contains(neighbor) && !queue.Contains(neighbor))
|
| 651 |
-
{
|
| 652 |
-
queue.Enqueue(neighbor);
|
| 653 |
-
}
|
| 654 |
-
}
|
| 655 |
-
}
|
| 656 |
-
|
| 657 |
-
var nodesByLayer = new Dictionary<int, List<NodeDto>>();
|
| 658 |
-
foreach (var node in nodes)
|
| 659 |
-
{
|
| 660 |
-
int layer = layers.ContainsKey(node.Id) ? layers[node.Id] : 0;
|
| 661 |
-
if (!nodesByLayer.ContainsKey(layer)) { nodesByLayer[layer] = new List<NodeDto>(); }
|
| 662 |
-
nodesByLayer[layer].Add(node);
|
| 663 |
-
}
|
| 664 |
-
|
| 665 |
-
double marginY = 100;
|
| 666 |
-
double spacingY = 220;
|
| 667 |
-
double spacingX = 350;
|
| 668 |
-
double centerX = 450;
|
| 669 |
-
|
| 670 |
-
var sortedLayers = nodesByLayer.Keys.OrderBy(l => l).ToList();
|
| 671 |
-
foreach (var layer in sortedLayers)
|
| 672 |
-
{
|
| 673 |
-
var layerNodes = nodesByLayer[layer];
|
| 674 |
-
int count = layerNodes.Count;
|
| 675 |
-
for (int i = 0; i < count; i++)
|
| 676 |
-
{
|
| 677 |
-
var node = layerNodes[i];
|
| 678 |
-
node.PosY = marginY + layer * spacingY;
|
| 679 |
-
node.PosX = centerX + (i - (count - 1) / 2.0) * spacingX;
|
| 680 |
-
}
|
| 681 |
-
}
|
| 682 |
-
}
|
| 683 |
-
|
| 684 |
-
private void ApplyBeautifulLayout(List<FlowAPI.Domain.Entities.TaskNode> nodes, List<FlowAPI.Domain.Entities.Edge> edges)
|
| 685 |
-
{
|
| 686 |
-
if (nodes == null || nodes.Count == 0) return;
|
| 687 |
-
|
| 688 |
-
var inDegree = new Dictionary<Guid, int>();
|
| 689 |
-
var adj = new Dictionary<Guid, List<Guid>>();
|
| 690 |
-
|
| 691 |
-
foreach (var node in nodes)
|
| 692 |
-
{
|
| 693 |
-
inDegree[node.Id] = 0;
|
| 694 |
-
adj[node.Id] = new List<Guid>();
|
| 695 |
-
}
|
| 696 |
-
|
| 697 |
-
foreach (var edge in edges)
|
| 698 |
-
{
|
| 699 |
-
if (inDegree.ContainsKey(edge.ToNodeId) && inDegree.ContainsKey(edge.FromNodeId))
|
| 700 |
-
{
|
| 701 |
-
inDegree[edge.ToNodeId]++;
|
| 702 |
-
adj[edge.FromNodeId].Add(edge.ToNodeId);
|
| 703 |
-
}
|
| 704 |
-
}
|
| 705 |
-
|
| 706 |
-
var layers = new Dictionary<Guid, int>();
|
| 707 |
-
foreach (var node in nodes) { layers[node.Id] = 0; }
|
| 708 |
-
|
| 709 |
-
var queue = new Queue<Guid>();
|
| 710 |
-
foreach (var node in nodes)
|
| 711 |
-
{
|
| 712 |
-
if (inDegree[node.Id] == 0) { queue.Enqueue(node.Id); }
|
| 713 |
-
}
|
| 714 |
-
|
| 715 |
-
if (queue.Count == 0 && nodes.Count > 0)
|
| 716 |
-
{
|
| 717 |
-
queue.Enqueue(nodes[0].Id);
|
| 718 |
-
}
|
| 719 |
-
|
| 720 |
-
var processed = new HashSet<Guid>();
|
| 721 |
-
while (queue.Count > 0)
|
| 722 |
-
{
|
| 723 |
-
var curr = queue.Dequeue();
|
| 724 |
-
processed.Add(curr);
|
| 725 |
-
|
| 726 |
-
int currentLayer = layers[curr];
|
| 727 |
-
foreach (var neighbor in adj[curr])
|
| 728 |
-
{
|
| 729 |
-
layers[neighbor] = Math.Max(layers[neighbor], currentLayer + 1);
|
| 730 |
-
if (!processed.Contains(neighbor) && !queue.Contains(neighbor))
|
| 731 |
-
{
|
| 732 |
-
queue.Enqueue(neighbor);
|
| 733 |
-
}
|
| 734 |
-
}
|
| 735 |
-
}
|
| 736 |
-
|
| 737 |
-
var nodesByLayer = new Dictionary<int, List<FlowAPI.Domain.Entities.TaskNode>>();
|
| 738 |
-
foreach (var node in nodes)
|
| 739 |
-
{
|
| 740 |
-
int layer = layers.ContainsKey(node.Id) ? layers[node.Id] : 0;
|
| 741 |
-
if (!nodesByLayer.ContainsKey(layer)) { nodesByLayer[layer] = new List<FlowAPI.Domain.Entities.TaskNode>(); }
|
| 742 |
-
nodesByLayer[layer].Add(node);
|
| 743 |
-
}
|
| 744 |
-
|
| 745 |
-
double marginY = 100;
|
| 746 |
-
double spacingY = 220;
|
| 747 |
-
double spacingX = 350;
|
| 748 |
-
double centerX = 450;
|
| 749 |
-
|
| 750 |
-
var sortedLayers = nodesByLayer.Keys.OrderBy(l => l).ToList();
|
| 751 |
-
foreach (var layer in sortedLayers)
|
| 752 |
-
{
|
| 753 |
-
var layerNodes = nodesByLayer[layer];
|
| 754 |
-
int count = layerNodes.Count;
|
| 755 |
-
for (int i = 0; i < count; i++)
|
| 756 |
-
{
|
| 757 |
-
var node = layerNodes[i];
|
| 758 |
-
node.PosY = marginY + layer * spacingY;
|
| 759 |
-
node.PosX = centerX + (i - (count - 1) / 2.0) * spacingX;
|
| 760 |
-
}
|
| 761 |
-
}
|
| 762 |
-
}
|
| 763 |
-
|
| 764 |
-
private class GeminiNode
|
| 765 |
-
{
|
| 766 |
-
public string Id { get; set; } = string.Empty;
|
| 767 |
-
public string Label { get; set; } = string.Empty;
|
| 768 |
-
public string Description { get; set; } = string.Empty;
|
| 769 |
-
public string Type { get; set; } = "sketch";
|
| 770 |
-
public string? Decision { get; set; }
|
| 771 |
-
public string? DependsOn { get; set; }
|
| 772 |
-
public string? Color { get; set; }
|
| 773 |
-
}
|
| 774 |
-
|
| 775 |
-
private class GeminiEdge
|
| 776 |
-
{
|
| 777 |
-
public string From { get; set; } = string.Empty;
|
| 778 |
-
public string To { get; set; } = string.Empty;
|
| 779 |
-
public string Relationship { get; set; } = "sequential";
|
| 780 |
-
public string? Condition { get; set; }
|
| 781 |
-
}
|
| 782 |
-
|
| 783 |
-
private class GeminiGoalResponse
|
| 784 |
-
{
|
| 785 |
-
public string Title { get; set; } = string.Empty;
|
| 786 |
-
public string Description { get; set; } = string.Empty;
|
| 787 |
-
public string Explanation { get; set; } = string.Empty;
|
| 788 |
-
public List<GeminiNode> Nodes { get; set; } = new();
|
| 789 |
-
public List<GeminiEdge> Edges { get; set; } = new();
|
| 790 |
-
}
|
| 791 |
-
|
| 792 |
-
private class GeminiAssistResponse
|
| 793 |
-
{
|
| 794 |
-
public string Explanation { get; set; } = string.Empty;
|
| 795 |
-
public List<GeminiNode> NewNodes { get; set; } = new();
|
| 796 |
-
public List<GeminiEdge> NewEdges { get; set; } = new();
|
| 797 |
-
}
|
| 798 |
-
|
| 799 |
-
private async Task<string> CallDeepSeekProxyApiAsync(object[] contents, string? systemInstruction = null, string? responseSchemaJson = null)
|
| 800 |
-
{
|
| 801 |
-
var messages = new List<object>();
|
| 802 |
-
|
| 803 |
-
if (responseSchemaJson != null)
|
| 804 |
-
{
|
| 805 |
-
var schemaInstructions = $"\n\n[STRICT REQUIREMENT] You MUST respond ONLY with a JSON object that strictly adheres to the following JSON schema:\n{responseSchemaJson}\nDo not wrap the JSON in markdown code blocks like ```json ... ```, just output the raw JSON text.";
|
| 806 |
-
if (!string.IsNullOrEmpty(systemInstruction))
|
| 807 |
-
{
|
| 808 |
-
systemInstruction += schemaInstructions;
|
| 809 |
-
}
|
| 810 |
-
else
|
| 811 |
-
{
|
| 812 |
-
systemInstruction = schemaInstructions;
|
| 813 |
-
}
|
| 814 |
-
}
|
| 815 |
-
|
| 816 |
-
if (!string.IsNullOrEmpty(systemInstruction))
|
| 817 |
-
{
|
| 818 |
-
messages.Add(new { role = "system", content = systemInstruction });
|
| 819 |
-
}
|
| 820 |
-
|
| 821 |
-
foreach (var content in contents)
|
| 822 |
-
{
|
| 823 |
-
try
|
| 824 |
-
{
|
| 825 |
-
var json = JsonSerializer.Serialize(content);
|
| 826 |
-
using var doc = JsonDocument.Parse(json);
|
| 827 |
-
var root = doc.RootElement;
|
| 828 |
-
|
| 829 |
-
string role = "user";
|
| 830 |
-
if (root.TryGetProperty("role", out var roleProp))
|
| 831 |
-
{
|
| 832 |
-
var rStr = roleProp.GetString();
|
| 833 |
-
role = rStr == "model" ? "assistant" : (rStr == "system" ? "system" : "user");
|
| 834 |
-
}
|
| 835 |
-
|
| 836 |
-
string text = string.Empty;
|
| 837 |
-
if (root.TryGetProperty("parts", out var partsProp) && partsProp.ValueKind == JsonValueKind.Array && partsProp.GetArrayLength() > 0)
|
| 838 |
-
{
|
| 839 |
-
var firstPart = partsProp[0];
|
| 840 |
-
if (firstPart.TryGetProperty("text", out var textProp))
|
| 841 |
-
{
|
| 842 |
-
text = textProp.GetString() ?? string.Empty;
|
| 843 |
-
}
|
| 844 |
-
}
|
| 845 |
-
|
| 846 |
-
if (!string.IsNullOrEmpty(text))
|
| 847 |
-
{
|
| 848 |
-
messages.Add(new { role = role, content = text });
|
| 849 |
-
}
|
| 850 |
-
}
|
| 851 |
-
catch (Exception ex)
|
| 852 |
-
{
|
| 853 |
-
Console.WriteLine($"[DeepSeekProxy] Error mapping message: {ex.Message}");
|
| 854 |
-
}
|
| 855 |
-
}
|
| 856 |
-
|
| 857 |
-
var requestBody = new
|
| 858 |
-
{
|
| 859 |
-
model = "deepseek-chat",
|
| 860 |
-
messages = messages,
|
| 861 |
-
stream = false
|
| 862 |
-
};
|
| 863 |
-
|
| 864 |
-
using var httpClient = new HttpClient();
|
| 865 |
-
httpClient.Timeout = TimeSpan.FromMinutes(5);
|
| 866 |
-
var jsonPayload = JsonSerializer.Serialize(requestBody);
|
| 867 |
-
|
| 868 |
-
using var requestContent = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
|
| 869 |
-
|
| 870 |
-
HttpResponseMessage? response = null;
|
| 871 |
-
string responseString = string.Empty;
|
| 872 |
-
|
| 873 |
-
int maxRetries = 3;
|
| 874 |
-
int delayMs = 1500;
|
| 875 |
-
|
| 876 |
-
for (int attempt = 1; attempt <= maxRetries; attempt++)
|
| 877 |
-
{
|
| 878 |
-
response = await httpClient.PostAsync("http://localhost:9655/v1/chat/completions", requestContent);
|
| 879 |
-
responseString = await response.Content.ReadAsStringAsync();
|
| 880 |
-
|
| 881 |
-
if (response.IsSuccessStatusCode)
|
| 882 |
-
{
|
| 883 |
-
break;
|
| 884 |
-
}
|
| 885 |
-
|
| 886 |
-
int statusCode = (int)response.StatusCode;
|
| 887 |
-
if (attempt < maxRetries && (statusCode == 503 || statusCode == 429 || statusCode == 500 || statusCode == 502))
|
| 888 |
-
{
|
| 889 |
-
await Task.Delay(delayMs * attempt);
|
| 890 |
-
continue;
|
| 891 |
-
}
|
| 892 |
-
|
| 893 |
-
throw new Exception($"DeepSeek Proxy API error (Status {response.StatusCode}): {responseString}");
|
| 894 |
-
}
|
| 895 |
-
|
| 896 |
-
using var resDoc = JsonDocument.Parse(responseString);
|
| 897 |
-
var textResponse = resDoc.RootElement
|
| 898 |
-
.GetProperty("choices")[0]
|
| 899 |
-
.GetProperty("message")
|
| 900 |
-
.GetProperty("content")
|
| 901 |
-
.GetString();
|
| 902 |
-
|
| 903 |
-
if (string.IsNullOrEmpty(textResponse))
|
| 904 |
-
{
|
| 905 |
-
throw new Exception("Empty response received from DeepSeek Proxy API.");
|
| 906 |
-
}
|
| 907 |
-
|
| 908 |
-
return textResponse;
|
| 909 |
-
}
|
| 910 |
-
|
| 911 |
-
private async Task CheckAndIncrementAiGenerationsLimitAsync(Guid userId)
|
| 912 |
-
{
|
| 913 |
-
var user = await _userRepo.GetByIdAsync(userId);
|
| 914 |
-
if (user == null) throw new Exception("User not found.");
|
| 915 |
-
|
| 916 |
-
var today = DateTime.UtcNow.Date;
|
| 917 |
-
if (user.LastAiGenerationDate.Date != today)
|
| 918 |
-
{
|
| 919 |
-
user.DailyAiGenerationsCount = 0;
|
| 920 |
-
user.LastAiGenerationDate = DateTime.UtcNow;
|
| 921 |
-
}
|
| 922 |
-
|
| 923 |
-
int limit = user.SubscriptionTier switch
|
| 924 |
-
{
|
| 925 |
-
"Free" => 3,
|
| 926 |
-
"Pro" => 200,
|
| 927 |
-
"Ultra" => int.MaxValue,
|
| 928 |
-
_ => 3
|
| 929 |
-
};
|
| 930 |
-
|
| 931 |
-
if (user.DailyAiGenerationsCount >= limit)
|
| 932 |
-
{
|
| 933 |
-
throw new InvalidOperationException($"Daily AI generation limit reached for your tier ({limit} generations per day).");
|
| 934 |
-
}
|
| 935 |
-
|
| 936 |
-
user.DailyAiGenerationsCount++;
|
| 937 |
-
await _userRepo.UpdateAsync(user);
|
| 938 |
-
}
|
| 939 |
-
}
|
| 940 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,203 +0,0 @@
|
|
| 1 |
-
using System;
|
| 2 |
-
using System.Diagnostics;
|
| 3 |
-
using System.IO;
|
| 4 |
-
using System.Text.Json;
|
| 5 |
-
using System.Text.Encodings.Web;
|
| 6 |
-
using System.Text.Unicode;
|
| 7 |
-
using System.Threading;
|
| 8 |
-
using System.Threading.Tasks;
|
| 9 |
-
using FlowAPI.Application.Interfaces;
|
| 10 |
-
using Microsoft.Extensions.Hosting;
|
| 11 |
-
using Microsoft.Extensions.Logging;
|
| 12 |
-
|
| 13 |
-
namespace FlowAPI.Application.Services
|
| 14 |
-
{
|
| 15 |
-
public class GeminiBridgeManager : IGeminiBridgeManager, IDisposable
|
| 16 |
-
{
|
| 17 |
-
private readonly ILogger<GeminiBridgeManager> _logger;
|
| 18 |
-
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
|
| 19 |
-
private Process? _process;
|
| 20 |
-
private bool _isReady = false;
|
| 21 |
-
private readonly JsonSerializerOptions _serializeOptions;
|
| 22 |
-
|
| 23 |
-
public GeminiBridgeManager(ILogger<GeminiBridgeManager> logger, IHostApplicationLifetime appLifetime)
|
| 24 |
-
{
|
| 25 |
-
_logger = logger;
|
| 26 |
-
_serializeOptions = new JsonSerializerOptions
|
| 27 |
-
{
|
| 28 |
-
Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
|
| 29 |
-
};
|
| 30 |
-
|
| 31 |
-
appLifetime.ApplicationStopping.Register(() =>
|
| 32 |
-
{
|
| 33 |
-
_logger.LogInformation("Application stopping, closing Gemini Bridge.");
|
| 34 |
-
Dispose();
|
| 35 |
-
});
|
| 36 |
-
}
|
| 37 |
-
|
| 38 |
-
private async Task EnsureProcessStartedAsync()
|
| 39 |
-
{
|
| 40 |
-
if (_process != null && !_process.HasExited && _isReady)
|
| 41 |
-
return;
|
| 42 |
-
|
| 43 |
-
_logger.LogInformation("Starting persistent Gemini Bridge process...");
|
| 44 |
-
|
| 45 |
-
string scriptPath = Path.Combine(AppContext.BaseDirectory, "gemini_bridge.py");
|
| 46 |
-
if (!File.Exists(scriptPath))
|
| 47 |
-
{
|
| 48 |
-
scriptPath = Path.Combine(Directory.GetCurrentDirectory(), "gemini_bridge.py");
|
| 49 |
-
}
|
| 50 |
-
if (!File.Exists(scriptPath))
|
| 51 |
-
{
|
| 52 |
-
scriptPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "gemini_bridge.py");
|
| 53 |
-
}
|
| 54 |
-
|
| 55 |
-
if (!File.Exists(scriptPath))
|
| 56 |
-
{
|
| 57 |
-
throw new FileNotFoundException("Could not locate gemini_bridge.py in application folders.");
|
| 58 |
-
}
|
| 59 |
-
|
| 60 |
-
var startInfo = new ProcessStartInfo
|
| 61 |
-
{
|
| 62 |
-
FileName = "python",
|
| 63 |
-
Arguments = $"\"{scriptPath}\" --headless",
|
| 64 |
-
RedirectStandardInput = true,
|
| 65 |
-
RedirectStandardOutput = true,
|
| 66 |
-
RedirectStandardError = true,
|
| 67 |
-
UseShellExecute = false,
|
| 68 |
-
CreateNoWindow = true,
|
| 69 |
-
WorkingDirectory = Path.GetDirectoryName(scriptPath)
|
| 70 |
-
};
|
| 71 |
-
|
| 72 |
-
_process = new Process { StartInfo = startInfo };
|
| 73 |
-
_process.Start();
|
| 74 |
-
|
| 75 |
-
// Fire and forget error logging
|
| 76 |
-
_ = Task.Run(async () =>
|
| 77 |
-
{
|
| 78 |
-
while (_process != null && !_process.HasExited && !_process.StandardError.EndOfStream)
|
| 79 |
-
{
|
| 80 |
-
var errLine = await _process.StandardError.ReadLineAsync();
|
| 81 |
-
if (!string.IsNullOrEmpty(errLine))
|
| 82 |
-
{
|
| 83 |
-
_logger.LogWarning($"[GeminiBridge Python]: {errLine}");
|
| 84 |
-
}
|
| 85 |
-
}
|
| 86 |
-
});
|
| 87 |
-
|
| 88 |
-
// Wait for bridge to declare itself "ready"
|
| 89 |
-
var readyTimeout = Task.Delay(TimeSpan.FromSeconds(45));
|
| 90 |
-
var readReadyTask = Task.Run(async () =>
|
| 91 |
-
{
|
| 92 |
-
while (_process != null && !_process.HasExited && !_process.StandardOutput.EndOfStream)
|
| 93 |
-
{
|
| 94 |
-
var l = await _process.StandardOutput.ReadLineAsync();
|
| 95 |
-
if (l != null && l.Contains("\"type\": \"ready\""))
|
| 96 |
-
{
|
| 97 |
-
return true;
|
| 98 |
-
}
|
| 99 |
-
}
|
| 100 |
-
return false;
|
| 101 |
-
});
|
| 102 |
-
|
| 103 |
-
var completedTask = await Task.WhenAny(readReadyTask, readyTimeout);
|
| 104 |
-
if (completedTask == readyTimeout || !await readReadyTask)
|
| 105 |
-
{
|
| 106 |
-
try { _process.Kill(); } catch { }
|
| 107 |
-
_process = null;
|
| 108 |
-
throw new Exception("Timeout or failure waiting for persistent Gemini Browser Bridge to initialize.");
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
_isReady = true;
|
| 112 |
-
_logger.LogInformation("Persistent Gemini Bridge initialized successfully.");
|
| 113 |
-
}
|
| 114 |
-
|
| 115 |
-
public async Task<string> SendPromptAsync(string promptText, bool isNewChat, int timeoutSeconds = 120)
|
| 116 |
-
{
|
| 117 |
-
await _semaphore.WaitAsync();
|
| 118 |
-
try
|
| 119 |
-
{
|
| 120 |
-
await EnsureProcessStartedAsync();
|
| 121 |
-
|
| 122 |
-
if (_process == null || _process.HasExited)
|
| 123 |
-
throw new Exception("Gemini Bridge process is not running.");
|
| 124 |
-
|
| 125 |
-
var promptObj = new
|
| 126 |
-
{
|
| 127 |
-
type = "prompt",
|
| 128 |
-
id = Guid.NewGuid().ToString(),
|
| 129 |
-
new_chat = isNewChat,
|
| 130 |
-
content = promptText
|
| 131 |
-
};
|
| 132 |
-
|
| 133 |
-
string promptRequestJson = JsonSerializer.Serialize(promptObj, _serializeOptions);
|
| 134 |
-
|
| 135 |
-
// Send Prompt to standard input
|
| 136 |
-
await _process.StandardInput.WriteLineAsync(promptRequestJson);
|
| 137 |
-
await _process.StandardInput.FlushAsync();
|
| 138 |
-
|
| 139 |
-
// Await Gemini final response
|
| 140 |
-
var responseTimeout = Task.Delay(TimeSpan.FromSeconds(timeoutSeconds));
|
| 141 |
-
var readResponseTask = Task.Run(async () =>
|
| 142 |
-
{
|
| 143 |
-
while (_process != null && !_process.HasExited && !_process.StandardOutput.EndOfStream)
|
| 144 |
-
{
|
| 145 |
-
var l = await _process.StandardOutput.ReadLineAsync();
|
| 146 |
-
if (l != null && l.Contains("\"type\": \"response\"") && l.Contains($"\"id\": \"{promptObj.id}\""))
|
| 147 |
-
{
|
| 148 |
-
return l;
|
| 149 |
-
}
|
| 150 |
-
}
|
| 151 |
-
return null;
|
| 152 |
-
});
|
| 153 |
-
|
| 154 |
-
var responseCompletedTask = await Task.WhenAny(readResponseTask, responseTimeout);
|
| 155 |
-
if (responseCompletedTask == responseTimeout)
|
| 156 |
-
{
|
| 157 |
-
// If timeout occurs, we should probably kill the process to avoid desync
|
| 158 |
-
try { _process.Kill(); } catch { }
|
| 159 |
-
_process = null;
|
| 160 |
-
_isReady = false;
|
| 161 |
-
throw new Exception("Timeout waiting for AI response from Gemini Bridge.");
|
| 162 |
-
}
|
| 163 |
-
|
| 164 |
-
string? rawResponseJson = await readResponseTask;
|
| 165 |
-
|
| 166 |
-
if (string.IsNullOrEmpty(rawResponseJson))
|
| 167 |
-
{
|
| 168 |
-
throw new Exception("Did not receive a valid response block from the Gemini Bridge.");
|
| 169 |
-
}
|
| 170 |
-
|
| 171 |
-
return rawResponseJson;
|
| 172 |
-
}
|
| 173 |
-
finally
|
| 174 |
-
{
|
| 175 |
-
_semaphore.Release();
|
| 176 |
-
}
|
| 177 |
-
}
|
| 178 |
-
|
| 179 |
-
public void Dispose()
|
| 180 |
-
{
|
| 181 |
-
if (_process != null)
|
| 182 |
-
{
|
| 183 |
-
try
|
| 184 |
-
{
|
| 185 |
-
if (!_process.HasExited)
|
| 186 |
-
{
|
| 187 |
-
_process.StandardInput.WriteLine("{\"type\": \"exit\"}");
|
| 188 |
-
_process.StandardInput.Flush();
|
| 189 |
-
Thread.Sleep(500); // Give it a moment to exit gracefully
|
| 190 |
-
if (!_process.HasExited)
|
| 191 |
-
{
|
| 192 |
-
_process.Kill();
|
| 193 |
-
}
|
| 194 |
-
}
|
| 195 |
-
}
|
| 196 |
-
catch { }
|
| 197 |
-
_process.Dispose();
|
| 198 |
-
_process = null;
|
| 199 |
-
}
|
| 200 |
-
_semaphore.Dispose();
|
| 201 |
-
}
|
| 202 |
-
}
|
| 203 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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GraphRepository _sharedGraphRepo;
|
| 19 |
private readonly IUserRepository _userRepo;
|
| 20 |
-
private readonly ICustomTemplateRepository _customTemplateRepo;
|
| 21 |
|
| 22 |
public GraphService(
|
| 23 |
IGraphRepository repo,
|
|
@@ -25,8 +24,7 @@ namespace FlowAPI.Application.Services
|
|
| 25 |
IEdgeRepository edgeRepo,
|
| 26 |
IAchievementService achievementService,
|
| 27 |
ISharedGraphRepository sharedGraphRepo,
|
| 28 |
-
IUserRepository userRepo
|
| 29 |
-
ICustomTemplateRepository customTemplateRepo)
|
| 30 |
{
|
| 31 |
_repo = repo;
|
| 32 |
_nodeRepo = nodeRepo;
|
|
@@ -34,7 +32,6 @@ namespace FlowAPI.Application.Services
|
|
| 34 |
_achievementService = achievementService;
|
| 35 |
_sharedGraphRepo = sharedGraphRepo;
|
| 36 |
_userRepo = userRepo;
|
| 37 |
-
_customTemplateRepo = customTemplateRepo;
|
| 38 |
}
|
| 39 |
|
| 40 |
public async Task<IEnumerable<GraphResponseDto>> GetAllByUserIdAsync(Guid userId)
|
|
@@ -149,15 +146,12 @@ namespace FlowAPI.Application.Services
|
|
| 149 |
var user = await _userRepo.GetByIdAsync(currentUserId);
|
| 150 |
if (user == null) throw new Exception("User not found.");
|
| 151 |
|
| 152 |
-
|
| 153 |
-
bool isFree = string.IsNullOrEmpty(tier) || tier == "Free";
|
| 154 |
-
|
| 155 |
-
if (isFree)
|
| 156 |
{
|
| 157 |
var ownedGraphsCount = (await _repo.GetAllByUserIdAsync(currentUserId)).Count();
|
| 158 |
-
if (ownedGraphsCount >=
|
| 159 |
{
|
| 160 |
-
throw new InvalidOperationException("Free
|
| 161 |
}
|
| 162 |
}
|
| 163 |
|
|
@@ -170,82 +164,6 @@ namespace FlowAPI.Application.Services
|
|
| 170 |
CreatedAt = DateTime.UtcNow
|
| 171 |
};
|
| 172 |
|
| 173 |
-
if (!string.IsNullOrEmpty(dto.TemplateKey))
|
| 174 |
-
{
|
| 175 |
-
// Try to load system template first
|
| 176 |
-
var (nodes, edges) = TemplateLibrary.GetTemplateContent(dto.TemplateKey, graph.Id);
|
| 177 |
-
|
| 178 |
-
// If not found in system templates, check custom templates in DB
|
| 179 |
-
if (nodes.Count == 0 && Guid.TryParse(dto.TemplateKey, out var customTemplateId))
|
| 180 |
-
{
|
| 181 |
-
var customTemplate = await _customTemplateRepo.GetByIdAsync(customTemplateId);
|
| 182 |
-
if (customTemplate != null && (customTemplate.UserId == currentUserId || user.SubscriptionTier == "Ultra"))
|
| 183 |
-
{
|
| 184 |
-
try
|
| 185 |
-
{
|
| 186 |
-
var data = JsonSerializer.Deserialize<CustomTemplateContentDto>(customTemplate.ContentJson);
|
| 187 |
-
if (data != null)
|
| 188 |
-
{
|
| 189 |
-
var idMapping = new Dictionary<Guid, Guid>();
|
| 190 |
-
foreach (var nodeDto in data.Nodes)
|
| 191 |
-
{
|
| 192 |
-
var newId = Guid.NewGuid();
|
| 193 |
-
idMapping[nodeDto.Id] = newId;
|
| 194 |
-
var node = new TaskNode
|
| 195 |
-
{
|
| 196 |
-
Id = newId,
|
| 197 |
-
GraphId = graph.Id,
|
| 198 |
-
Label = nodeDto.Label,
|
| 199 |
-
PosX = nodeDto.PosX,
|
| 200 |
-
PosY = nodeDto.PosY,
|
| 201 |
-
Type = nodeDto.Type,
|
| 202 |
-
State = FlowAPI.Domain.Enums.NodeState.Pending,
|
| 203 |
-
CreatedAt = DateTime.UtcNow,
|
| 204 |
-
Description = nodeDto.Description,
|
| 205 |
-
Color = nodeDto.Color,
|
| 206 |
-
IsPinned = nodeDto.IsPinned,
|
| 207 |
-
Width = nodeDto.Width,
|
| 208 |
-
Height = nodeDto.Height,
|
| 209 |
-
Data = nodeDto.Data,
|
| 210 |
-
Decision = nodeDto.Decision
|
| 211 |
-
};
|
| 212 |
-
nodes.Add(node);
|
| 213 |
-
}
|
| 214 |
-
foreach (var edgeDto in data.Edges)
|
| 215 |
-
{
|
| 216 |
-
if (idMapping.TryGetValue(edgeDto.FromNodeId, out var fromId) &&
|
| 217 |
-
idMapping.TryGetValue(edgeDto.ToNodeId, out var toId))
|
| 218 |
-
{
|
| 219 |
-
edges.Add(new Edge
|
| 220 |
-
{
|
| 221 |
-
Id = Guid.NewGuid(),
|
| 222 |
-
GraphId = graph.Id,
|
| 223 |
-
FromNodeId = fromId,
|
| 224 |
-
ToNodeId = toId,
|
| 225 |
-
Condition = edgeDto.Condition
|
| 226 |
-
});
|
| 227 |
-
}
|
| 228 |
-
}
|
| 229 |
-
}
|
| 230 |
-
}
|
| 231 |
-
catch (Exception ex)
|
| 232 |
-
{
|
| 233 |
-
System.Console.WriteLine($"[GraphService] Failed to load custom template: {ex.Message}");
|
| 234 |
-
}
|
| 235 |
-
}
|
| 236 |
-
}
|
| 237 |
-
|
| 238 |
-
if (nodes.Count > 0)
|
| 239 |
-
{
|
| 240 |
-
graph.Nodes = nodes;
|
| 241 |
-
graph.Edges = edges;
|
| 242 |
-
if (string.IsNullOrEmpty(dto.Description) || dto.Description == "New strategy path...")
|
| 243 |
-
{
|
| 244 |
-
graph.Description = $"Побудовано за шаблоном";
|
| 245 |
-
}
|
| 246 |
-
}
|
| 247 |
-
}
|
| 248 |
-
|
| 249 |
var created = await _repo.CreateAsync(graph);
|
| 250 |
|
| 251 |
await _achievementService.ProcessEventAsync(currentUserId, "GraphCreated");
|
|
@@ -314,17 +232,6 @@ namespace FlowAPI.Application.Services
|
|
| 314 |
var user = await _userRepo.GetByIdAsync(currentUserId);
|
| 315 |
if (user == null) throw new Exception("User not found.");
|
| 316 |
|
| 317 |
-
var tier = user.SubscriptionTier?.Trim();
|
| 318 |
-
bool isFree = string.IsNullOrEmpty(tier) || tier == "Free";
|
| 319 |
-
|
| 320 |
-
if (isFree)
|
| 321 |
-
{
|
| 322 |
-
if (dto.Nodes.Count > 200)
|
| 323 |
-
{
|
| 324 |
-
throw new InvalidOperationException("Free tier is limited to 200 nodes per canvas.");
|
| 325 |
-
}
|
| 326 |
-
}
|
| 327 |
-
|
| 328 |
// Secure: only allowed for owner or shared users with Edit permission
|
| 329 |
if (graph.UserId != currentUserId)
|
| 330 |
{
|
|
@@ -332,6 +239,13 @@ namespace FlowAPI.Application.Services
|
|
| 332 |
if (shared is null || shared.Permission != "Edit") return false;
|
| 333 |
}
|
| 334 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 335 |
// Map DTOs to Domain Entities
|
| 336 |
var mappedNodes = dto.Nodes.Select(nodeDto => new TaskNode
|
| 337 |
{
|
|
@@ -407,16 +321,9 @@ namespace FlowAPI.Application.Services
|
|
| 407 |
var shares = await _sharedGraphRepo.GetSharesForGraphAsync(graphId);
|
| 408 |
int currentSharedCount = shares?.Count() ?? 0;
|
| 409 |
|
| 410 |
-
|
| 411 |
-
bool ownerIsFree = string.IsNullOrEmpty(ownerTier) || ownerTier == "Free";
|
| 412 |
-
|
| 413 |
-
if (ownerIsFree && currentSharedCount >= 1)
|
| 414 |
{
|
| 415 |
-
throw new InvalidOperationException("Free
|
| 416 |
-
}
|
| 417 |
-
else if (ownerTier == "Pro" && currentSharedCount >= 9)
|
| 418 |
-
{
|
| 419 |
-
throw new InvalidOperationException("Pro tier is limited to 10 people on a board (9 guests).");
|
| 420 |
}
|
| 421 |
|
| 422 |
var share = new SharedGraph
|
|
@@ -500,79 +407,5 @@ namespace FlowAPI.Application.Services
|
|
| 500 |
Description = graph.Description,
|
| 501 |
CreatedAt = graph.CreatedAt
|
| 502 |
};
|
| 503 |
-
|
| 504 |
-
public async Task<CustomTemplate> SaveAsTemplateAsync(Guid graphId, Guid userId, string title, string description)
|
| 505 |
-
{
|
| 506 |
-
var user = await _userRepo.GetByIdAsync(userId);
|
| 507 |
-
if (user == null) throw new Exception("User not found.");
|
| 508 |
-
|
| 509 |
-
if (user.SubscriptionTier != "Ultra")
|
| 510 |
-
{
|
| 511 |
-
throw new InvalidOperationException("Creating custom templates is an Ultra tier feature.");
|
| 512 |
-
}
|
| 513 |
-
|
| 514 |
-
var graph = await _repo.GetByIdWithDetailsAsync(graphId);
|
| 515 |
-
if (graph == null || graph.UserId != userId)
|
| 516 |
-
{
|
| 517 |
-
throw new Exception("Graph not found or you are not the owner.");
|
| 518 |
-
}
|
| 519 |
-
|
| 520 |
-
// Map nodes and edges to DTOs for serialization
|
| 521 |
-
var nodes = graph.Nodes.Select(n => new NodeDto
|
| 522 |
-
{
|
| 523 |
-
Id = n.Id,
|
| 524 |
-
Label = n.Label,
|
| 525 |
-
PosX = n.PosX,
|
| 526 |
-
PosY = n.PosY,
|
| 527 |
-
Type = n.Type,
|
| 528 |
-
State = (int)n.State,
|
| 529 |
-
Decision = n.Decision,
|
| 530 |
-
Description = n.Description,
|
| 531 |
-
Color = n.Color,
|
| 532 |
-
IsPinned = n.IsPinned,
|
| 533 |
-
Width = n.Width,
|
| 534 |
-
Height = n.Height,
|
| 535 |
-
Data = n.Data
|
| 536 |
-
}).ToList();
|
| 537 |
-
|
| 538 |
-
var edges = graph.Edges.Select(e => new EdgeDto
|
| 539 |
-
{
|
| 540 |
-
Id = e.Id,
|
| 541 |
-
FromNodeId = e.FromNodeId,
|
| 542 |
-
ToNodeId = e.ToNodeId,
|
| 543 |
-
Condition = e.Condition
|
| 544 |
-
}).ToList();
|
| 545 |
-
|
| 546 |
-
var contentJson = JsonSerializer.Serialize(new CustomTemplateContentDto
|
| 547 |
-
{
|
| 548 |
-
Nodes = nodes,
|
| 549 |
-
Edges = edges
|
| 550 |
-
});
|
| 551 |
-
|
| 552 |
-
var template = new CustomTemplate
|
| 553 |
-
{
|
| 554 |
-
Id = Guid.NewGuid(),
|
| 555 |
-
UserId = userId,
|
| 556 |
-
Title = title,
|
| 557 |
-
Description = description,
|
| 558 |
-
Category = "Custom",
|
| 559 |
-
Icon = "BookOpen",
|
| 560 |
-
ContentJson = contentJson,
|
| 561 |
-
CreatedAt = DateTime.UtcNow
|
| 562 |
-
};
|
| 563 |
-
|
| 564 |
-
return await _customTemplateRepo.CreateAsync(template);
|
| 565 |
-
}
|
| 566 |
-
|
| 567 |
-
public async Task<IEnumerable<CustomTemplate>> GetCustomTemplatesAsync(Guid userId)
|
| 568 |
-
{
|
| 569 |
-
return await _customTemplateRepo.GetByUserIdAsync(userId);
|
| 570 |
-
}
|
| 571 |
-
|
| 572 |
-
private class CustomTemplateContentDto
|
| 573 |
-
{
|
| 574 |
-
public List<NodeDto> Nodes { get; set; } = new();
|
| 575 |
-
public List<EdgeDto> Edges { get; set; } = new();
|
| 576 |
-
}
|
| 577 |
}
|
| 578 |
}
|
|
|
|
| 17 |
private readonly IAchievementService _achievementService;
|
| 18 |
private readonly ISharedGraphRepository _sharedGraphRepo;
|
| 19 |
private readonly IUserRepository _userRepo;
|
|
|
|
| 20 |
|
| 21 |
public GraphService(
|
| 22 |
IGraphRepository repo,
|
|
|
|
| 24 |
IEdgeRepository edgeRepo,
|
| 25 |
IAchievementService achievementService,
|
| 26 |
ISharedGraphRepository sharedGraphRepo,
|
| 27 |
+
IUserRepository userRepo)
|
|
|
|
| 28 |
{
|
| 29 |
_repo = repo;
|
| 30 |
_nodeRepo = nodeRepo;
|
|
|
|
| 32 |
_achievementService = achievementService;
|
| 33 |
_sharedGraphRepo = sharedGraphRepo;
|
| 34 |
_userRepo = userRepo;
|
|
|
|
| 35 |
}
|
| 36 |
|
| 37 |
public async Task<IEnumerable<GraphResponseDto>> GetAllByUserIdAsync(Guid userId)
|
|
|
|
| 146 |
var user = await _userRepo.GetByIdAsync(currentUserId);
|
| 147 |
if (user == null) throw new Exception("User not found.");
|
| 148 |
|
| 149 |
+
if (!Plans.IsPlus(user))
|
|
|
|
|
|
|
|
|
|
| 150 |
{
|
| 151 |
var ownedGraphsCount = (await _repo.GetAllByUserIdAsync(currentUserId)).Count();
|
| 152 |
+
if (ownedGraphsCount >= Plans.FreeMaxBoards)
|
| 153 |
{
|
| 154 |
+
throw new InvalidOperationException($"Free plan is limited to {Plans.FreeMaxBoards} boards. Upgrade to Plus for unlimited boards.");
|
| 155 |
}
|
| 156 |
}
|
| 157 |
|
|
|
|
| 164 |
CreatedAt = DateTime.UtcNow
|
| 165 |
};
|
| 166 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
var created = await _repo.CreateAsync(graph);
|
| 168 |
|
| 169 |
await _achievementService.ProcessEventAsync(currentUserId, "GraphCreated");
|
|
|
|
| 232 |
var user = await _userRepo.GetByIdAsync(currentUserId);
|
| 233 |
if (user == null) throw new Exception("User not found.");
|
| 234 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 235 |
// Secure: only allowed for owner or shared users with Edit permission
|
| 236 |
if (graph.UserId != currentUserId)
|
| 237 |
{
|
|
|
|
| 239 |
if (shared is null || shared.Permission != "Edit") return false;
|
| 240 |
}
|
| 241 |
|
| 242 |
+
// Limits are bound to the board owner's plan, not to the editor's
|
| 243 |
+
var owner = graph.UserId == currentUserId ? user : await _userRepo.GetByIdAsync(graph.UserId);
|
| 244 |
+
if (owner != null && !Plans.IsPlus(owner) && dto.Nodes.Count > Plans.FreeMaxNodesPerBoard)
|
| 245 |
+
{
|
| 246 |
+
throw new InvalidOperationException($"Free plan is limited to {Plans.FreeMaxNodesPerBoard} nodes per board. Upgrade to Plus for unlimited nodes.");
|
| 247 |
+
}
|
| 248 |
+
|
| 249 |
// Map DTOs to Domain Entities
|
| 250 |
var mappedNodes = dto.Nodes.Select(nodeDto => new TaskNode
|
| 251 |
{
|
|
|
|
| 321 |
var shares = await _sharedGraphRepo.GetSharesForGraphAsync(graphId);
|
| 322 |
int currentSharedCount = shares?.Count() ?? 0;
|
| 323 |
|
| 324 |
+
if (!Plans.IsPlus(owner) && currentSharedCount >= Plans.FreeMaxGuestsPerBoard)
|
|
|
|
|
|
|
|
|
|
| 325 |
{
|
| 326 |
+
throw new InvalidOperationException($"Free plan allows up to {Plans.FreeMaxGuestsPerBoard} guests per board. Upgrade to Plus for unlimited collaborators.");
|
|
|
|
|
|
|
|
|
|
|
|
|
| 327 |
}
|
| 328 |
|
| 329 |
var share = new SharedGraph
|
|
|
|
| 407 |
Description = graph.Description,
|
| 408 |
CreatedAt = graph.CreatedAt
|
| 409 |
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
}
|
| 411 |
}
|
|
@@ -32,17 +32,14 @@ namespace FlowAPI.Application.Services
|
|
| 32 |
var existing = await _repo.GetRecordForDateAsync(dto.UserId, dto.HabitName, targetDate.Date);
|
| 33 |
if (existing is not null) return MapToDto(existing);
|
| 34 |
|
| 35 |
-
|
| 36 |
-
bool isFree = string.IsNullOrEmpty(tier) || tier == "Free";
|
| 37 |
-
|
| 38 |
-
if (isFree)
|
| 39 |
{
|
| 40 |
var allRecords = await _repo.GetAllByUserIdAsync(dto.UserId);
|
| 41 |
var distinctHabits = allRecords.Select(r => r.HabitName).Distinct().ToList();
|
| 42 |
|
| 43 |
-
if (!distinctHabits.Contains(dto.HabitName) && distinctHabits.Count >=
|
| 44 |
{
|
| 45 |
-
throw new InvalidOperationException("Free
|
| 46 |
}
|
| 47 |
}
|
| 48 |
|
|
|
|
| 32 |
var existing = await _repo.GetRecordForDateAsync(dto.UserId, dto.HabitName, targetDate.Date);
|
| 33 |
if (existing is not null) return MapToDto(existing);
|
| 34 |
|
| 35 |
+
if (!Plans.IsPlus(user))
|
|
|
|
|
|
|
|
|
|
| 36 |
{
|
| 37 |
var allRecords = await _repo.GetAllByUserIdAsync(dto.UserId);
|
| 38 |
var distinctHabits = allRecords.Select(r => r.HabitName).Distinct().ToList();
|
| 39 |
|
| 40 |
+
if (!distinctHabits.Contains(dto.HabitName) && distinctHabits.Count >= Plans.FreeMaxHabits)
|
| 41 |
{
|
| 42 |
+
throw new InvalidOperationException($"Free plan is limited to {Plans.FreeMaxHabits} habits.");
|
| 43 |
}
|
| 44 |
}
|
| 45 |
|
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
using FlowAPI.Domain.Entities;
|
| 2 |
+
|
| 3 |
+
namespace FlowAPI.Application.Services
|
| 4 |
+
{
|
| 5 |
+
/// <summary>
|
| 6 |
+
/// Subscription plans. There are only two: Free (small creation limits) and Plus (no limits).
|
| 7 |
+
/// Legacy values ("Pro", "Ultra") are treated as Plus.
|
| 8 |
+
/// </summary>
|
| 9 |
+
public static class Plans
|
| 10 |
+
{
|
| 11 |
+
public const string Free = "Free";
|
| 12 |
+
public const string Plus = "Plus";
|
| 13 |
+
|
| 14 |
+
public const int FreeMaxBoards = 5;
|
| 15 |
+
public const int FreeMaxNodesPerBoard = 300;
|
| 16 |
+
public const int FreeMaxGuestsPerBoard = 2;
|
| 17 |
+
public const int FreeMaxTemplates = 3;
|
| 18 |
+
public const int FreeMaxHabits = 3;
|
| 19 |
+
|
| 20 |
+
public static string Normalize(string? tier) =>
|
| 21 |
+
string.IsNullOrWhiteSpace(tier) || tier.Trim().Equals(Free, System.StringComparison.OrdinalIgnoreCase)
|
| 22 |
+
? Free
|
| 23 |
+
: Plus;
|
| 24 |
+
|
| 25 |
+
public static bool IsValid(string? tier) =>
|
| 26 |
+
tier != null && (tier.Trim() == Free || tier.Trim() == Plus);
|
| 27 |
+
|
| 28 |
+
public static bool IsPlus(User user) => Normalize(user.SubscriptionTier) == Plus;
|
| 29 |
+
}
|
| 30 |
+
}
|
|
@@ -1,353 +0,0 @@
|
|
| 1 |
-
using System;
|
| 2 |
-
using System.Collections.Generic;
|
| 3 |
-
using FlowAPI.Application.DTOs.Graph;
|
| 4 |
-
using FlowAPI.Domain.Entities;
|
| 5 |
-
using FlowAPI.Domain.Enums;
|
| 6 |
-
|
| 7 |
-
namespace FlowAPI.Application.Services
|
| 8 |
-
{
|
| 9 |
-
public static class TemplateLibrary
|
| 10 |
-
{
|
| 11 |
-
private class TemplateNodeDef
|
| 12 |
-
{
|
| 13 |
-
public string TempId { get; set; } = string.Empty;
|
| 14 |
-
public string Label { get; set; } = string.Empty;
|
| 15 |
-
public double PosX { get; set; }
|
| 16 |
-
public double PosY { get; set; }
|
| 17 |
-
public string Type { get; set; } = "sketch";
|
| 18 |
-
public string Color { get; set; } = "white";
|
| 19 |
-
public string Description { get; set; } = string.Empty;
|
| 20 |
-
public string DecisionJson { get; set; } = string.Empty;
|
| 21 |
-
public double? Width { get; set; }
|
| 22 |
-
public double? Height { get; set; }
|
| 23 |
-
}
|
| 24 |
-
|
| 25 |
-
private class TemplateEdgeDef
|
| 26 |
-
{
|
| 27 |
-
public string FromTempId { get; set; } = string.Empty;
|
| 28 |
-
public string ToTempId { get; set; } = string.Empty;
|
| 29 |
-
public string Condition { get; set; } = "True";
|
| 30 |
-
}
|
| 31 |
-
|
| 32 |
-
private class TemplateDef
|
| 33 |
-
{
|
| 34 |
-
public string Key { get; set; } = string.Empty;
|
| 35 |
-
public string Title { get; set; } = string.Empty;
|
| 36 |
-
public string Description { get; set; } = string.Empty;
|
| 37 |
-
public string Icon { get; set; } = string.Empty;
|
| 38 |
-
public string Category { get; set; } = string.Empty;
|
| 39 |
-
public List<TemplateNodeDef> Nodes { get; set; } = new();
|
| 40 |
-
public List<TemplateEdgeDef> Edges { get; set; } = new();
|
| 41 |
-
}
|
| 42 |
-
|
| 43 |
-
private static readonly Dictionary<string, TemplateDef> Templates = new()
|
| 44 |
-
{
|
| 45 |
-
{
|
| 46 |
-
"startup",
|
| 47 |
-
new TemplateDef
|
| 48 |
-
{
|
| 49 |
-
Key = "startup",
|
| 50 |
-
Title = "Запуск Стартапу",
|
| 51 |
-
Description = "Шлях від формулювання ціннісної пропозиції та CustDev до запуску MVP та перших 100 користувачів.",
|
| 52 |
-
Icon = "Rocket",
|
| 53 |
-
Category = "Business",
|
| 54 |
-
Nodes = new List<TemplateNodeDef>
|
| 55 |
-
{
|
| 56 |
-
new() { TempId = "vprop", Label = "Формулювання ціннісної пропозиції", PosX = 250, PosY = 50, Color = "purple", Description = "Чітко опишіть, яку проблему вирішує ваш продукт і для кого." },
|
| 57 |
-
new() { TempId = "custdev", Label = "CustDev: Інтерв'ю з клієнтами", PosX = 250, PosY = 170, Color = "blue", Description = "Проведіть принаймні 10 інтерв'ю з потенційними користувачами." },
|
| 58 |
-
new() { TempId = "fit", Label = "Чи підтверджено проблему?", PosX = 250, PosY = 290, Type = "condition", DecisionJson = "{\"options\":[{\"id\":\"opt-yes\",\"label\":\"Так (Є інтерес)\"},{\"id\":\"opt-no\",\"label\":\"Ні (Потрібен півот)\"}],\"selected\":[],\"multiSelect\":false}" },
|
| 59 |
-
new() { TempId = "mvp", Label = "Розробка MVP", PosX = 100, PosY = 420, Color = "green", Description = "Створіть мінімально життєздатний продукт з однією ключовою функцією." },
|
| 60 |
-
new() { TempId = "pivot", Label = "Півот ідеї", PosX = 400, PosY = 420, Color = "orange", Description = "Змініть напрямок або цільову аудиторію на основі фідбеку з інтерв'ю." },
|
| 61 |
-
new() { TempId = "landing", Label = "Лендинг та збір заявок", PosX = 100, PosY = 550, Color = "pink", Description = "Налаштуйте просту сторінку для збору контактів зацікавлених клієнтів." },
|
| 62 |
-
new() { TempId = "users", Label = "Залучення перших 100 користувачів", PosX = 100, PosY = 680, Color = "yellow", Description = "Використовуйте безкоштовні канали (соцмережі, профільні форуми, зв'язки)." }
|
| 63 |
-
},
|
| 64 |
-
Edges = new List<TemplateEdgeDef>
|
| 65 |
-
{
|
| 66 |
-
new() { FromTempId = "vprop", ToTempId = "custdev" },
|
| 67 |
-
new() { FromTempId = "custdev", ToTempId = "fit" },
|
| 68 |
-
new() { FromTempId = "fit", ToTempId = "mvp", Condition = "True" },
|
| 69 |
-
new() { FromTempId = "fit", ToTempId = "pivot", Condition = "False" },
|
| 70 |
-
new() { FromTempId = "pivot", ToTempId = "vprop" },
|
| 71 |
-
new() { FromTempId = "mvp", ToTempId = "landing" },
|
| 72 |
-
new() { FromTempId = "landing", ToTempId = "users" }
|
| 73 |
-
}
|
| 74 |
-
}
|
| 75 |
-
},
|
| 76 |
-
{
|
| 77 |
-
"software",
|
| 78 |
-
new TemplateDef
|
| 79 |
-
{
|
| 80 |
-
Key = "software",
|
| 81 |
-
Title = "Розробка ПЗ (Web App)",
|
| 82 |
-
Description = "Стандартний життєвий цикл розробки веб-додатку: вимоги, дизайн, UI/UX, API, інтеграція та реліз.",
|
| 83 |
-
Icon = "Code",
|
| 84 |
-
Category = "Development",
|
| 85 |
-
Nodes = new List<TemplateNodeDef>
|
| 86 |
-
{
|
| 87 |
-
new() { TempId = "req", Label = "Збір та аналіз вимог", PosX = 250, PosY = 50, Color = "blue", Description = "Опишіть функціонал проекту та підготуйте ТЗ." },
|
| 88 |
-
new() { TempId = "arch", Label = "Архітектура та проектування БД", PosX = 250, PosY = 170, Color = "purple", Description = "Спроектуйте схему бази даних та виберіть стек технологій." },
|
| 89 |
-
new() { TempId = "uiux", Label = "UI/UX макети та дизайн", PosX = 100, PosY = 300, Color = "pink", Description = "Створіть клікабельний прототип у Figma." },
|
| 90 |
-
new() { TempId = "api", Label = "Розробка API та Бекенду", PosX = 400, PosY = 300, Color = "yellow", Description = "Реалізуйте серверу логіку, авторизацію та базу даних." },
|
| 91 |
-
new() { TempId = "integ", Label = "Інтеграція та тестування", PosX = 250, PosY = 440, Color = "green", Description = "З'єднайте фронтенд з бекендом та проведіть ручне тестування." },
|
| 92 |
-
new() { TempId = "staging", Label = "Деплой на Staging сервер", PosX = 250, PosY = 560, Color = "orange", Description = "Розгорніть тестову версію додатку для фінальної перевірки." },
|
| 93 |
-
new() { TempId = "prod", Label = "Реліз у Production та моніторинг", PosX = 250, PosY = 680, Color = "green", Description = "Запустіть додаток для реальних користувачів та підключіть аналітику." }
|
| 94 |
-
},
|
| 95 |
-
Edges = new List<TemplateEdgeDef>
|
| 96 |
-
{
|
| 97 |
-
new() { FromTempId = "req", ToTempId = "arch" },
|
| 98 |
-
new() { FromTempId = "arch", ToTempId = "uiux" },
|
| 99 |
-
new() { FromTempId = "arch", ToTempId = "api" },
|
| 100 |
-
new() { FromTempId = "uiux", ToTempId = "integ" },
|
| 101 |
-
new() { FromTempId = "api", ToTempId = "integ" },
|
| 102 |
-
new() { FromTempId = "integ", ToTempId = "staging" },
|
| 103 |
-
new() { FromTempId = "staging", ToTempId = "prod" }
|
| 104 |
-
}
|
| 105 |
-
}
|
| 106 |
-
},
|
| 107 |
-
{
|
| 108 |
-
"language",
|
| 109 |
-
new TemplateDef
|
| 110 |
-
{
|
| 111 |
-
Key = "language",
|
| 112 |
-
Title = "Вивчення Іноземної Мови",
|
| 113 |
-
Description = "Методика освоєння мови через щоденні звички, проходження базового курсу та вихід у практику.",
|
| 114 |
-
Icon = "Languages",
|
| 115 |
-
Category = "Education",
|
| 116 |
-
Nodes = new List<TemplateNodeDef>
|
| 117 |
-
{
|
| 118 |
-
new() { TempId = "goal", Label = "Визначення цілей та ресурсів", PosX = 250, PosY = 50, Color = "purple", Description = "Оберіть додатки, підручники та поставте чітку ціль (наприклад, рівень B1)." },
|
| 119 |
-
new() { TempId = "words", Label = "Вчити 15 нових слів щодня", PosX = 100, PosY = 170, Type = "habit", Color = "blue", Description = "Використовуйте картки Anki або Quizlet для регулярного повторення.", DecisionJson = "{\"resetRule\":{\"type\":\"daily\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Використовуйте картки Anki або Quizlet для регулярного повторення.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" },
|
| 120 |
-
new() { TempId = "listen", Label = "Слухати подкаст / дивитись відео", PosX = 400, PosY = 170, Type = "habit", Color = "pink", Description = "Принаймні 20 хвилин фонового або активного слухання щодня.", DecisionJson = "{\"resetRule\":{\"type\":\"daily\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Принаймні 20 хвилин фонового або активного слухання щодня.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" },
|
| 121 |
-
new() { TempId = "course", Label = "Завершити курс для початківців", PosX = 250, PosY = 300, Color = "yellow", Description = "Пройти базову граматику та отримати розуміння структури мови." },
|
| 122 |
-
new() { TempId = "speak", Label = "Розмовна сесія (1 раз на тиждень)", PosX = 100, PosY = 430, Type = "habit", Color = "green", Description = "Знайдіть партнера для спілкування на Tandem або викладача.", DecisionJson = "{\"resetRule\":{\"type\":\"weekly\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Знайдіть партнера для спілкування на Tandem або викладача.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" },
|
| 123 |
-
new() { TempId = "read", Label = "Прочитати першу коротку розповідь", PosX = 400, PosY = 430, Color = "orange", Description = "Оберіть адаптовану книгу під ваш поточний рівень." },
|
| 124 |
-
new() { TempId = "exam", Label = "Скласти тестовий іспит", PosX = 250, PosY = 560, Color = "green", Description = "Перевірте свій прогрес за допомогою офіційного пробного тесту." }
|
| 125 |
-
},
|
| 126 |
-
Edges = new List<TemplateEdgeDef>
|
| 127 |
-
{
|
| 128 |
-
new() { FromTempId = "goal", ToTempId = "words" },
|
| 129 |
-
new() { FromTempId = "goal", ToTempId = "listen" },
|
| 130 |
-
new() { FromTempId = "words", ToTempId = "course" },
|
| 131 |
-
new() { FromTempId = "listen", ToTempId = "course" },
|
| 132 |
-
new() { FromTempId = "course", ToTempId = "speak" },
|
| 133 |
-
new() { FromTempId = "course", ToTempId = "read" },
|
| 134 |
-
new() { FromTempId = "speak", ToTempId = "exam" },
|
| 135 |
-
new() { FromTempId = "read", ToTempId = "exam" }
|
| 136 |
-
}
|
| 137 |
-
}
|
| 138 |
-
},
|
| 139 |
-
{
|
| 140 |
-
"fitness",
|
| 141 |
-
new TemplateDef
|
| 142 |
-
{
|
| 143 |
-
Key = "fitness",
|
| 144 |
-
Title = "Фітнес та Здорове Тіло",
|
| 145 |
-
Description = "Збалансований план тренувань, контролю харчування та циклічного аналізу результатів.",
|
| 146 |
-
Icon = "Activity",
|
| 147 |
-
Category = "Health",
|
| 148 |
-
Nodes = new List<TemplateNodeDef>
|
| 149 |
-
{
|
| 150 |
-
new() { TempId = "setup", Label = "Поставити ціль та розрахувати КБЖВ", PosX = 250, PosY = 50, Color = "blue", Description = "Визначте добову норму калорій залежно від мети (схуднення чи набір маси)." },
|
| 151 |
-
new() { TempId = "plan", Label = "Скласти план тренувань та раціон", PosX = 250, PosY = 170, Color = "purple", Description = "Виберіть 3 дні для занять та підготуйте перелік здорових страв." },
|
| 152 |
-
new() { TempId = "diet", Label = "Трекати щоденне харчування та воду", PosX = 100, PosY = 300, Type = "habit", Color = "green", Description = "Записуйте все з'їдене в MyFitnessPal та пийте достатньо води.", DecisionJson = "{\"resetRule\":{\"type\":\"daily\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Записуйте все з'їдене в MyFitnessPal та пийте достатньо води.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" },
|
| 153 |
-
new() { TempId = "workout", Label = "Силове або кардіо тренування", PosX = 400, PosY = 300, Type = "habit", Color = "orange", Description = "Виконуйте заплановане тренування 3 рази на тиждень.", DecisionJson = "{\"resetRule\":{\"type\":\"weekly\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Виконуйте заплановане тренування 3 рази на тиждень.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" },
|
| 154 |
-
new() { TempId = "check", Label = "Контрольне зважування та заміри (4 тижні)", PosX = 250, PosY = 430, Color = "yellow", Description = "Порівняйте поточну вагу та об'єми тіла з початковими показниками." },
|
| 155 |
-
new() { TempId = "satisfied", Label = "Чи є прогрес задовільним?", PosX = 250, PosY = 550, Type = "condition", DecisionJson = "{\"options\":[{\"id\":\"opt-yes\",\"label\":\"Так (Продовжуємо)\"},{\"id\":\"opt-no\",\"label\":\"Ні (Потрібні коригування)\"}],\"selected\":[],\"multiSelect\":false}" },
|
| 156 |
-
new() { TempId = "advance", Label = "Ускладнити програму тренувань", PosX = 100, PosY = 680, Color = "pink", Description = "Додайте вагу на снарядах або збільшіть інтенсивність." },
|
| 157 |
-
new() { TempId = "adjust", Label = "Скоригувати КБЖВ та план їжі", PosX = 400, PosY = 680, Color = "yellow", Description = "Зменшіть або збільшіть калорійність раціону на 10%." }
|
| 158 |
-
},
|
| 159 |
-
Edges = new List<TemplateEdgeDef>
|
| 160 |
-
{
|
| 161 |
-
new() { FromTempId = "setup", ToTempId = "plan" },
|
| 162 |
-
new() { FromTempId = "plan", ToTempId = "diet" },
|
| 163 |
-
new() { FromTempId = "plan", ToTempId = "workout" },
|
| 164 |
-
new() { FromTempId = "diet", ToTempId = "check" },
|
| 165 |
-
new() { FromTempId = "workout", ToTempId = "check" },
|
| 166 |
-
new() { FromTempId = "check", ToTempId = "satisfied" },
|
| 167 |
-
new() { FromTempId = "satisfied", ToTempId = "advance", Condition = "True" },
|
| 168 |
-
new() { FromTempId = "satisfied", ToTempId = "adjust", Condition = "False" },
|
| 169 |
-
new() { FromTempId = "adjust", ToTempId = "plan" }
|
| 170 |
-
}
|
| 171 |
-
}
|
| 172 |
-
},
|
| 173 |
-
{
|
| 174 |
-
"gamedev",
|
| 175 |
-
new TemplateDef
|
| 176 |
-
{
|
| 177 |
-
Key = "gamedev",
|
| 178 |
-
Title = "Створення Інді-Гри",
|
| 179 |
-
Description = "Повний цикл геймдеву від ідеї та прототипу до створення сторінки в Steam та релізу.",
|
| 180 |
-
Icon = "Gamepad",
|
| 181 |
-
Category = "Creative",
|
| 182 |
-
Nodes = new List<TemplateNodeDef>
|
| 183 |
-
{
|
| 184 |
-
new() { TempId = "concept", Label = "Концепт та написання GDD", PosX = 250, PosY = 50, Color = "pink", Description = "Сформулюйте основну ідею гри та опишіть її механіки в дизайн-документі." },
|
| 185 |
-
new() { TempId = "proto", Label = "Прототип базового геймплею", PosX = 250, PosY = 170, Color = "purple", Description = "Створіть «сіру коробку» на рушії, щоб перевірити, чи весело грати." },
|
| 186 |
-
new() { TempId = "art", Label = "Стилістика та створення артів", PosX = 100, PosY = 300, Color = "orange", Description = "Визначте художній стиль та підготуйте перші 2D/3D моделі." },
|
| 187 |
-
new() { TempId = "level", Label = "Дизайн рівнів та звуковий супровід", PosX = 400, PosY = 300, Color = "blue", Description = "Створіть тестовий рівень та додайте базові звукові ефекти." },
|
| 188 |
-
new() { TempId = "playable", Label = "Перша грабельна демо-версія", PosX = 250, PosY = 430, Color = "yellow", Description = "Зберіть стабільний білд для тестування друзями." },
|
| 189 |
-
new() { TempId = "test", Label = "Плейтести та виправлення багів", PosX = 100, PosY = 560, Type = "habit", Color = "pink", Description = "Щодня грайте, збирайте фідбек та виправляйте помилки.", DecisionJson = "{\"resetRule\":{\"type\":\"daily\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Щодня грайте, збирайте фідбек та виправляйте помилки.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" },
|
| 190 |
-
new() { TempId = "steam", Label = "Створення сторінки в Steam", PosX = 400, PosY = 560, Color = "yellow", Description = "Підготуйте красиві скріншоти, трейлер та запустіть сторінку для збору Wishlists." },
|
| 191 |
-
new() { TempId = "release", Label = "Реліз гри в Steam", PosX = 250, PosY = 690, Color = "green", Description = "Опублікуйте фінальний білд та підтримайте запуск маркетинговою кампанією." }
|
| 192 |
-
},
|
| 193 |
-
Edges = new List<TemplateEdgeDef>
|
| 194 |
-
{
|
| 195 |
-
new() { FromTempId = "concept", ToTempId = "proto" },
|
| 196 |
-
new() { FromTempId = "proto", ToTempId = "art" },
|
| 197 |
-
new() { FromTempId = "proto", ToTempId = "level" },
|
| 198 |
-
new() { FromTempId = "art", ToTempId = "playable" },
|
| 199 |
-
new() { FromTempId = "level", ToTempId = "playable" },
|
| 200 |
-
new() { FromTempId = "playable", ToTempId = "test" },
|
| 201 |
-
new() { FromTempId = "playable", ToTempId = "steam" },
|
| 202 |
-
new() { FromTempId = "test", ToTempId = "release" },
|
| 203 |
-
new() { FromTempId = "steam", ToTempId = "release" }
|
| 204 |
-
}
|
| 205 |
-
}
|
| 206 |
-
},
|
| 207 |
-
{
|
| 208 |
-
"finance",
|
| 209 |
-
new TemplateDef
|
| 210 |
-
{
|
| 211 |
-
Key = "finance",
|
| 212 |
-
Title = "Фінансова Свобода",
|
| 213 |
-
Description = "Покроковий план досягнення фінансової незалежності: облік витрат, подушка безпеки та інвестиції.",
|
| 214 |
-
Icon = "DollarSign",
|
| 215 |
-
Category = "Finance",
|
| 216 |
-
Nodes = new List<TemplateNodeDef>
|
| 217 |
-
{
|
| 218 |
-
new() { TempId = "audit", Label = "Аудит активів та боргових зобов'язань", PosX = 250, PosY = 50, Color = "yellow", Description = "Запишіть усі свої збереження, майно та кредити." },
|
| 219 |
-
new() { TempId = "track", Label = "Щоденний облік усіх витрат", PosX = 100, PosY = 170, Type = "habit", Color = "blue", Description = "Записуйте кожну покупку в мобільний додаток або Excel таблицю.", DecisionJson = "{\"resetRule\":{\"type\":\"daily\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Записуйте кожну покупку в мобільний додаток або Excel таблицю.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" },
|
| 220 |
-
new() { TempId = "emergency", Label = "Сформувати подушку на 3 місяці", PosX = 300, PosY = 170, Color = "orange", Description = "Розрахуйте мінімальний бюджет життя та накопичте цю суму на депозиті." },
|
| 221 |
-
new() { TempId = "debt", Label = "Виплатити всі споживчі кредити", PosX = 250, PosY = 290, Color = "pink", Description = "Спрямуйте вільні кошти на швидке закриття боргів з найвищими відсотками." },
|
| 222 |
-
new() { TempId = "invest", Label = "Інвестувати 20% від доходу", PosX = 100, PosY = 420, Type = "habit", Color = "green", Description = "Регулярно купуйте надійні індекси (ETF) або облігації.", DecisionJson = "{\"resetRule\":{\"type\":\"monthly\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Регулярно купуйте надійні індекси (ETF) або облігації.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" },
|
| 223 |
-
new() { TempId = "passive", Label = "Створити джерело пасивного доходу", PosX = 400, PosY = 420, Color = "purple", Description = "Створіть власний блог, курс, невеликий онлайн-сервіс чи придбайте дивідендні акції." },
|
| 224 |
-
new() { TempId = "freedom", Label = "Досягти фінансової незалежності", PosX = 250, PosY = 550, Color = "green", Description = "Коли пасивний дохід повністю перекриє ваші щомісячні витрати." }
|
| 225 |
-
},
|
| 226 |
-
Edges = new List<TemplateEdgeDef>
|
| 227 |
-
{
|
| 228 |
-
new() { FromTempId = "audit", ToTempId = "track" },
|
| 229 |
-
new() { FromTempId = "audit", ToTempId = "emergency" },
|
| 230 |
-
new() { FromTempId = "track", ToTempId = "debt" },
|
| 231 |
-
new() { FromTempId = "emergency", ToTempId = "debt" },
|
| 232 |
-
new() { FromTempId = "debt", ToTempId = "invest" },
|
| 233 |
-
new() { FromTempId = "debt", ToTempId = "passive" },
|
| 234 |
-
new() { FromTempId = "invest", ToTempId = "freedom" },
|
| 235 |
-
new() { FromTempId = "passive", ToTempId = "freedom" }
|
| 236 |
-
}
|
| 237 |
-
}
|
| 238 |
-
},
|
| 239 |
-
{
|
| 240 |
-
"writing",
|
| 241 |
-
new TemplateDef
|
| 242 |
-
{
|
| 243 |
-
Key = "writing",
|
| 244 |
-
Title = "Написання та Публікація Книги",
|
| 245 |
-
Description = "Шлях автора: від розробки сюжету та персо��ажів до щоденного написання, редактури та релізу.",
|
| 246 |
-
Icon = "BookOpen",
|
| 247 |
-
Category = "Creative",
|
| 248 |
-
Nodes = new List<TemplateNodeDef>
|
| 249 |
-
{
|
| 250 |
-
new() { TempId = "outline", Label = "Побудова сюжету та анкет персонажів", PosX = 250, PosY = 50, Color = "pink", Description = "Напишіть синопсис та детально розпишіть структуру розділів книги." },
|
| 251 |
-
new() { TempId = "words", Label = "Писати по 1000 слів щодня", PosX = 100, PosY = 170, Type = "habit", Color = "purple", Description = "Формуйте звичку писати без критики та внутрішнього редактора.", DecisionJson = "{\"resetRule\":{\"type\":\"daily\",\"time\":\"00:00\"},\"createdAt\":\"" + DateTime.UtcNow.ToString("o") + "\",\"description\":\"Формуйте звичку писати без критики та внутрішнього редактора.\",\"tags\":[],\"status\":\"Todo\",\"progress\":0}" },
|
| 252 |
-
new() { TempId = "draft", Label = "Завершити першу чернетку", PosX = 350, PosY = 170, Color = "yellow", Description = "Напишіть повну історію від початку до кінця (орієнтовно 50-80 тис. слів)." },
|
| 253 |
-
new() { TempId = "edit", Label = "Самостійна редактура та вичитка", PosX = 250, PosY = 300, Color = "orange", Description = "Виправте логічні помилки, покращіть діалоги та стиль оповідання." },
|
| 254 |
-
new() { TempId = "beta", Label = "Отримати фідбек від бета-рідерів", PosX = 250, PosY = 420, Color = "blue", Description = "Дайте почитати книгу кільком людям із вашої цільової аудиторії." },
|
| 255 |
-
new() { TempId = "professional", Label = "Професійна коректура та верстка", PosX = 250, PosY = 540, Color = "pink", Description = "Знайдіть професійного редактора для виправлення граматики та підготовки макету." },
|
| 256 |
-
new() { TempId = "cover", Label = "Створення обкладинки та форматування", PosX = 100, PosY = 660, Color = "purple", Description = "Замовте обкладинку в дизайнера та підготуйте формати ePub, PDF." },
|
| 257 |
-
new() { TempId = "publish", Label = "Публікація та запуск маркетингу", PosX = 350, PosY = 660, Color = "green", Description = "Опублікуйте книгу на Amazon / Litres та запустіть промо-акції." }
|
| 258 |
-
},
|
| 259 |
-
Edges = new List<TemplateEdgeDef>
|
| 260 |
-
{
|
| 261 |
-
new() { FromTempId = "outline", ToTempId = "words" },
|
| 262 |
-
new() { FromTempId = "words", ToTempId = "draft" },
|
| 263 |
-
new() { FromTempId = "draft", ToTempId = "edit" },
|
| 264 |
-
new() { FromTempId = "edit", ToTempId = "beta" },
|
| 265 |
-
new() { FromTempId = "beta", ToTempId = "professional" },
|
| 266 |
-
new() { FromTempId = "professional", ToTempId = "cover" },
|
| 267 |
-
new() { FromTempId = "professional", ToTempId = "publish" }
|
| 268 |
-
}
|
| 269 |
-
}
|
| 270 |
-
}
|
| 271 |
-
};
|
| 272 |
-
|
| 273 |
-
public static IEnumerable<TemplateInfoDto> GetTemplateInfos()
|
| 274 |
-
{
|
| 275 |
-
var list = new List<TemplateInfoDto>();
|
| 276 |
-
foreach (var kv in Templates)
|
| 277 |
-
{
|
| 278 |
-
list.Add(new TemplateInfoDto
|
| 279 |
-
{
|
| 280 |
-
Key = kv.Value.Key,
|
| 281 |
-
Title = kv.Value.Title,
|
| 282 |
-
Description = kv.Value.Description,
|
| 283 |
-
Icon = kv.Value.Icon,
|
| 284 |
-
Category = kv.Value.Category
|
| 285 |
-
});
|
| 286 |
-
}
|
| 287 |
-
return list;
|
| 288 |
-
}
|
| 289 |
-
|
| 290 |
-
public static (List<TaskNode> Nodes, List<Edge> Edges) GetTemplateContent(string key, Guid graphId)
|
| 291 |
-
{
|
| 292 |
-
if (!Templates.TryGetValue(key.ToLower().Trim(), out var template))
|
| 293 |
-
{
|
| 294 |
-
return (new List<TaskNode>(), new List<Edge>());
|
| 295 |
-
}
|
| 296 |
-
|
| 297 |
-
var nodes = new List<TaskNode>();
|
| 298 |
-
var edges = new List<Edge>();
|
| 299 |
-
var idMapping = new Dictionary<string, Guid>();
|
| 300 |
-
|
| 301 |
-
// 1. Instantiate nodes and map their IDs
|
| 302 |
-
foreach (var nodeDef in template.Nodes)
|
| 303 |
-
{
|
| 304 |
-
var newId = Guid.NewGuid();
|
| 305 |
-
idMapping[nodeDef.TempId] = newId;
|
| 306 |
-
|
| 307 |
-
var taskNode = new TaskNode
|
| 308 |
-
{
|
| 309 |
-
Id = newId,
|
| 310 |
-
GraphId = graphId,
|
| 311 |
-
Label = nodeDef.Label,
|
| 312 |
-
PosX = nodeDef.PosX,
|
| 313 |
-
PosY = nodeDef.PosY,
|
| 314 |
-
Type = nodeDef.Type,
|
| 315 |
-
State = NodeState.Pending,
|
| 316 |
-
CreatedAt = DateTime.UtcNow,
|
| 317 |
-
Description = nodeDef.Description,
|
| 318 |
-
Color = nodeDef.Color,
|
| 319 |
-
IsPinned = false,
|
| 320 |
-
Decision = string.IsNullOrEmpty(nodeDef.DecisionJson) ? null : nodeDef.DecisionJson
|
| 321 |
-
};
|
| 322 |
-
|
| 323 |
-
// For normal sketch nodes without custom Decision JSON, populate standard default JSON
|
| 324 |
-
if (nodeDef.Type == "sketch" && string.IsNullOrEmpty(nodeDef.DecisionJson))
|
| 325 |
-
{
|
| 326 |
-
taskNode.Decision = $"{{\"description\":\"{nodeDef.Description}\",\"progress\":0,\"showProgress\":false,\"decision\":\"bottom\",\"assignees\":[],\"color\":\"{nodeDef.Color}\",\"isPinned\":false,\"tags\":[],\"status\":\"Todo\"}}";
|
| 327 |
-
}
|
| 328 |
-
|
| 329 |
-
nodes.Add(taskNode);
|
| 330 |
-
}
|
| 331 |
-
|
| 332 |
-
// 2. Instantiate edges
|
| 333 |
-
foreach (var edgeDef in template.Edges)
|
| 334 |
-
{
|
| 335 |
-
if (idMapping.TryGetValue(edgeDef.FromTempId, out var fromId) &&
|
| 336 |
-
idMapping.TryGetValue(edgeDef.ToTempId, out var toId))
|
| 337 |
-
{
|
| 338 |
-
var edge = new Edge
|
| 339 |
-
{
|
| 340 |
-
Id = Guid.NewGuid(),
|
| 341 |
-
GraphId = graphId,
|
| 342 |
-
FromNodeId = fromId,
|
| 343 |
-
ToNodeId = toId,
|
| 344 |
-
Condition = edgeDef.Condition
|
| 345 |
-
};
|
| 346 |
-
edges.Add(edge);
|
| 347 |
-
}
|
| 348 |
-
}
|
| 349 |
-
|
| 350 |
-
return (nodes, edges);
|
| 351 |
-
}
|
| 352 |
-
}
|
| 353 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
using FlowAPI.Application.DTOs.Template;
|
| 2 |
+
using FlowAPI.Application.Interfaces;
|
| 3 |
+
using FlowAPI.Domain.Entities;
|
| 4 |
+
using System;
|
| 5 |
+
using System.Collections.Generic;
|
| 6 |
+
using System.Linq;
|
| 7 |
+
using System.Text.Json;
|
| 8 |
+
using System.Threading.Tasks;
|
| 9 |
+
|
| 10 |
+
namespace FlowAPI.Application.Services
|
| 11 |
+
{
|
| 12 |
+
public class TemplateService : ITemplateService
|
| 13 |
+
{
|
| 14 |
+
private const int MaxContentLength = 1_500_000;
|
| 15 |
+
private const int MaxTitleLength = 80;
|
| 16 |
+
private const int MaxDescriptionLength = 300;
|
| 17 |
+
|
| 18 |
+
private readonly ICustomTemplateRepository _repo;
|
| 19 |
+
private readonly IUserRepository _userRepo;
|
| 20 |
+
|
| 21 |
+
public TemplateService(ICustomTemplateRepository repo, IUserRepository userRepo)
|
| 22 |
+
{
|
| 23 |
+
_repo = repo;
|
| 24 |
+
_userRepo = userRepo;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
public async Task<IEnumerable<TemplateDto>> GetMineAsync(Guid userId)
|
| 28 |
+
{
|
| 29 |
+
var templates = await _repo.GetByUserIdAsync(userId);
|
| 30 |
+
return templates.Select(MapToDto);
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
public async Task<TemplateDto?> GetAsync(Guid id, Guid userId)
|
| 34 |
+
{
|
| 35 |
+
var template = await _repo.GetByIdAsync(id);
|
| 36 |
+
if (template is null || template.UserId != userId) return null;
|
| 37 |
+
return MapToDto(template);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
public async Task<TemplateDto> CreateAsync(CreateTemplateDto dto, Guid userId)
|
| 41 |
+
{
|
| 42 |
+
var user = await _userRepo.GetByIdAsync(userId) ?? throw new InvalidOperationException("User not found.");
|
| 43 |
+
|
| 44 |
+
if (!Plans.IsPlus(user) && await _repo.CountByUserIdAsync(userId) >= Plans.FreeMaxTemplates)
|
| 45 |
+
{
|
| 46 |
+
throw new InvalidOperationException($"Free plan allows up to {Plans.FreeMaxTemplates} saved templates. Upgrade to Plus for unlimited templates.");
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
var title = (dto.Title ?? string.Empty).Trim();
|
| 50 |
+
if (title.Length == 0) throw new InvalidOperationException("Template title is required.");
|
| 51 |
+
if (title.Length > MaxTitleLength) title = title[..MaxTitleLength];
|
| 52 |
+
|
| 53 |
+
ValidateContent(dto.Content);
|
| 54 |
+
|
| 55 |
+
var template = new CustomTemplate
|
| 56 |
+
{
|
| 57 |
+
Id = Guid.NewGuid(),
|
| 58 |
+
UserId = userId,
|
| 59 |
+
Title = title,
|
| 60 |
+
Description = Truncate(dto.Description, MaxDescriptionLength),
|
| 61 |
+
Category = string.IsNullOrWhiteSpace(dto.Category) ? "Мої" : dto.Category.Trim(),
|
| 62 |
+
Icon = string.IsNullOrWhiteSpace(dto.Icon) ? "LayoutTemplate" : dto.Icon.Trim(),
|
| 63 |
+
ContentJson = dto.Content,
|
| 64 |
+
CreatedAt = DateTime.UtcNow
|
| 65 |
+
};
|
| 66 |
+
|
| 67 |
+
return MapToDto(await _repo.CreateAsync(template));
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
public async Task<TemplateDto?> UpdateAsync(Guid id, UpdateTemplateDto dto, Guid userId)
|
| 71 |
+
{
|
| 72 |
+
var template = await _repo.GetByIdAsync(id);
|
| 73 |
+
if (template is null || template.UserId != userId) return null;
|
| 74 |
+
|
| 75 |
+
if (!string.IsNullOrWhiteSpace(dto.Title)) template.Title = Truncate(dto.Title, MaxTitleLength);
|
| 76 |
+
if (dto.Description != null) template.Description = Truncate(dto.Description, MaxDescriptionLength);
|
| 77 |
+
if (!string.IsNullOrWhiteSpace(dto.Category)) template.Category = dto.Category.Trim();
|
| 78 |
+
if (!string.IsNullOrWhiteSpace(dto.Icon)) template.Icon = dto.Icon.Trim();
|
| 79 |
+
|
| 80 |
+
return MapToDto(await _repo.UpdateAsync(template));
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
public async Task<bool> DeleteAsync(Guid id, Guid userId)
|
| 84 |
+
{
|
| 85 |
+
var template = await _repo.GetByIdAsync(id);
|
| 86 |
+
if (template is null || template.UserId != userId) return false;
|
| 87 |
+
return await _repo.DeleteAsync(id);
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
private static void ValidateContent(string content)
|
| 91 |
+
{
|
| 92 |
+
if (string.IsNullOrWhiteSpace(content)) throw new InvalidOperationException("Template content is empty.");
|
| 93 |
+
if (content.Length > MaxContentLength) throw new InvalidOperationException("Template is too large. Remove images and try again.");
|
| 94 |
+
|
| 95 |
+
try
|
| 96 |
+
{
|
| 97 |
+
using var doc = JsonDocument.Parse(content);
|
| 98 |
+
if (!doc.RootElement.TryGetProperty("nodes", out var nodes) || nodes.ValueKind != JsonValueKind.Array || nodes.GetArrayLength() == 0)
|
| 99 |
+
{
|
| 100 |
+
throw new InvalidOperationException("Template must contain at least one node.");
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
catch (JsonException)
|
| 104 |
+
{
|
| 105 |
+
throw new InvalidOperationException("Template content is not valid JSON.");
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
private static string Truncate(string? value, int max)
|
| 110 |
+
{
|
| 111 |
+
var trimmed = (value ?? string.Empty).Trim();
|
| 112 |
+
return trimmed.Length > max ? trimmed[..max] : trimmed;
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
private static TemplateDto MapToDto(CustomTemplate t) => new()
|
| 116 |
+
{
|
| 117 |
+
Id = t.Id,
|
| 118 |
+
Title = t.Title,
|
| 119 |
+
Description = t.Description,
|
| 120 |
+
Category = t.Category,
|
| 121 |
+
Icon = t.Icon,
|
| 122 |
+
Content = t.ContentJson,
|
| 123 |
+
CreatedAt = t.CreatedAt
|
| 124 |
+
};
|
| 125 |
+
}
|
| 126 |
+
}
|
|
@@ -36,6 +36,9 @@ namespace FlowAPI.Application.Services
|
|
| 36 |
|
| 37 |
public async Task<AuthResponseDto> RegisterAsync(CreateUserDto dto)
|
| 38 |
{
|
|
|
|
|
|
|
|
|
|
| 39 |
var existing = await _repo.GetByEmailAsync(dto.Email);
|
| 40 |
if (existing is not null)
|
| 41 |
throw new InvalidOperationException("User with this email already exists.");
|
|
@@ -60,9 +63,15 @@ namespace FlowAPI.Application.Services
|
|
| 60 |
public async Task<AuthResponseDto?> LoginAsync(LoginDto dto)
|
| 61 |
{
|
| 62 |
var user = await _repo.GetByEmailAsync(dto.Email);
|
| 63 |
-
if (user is null || string.IsNullOrEmpty(user.PasswordHash) ||
|
| 64 |
return null;
|
| 65 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
return new AuthResponseDto
|
| 67 |
{
|
| 68 |
User = MapToDto(user),
|
|
@@ -109,14 +118,13 @@ namespace FlowAPI.Application.Services
|
|
| 109 |
bool isAvatarUpdated = dto.AvatarUrl is not null && user.AvatarUrl != dto.AvatarUrl;
|
| 110 |
|
| 111 |
if (dto.DisplayName is not null) user.DisplayName = dto.DisplayName;
|
| 112 |
-
if (dto.IsPremium.HasValue) user.IsPremium = dto.IsPremium.Value;
|
| 113 |
if (dto.AvatarUrl is not null) user.AvatarUrl = dto.AvatarUrl;
|
| 114 |
-
if (dto.
|
| 115 |
{
|
| 116 |
-
|
| 117 |
-
|
|
|
|
| 118 |
}
|
| 119 |
-
if (!string.IsNullOrEmpty(dto.Password)) user.PasswordHash = HashPassword(dto.Password);
|
| 120 |
|
| 121 |
var updated = await _repo.UpdateAsync(user);
|
| 122 |
|
|
@@ -133,10 +141,36 @@ namespace FlowAPI.Application.Services
|
|
| 133 |
return await _repo.DeleteAsync(id);
|
| 134 |
}
|
| 135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
private static string HashPassword(string password)
|
| 137 |
{
|
| 138 |
-
var
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
}
|
| 141 |
|
| 142 |
private static UserResponseDto MapToDto(User user) => new()
|
|
@@ -147,8 +181,7 @@ namespace FlowAPI.Application.Services
|
|
| 147 |
IsPremium = user.IsPremium,
|
| 148 |
AvatarUrl = user.AvatarUrl,
|
| 149 |
CreatedAt = user.CreatedAt,
|
| 150 |
-
SubscriptionTier = user.SubscriptionTier
|
| 151 |
-
DailyAiGenerationsCount = user.DailyAiGenerationsCount
|
| 152 |
};
|
| 153 |
}
|
| 154 |
}
|
|
|
|
| 36 |
|
| 37 |
public async Task<AuthResponseDto> RegisterAsync(CreateUserDto dto)
|
| 38 |
{
|
| 39 |
+
if (string.IsNullOrWhiteSpace(dto.Email) || string.IsNullOrEmpty(dto.Password) || dto.Password.Length < MinPasswordLength)
|
| 40 |
+
throw new ArgumentException($"Email is required and password must be at least {MinPasswordLength} characters.");
|
| 41 |
+
|
| 42 |
var existing = await _repo.GetByEmailAsync(dto.Email);
|
| 43 |
if (existing is not null)
|
| 44 |
throw new InvalidOperationException("User with this email already exists.");
|
|
|
|
| 63 |
public async Task<AuthResponseDto?> LoginAsync(LoginDto dto)
|
| 64 |
{
|
| 65 |
var user = await _repo.GetByEmailAsync(dto.Email);
|
| 66 |
+
if (user is null || string.IsNullOrEmpty(user.PasswordHash) || !VerifyPassword(dto.Password, user.PasswordHash, out var needsRehash))
|
| 67 |
return null;
|
| 68 |
|
| 69 |
+
if (needsRehash)
|
| 70 |
+
{
|
| 71 |
+
user.PasswordHash = HashPassword(dto.Password);
|
| 72 |
+
await _repo.UpdateAsync(user);
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
return new AuthResponseDto
|
| 76 |
{
|
| 77 |
User = MapToDto(user),
|
|
|
|
| 118 |
bool isAvatarUpdated = dto.AvatarUrl is not null && user.AvatarUrl != dto.AvatarUrl;
|
| 119 |
|
| 120 |
if (dto.DisplayName is not null) user.DisplayName = dto.DisplayName;
|
|
|
|
| 121 |
if (dto.AvatarUrl is not null) user.AvatarUrl = dto.AvatarUrl;
|
| 122 |
+
if (!string.IsNullOrEmpty(dto.Password))
|
| 123 |
{
|
| 124 |
+
if (dto.Password.Length < MinPasswordLength)
|
| 125 |
+
throw new ArgumentException($"Password must be at least {MinPasswordLength} characters.");
|
| 126 |
+
user.PasswordHash = HashPassword(dto.Password);
|
| 127 |
}
|
|
|
|
| 128 |
|
| 129 |
var updated = await _repo.UpdateAsync(user);
|
| 130 |
|
|
|
|
| 141 |
return await _repo.DeleteAsync(id);
|
| 142 |
}
|
| 143 |
|
| 144 |
+
// Format: pbkdf2-sha256$<iterations>$<salt b64>$<hash b64>
|
| 145 |
+
private const string HashPrefix = "pbkdf2-sha256";
|
| 146 |
+
private const int HashIterations = 210_000;
|
| 147 |
+
private const int MinPasswordLength = 6;
|
| 148 |
+
|
| 149 |
private static string HashPassword(string password)
|
| 150 |
{
|
| 151 |
+
var salt = RandomNumberGenerator.GetBytes(16);
|
| 152 |
+
var hash = Rfc2898DeriveBytes.Pbkdf2(password, salt, HashIterations, HashAlgorithmName.SHA256, 32);
|
| 153 |
+
return $"{HashPrefix}${HashIterations}${Convert.ToBase64String(salt)}${Convert.ToBase64String(hash)}";
|
| 154 |
+
}
|
| 155 |
+
|
| 156 |
+
private static bool VerifyPassword(string password, string stored, out bool needsRehash)
|
| 157 |
+
{
|
| 158 |
+
needsRehash = false;
|
| 159 |
+
var parts = stored.Split('$');
|
| 160 |
+
if (parts.Length == 4 && parts[0] == HashPrefix && int.TryParse(parts[1], out var iterations))
|
| 161 |
+
{
|
| 162 |
+
var salt = Convert.FromBase64String(parts[2]);
|
| 163 |
+
var expected = Convert.FromBase64String(parts[3]);
|
| 164 |
+
var actual = Rfc2898DeriveBytes.Pbkdf2(password, salt, iterations, HashAlgorithmName.SHA256, expected.Length);
|
| 165 |
+
needsRehash = iterations < HashIterations;
|
| 166 |
+
return CryptographicOperations.FixedTimeEquals(actual, expected);
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
// Legacy unsalted SHA-256 hashes: accept once, then upgrade to PBKDF2
|
| 170 |
+
var legacy = Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(password)));
|
| 171 |
+
var ok = CryptographicOperations.FixedTimeEquals(Encoding.UTF8.GetBytes(legacy), Encoding.UTF8.GetBytes(stored));
|
| 172 |
+
needsRehash = ok;
|
| 173 |
+
return ok;
|
| 174 |
}
|
| 175 |
|
| 176 |
private static UserResponseDto MapToDto(User user) => new()
|
|
|
|
| 181 |
IsPremium = user.IsPremium,
|
| 182 |
AvatarUrl = user.AvatarUrl,
|
| 183 |
CreatedAt = user.CreatedAt,
|
| 184 |
+
SubscriptionTier = Plans.Normalize(user.SubscriptionTier)
|
|
|
|
| 185 |
};
|
| 186 |
}
|
| 187 |
}
|
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
using FlowAPI.Infrastructure.Data;
|
| 2 |
+
using Microsoft.EntityFrameworkCore.Infrastructure;
|
| 3 |
+
using Microsoft.EntityFrameworkCore.Migrations;
|
| 4 |
+
|
| 5 |
+
#nullable disable
|
| 6 |
+
|
| 7 |
+
namespace FlowAPI.Infrastructure.Migrations
|
| 8 |
+
{
|
| 9 |
+
/// <summary>
|
| 10 |
+
/// Data-only migration: the Pro and Ultra tiers were merged into a single Plus plan.
|
| 11 |
+
/// </summary>
|
| 12 |
+
[DbContext(typeof(AppDbContext))]
|
| 13 |
+
[Migration("20261017120000_MergeTiersIntoPlus")]
|
| 14 |
+
public partial class MergeTiersIntoPlus : Migration
|
| 15 |
+
{
|
| 16 |
+
/// <inheritdoc />
|
| 17 |
+
protected override void Up(MigrationBuilder migrationBuilder)
|
| 18 |
+
{
|
| 19 |
+
migrationBuilder.Sql("UPDATE Users SET SubscriptionTier = 'Plus', IsPremium = 1 WHERE SubscriptionTier IN ('Pro', 'Ultra');");
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
/// <inheritdoc />
|
| 23 |
+
protected override void Down(MigrationBuilder migrationBuilder)
|
| 24 |
+
{
|
| 25 |
+
migrationBuilder.Sql("UPDATE Users SET SubscriptionTier = 'Pro' WHERE SubscriptionTier = 'Plus';");
|
| 26 |
+
}
|
| 27 |
+
}
|
| 28 |
+
}
|
|
@@ -37,5 +37,26 @@ namespace FlowAPI.Infrastructure.Repositories
|
|
| 37 |
await _context.SaveChangesAsync();
|
| 38 |
return template;
|
| 39 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
}
|
| 41 |
}
|
|
|
|
| 37 |
await _context.SaveChangesAsync();
|
| 38 |
return template;
|
| 39 |
}
|
| 40 |
+
|
| 41 |
+
public async Task<CustomTemplate> UpdateAsync(CustomTemplate template)
|
| 42 |
+
{
|
| 43 |
+
_context.CustomTemplates.Update(template);
|
| 44 |
+
await _context.SaveChangesAsync();
|
| 45 |
+
return template;
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
public async Task<bool> DeleteAsync(Guid id)
|
| 49 |
+
{
|
| 50 |
+
var template = await _context.CustomTemplates.FindAsync(id);
|
| 51 |
+
if (template is null) return false;
|
| 52 |
+
_context.CustomTemplates.Remove(template);
|
| 53 |
+
await _context.SaveChangesAsync();
|
| 54 |
+
return true;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
public async Task<int> CountByUserIdAsync(Guid userId)
|
| 58 |
+
{
|
| 59 |
+
return await _context.CustomTemplates.CountAsync(t => t.UserId == userId);
|
| 60 |
+
}
|
| 61 |
}
|
| 62 |
}
|
|
@@ -1,77 +0,0 @@
|
|
| 1 |
-
using FlowAPI.Application.DTOs.AI;
|
| 2 |
-
using FlowAPI.Application.DTOs.Graph;
|
| 3 |
-
using FlowAPI.Application.Interfaces;
|
| 4 |
-
using Microsoft.AspNetCore.Mvc;
|
| 5 |
-
|
| 6 |
-
namespace FlowAPI.Controllers
|
| 7 |
-
{
|
| 8 |
-
[ApiController]
|
| 9 |
-
[Route("api/[controller]")]
|
| 10 |
-
public class AIController : ControllerBase
|
| 11 |
-
{
|
| 12 |
-
private readonly IAIService _aiService;
|
| 13 |
-
|
| 14 |
-
public AIController(IAIService aiService)
|
| 15 |
-
{
|
| 16 |
-
_aiService = aiService;
|
| 17 |
-
}
|
| 18 |
-
|
| 19 |
-
[HttpPost("generate-alternative")]
|
| 20 |
-
public async Task<ActionResult<AIPathResponseDto>> GenerateAlternative([FromBody] GenerateAlternativeRequestDto request)
|
| 21 |
-
{
|
| 22 |
-
try
|
| 23 |
-
{
|
| 24 |
-
var response = await _aiService.GenerateAlternativePathAsync(request);
|
| 25 |
-
return Ok(response);
|
| 26 |
-
}
|
| 27 |
-
catch (UnauthorizedAccessException)
|
| 28 |
-
{
|
| 29 |
-
return StatusCode(403, new { message = "Premium subscription required for AI generation." });
|
| 30 |
-
}
|
| 31 |
-
catch (InvalidOperationException ex)
|
| 32 |
-
{
|
| 33 |
-
return StatusCode(403, new { message = ex.Message });
|
| 34 |
-
}
|
| 35 |
-
catch (Exception ex)
|
| 36 |
-
{
|
| 37 |
-
return BadRequest(new { message = ex.Message });
|
| 38 |
-
}
|
| 39 |
-
}
|
| 40 |
-
|
| 41 |
-
[HttpPost("generate-goal")]
|
| 42 |
-
public async Task<ActionResult<FullGraphResponseDto>> GenerateGoal([FromBody] GenerateGoalGraphRequestDto request)
|
| 43 |
-
{
|
| 44 |
-
try
|
| 45 |
-
{
|
| 46 |
-
var response = await _aiService.GenerateGoalGraphAsync(request);
|
| 47 |
-
return Ok(response);
|
| 48 |
-
}
|
| 49 |
-
catch (InvalidOperationException ex)
|
| 50 |
-
{
|
| 51 |
-
return StatusCode(403, new { message = ex.Message });
|
| 52 |
-
}
|
| 53 |
-
catch (Exception ex)
|
| 54 |
-
{
|
| 55 |
-
return BadRequest(new { message = ex.Message });
|
| 56 |
-
}
|
| 57 |
-
}
|
| 58 |
-
|
| 59 |
-
[HttpPost("assist")]
|
| 60 |
-
public async Task<ActionResult<AICanvasAssistResponseDto>> CanvasAssist([FromBody] AICanvasAssistRequestDto request)
|
| 61 |
-
{
|
| 62 |
-
try
|
| 63 |
-
{
|
| 64 |
-
var response = await _aiService.CanvasAssistAsync(request);
|
| 65 |
-
return Ok(response);
|
| 66 |
-
}
|
| 67 |
-
catch (InvalidOperationException ex)
|
| 68 |
-
{
|
| 69 |
-
return StatusCode(403, new { message = ex.Message });
|
| 70 |
-
}
|
| 71 |
-
catch (Exception ex)
|
| 72 |
-
{
|
| 73 |
-
return BadRequest(new { message = ex.Message });
|
| 74 |
-
}
|
| 75 |
-
}
|
| 76 |
-
}
|
| 77 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -30,7 +30,6 @@ namespace FlowAPI.Controllers
|
|
| 30 |
}
|
| 31 |
|
| 32 |
[HttpPost("seed")]
|
| 33 |
-
[AllowAnonymous] // Allowing anonymous for easy dev setup. Can be secured later.
|
| 34 |
public async Task<IActionResult> SeedAchievements()
|
| 35 |
{
|
| 36 |
await _achievementService.SeedAchievementsAsync();
|
|
|
|
| 30 |
}
|
| 31 |
|
| 32 |
[HttpPost("seed")]
|
|
|
|
| 33 |
public async Task<IActionResult> SeedAchievements()
|
| 34 |
{
|
| 35 |
await _achievementService.SeedAchievementsAsync();
|
|
@@ -40,38 +40,6 @@ namespace FlowAPI.Controllers
|
|
| 40 |
_config = config;
|
| 41 |
}
|
| 42 |
|
| 43 |
-
[AllowAnonymous]
|
| 44 |
-
[HttpGet("token")]
|
| 45 |
-
public async Task<IActionResult> GetToken()
|
| 46 |
-
{
|
| 47 |
-
// First check if the user exists by email to prevent Unique Index violations
|
| 48 |
-
var user = await _userRepo.GetByEmailAsync("dan9228335@gmail.com");
|
| 49 |
-
if (user == null)
|
| 50 |
-
{
|
| 51 |
-
var userId = Guid.Parse("33d1ae31-bf51-4b12-89d0-8e574e7916ab");
|
| 52 |
-
// Check if the hardcoded ID is somehow already in use
|
| 53 |
-
var existingById = await _userRepo.GetByIdAsync(userId);
|
| 54 |
-
if (existingById != null)
|
| 55 |
-
{
|
| 56 |
-
user = existingById;
|
| 57 |
-
}
|
| 58 |
-
else
|
| 59 |
-
{
|
| 60 |
-
user = new User
|
| 61 |
-
{
|
| 62 |
-
Id = userId,
|
| 63 |
-
Email = "dan9228335@gmail.com",
|
| 64 |
-
DisplayName = "Dodikuser",
|
| 65 |
-
PasswordHash = "",
|
| 66 |
-
CreatedAt = DateTime.UtcNow
|
| 67 |
-
};
|
| 68 |
-
await _userRepo.CreateAsync(user);
|
| 69 |
-
}
|
| 70 |
-
}
|
| 71 |
-
var token = _tokenService.CreateToken(user);
|
| 72 |
-
return Ok(new { token });
|
| 73 |
-
}
|
| 74 |
-
|
| 75 |
[HttpPost("create")]
|
| 76 |
public async Task<IActionResult> CreateFromAgent([FromBody] QuestSchemaDto schema)
|
| 77 |
{
|
|
|
|
| 40 |
_config = config;
|
| 41 |
}
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
[HttpPost("create")]
|
| 44 |
public async Task<IActionResult> CreateFromAgent([FromBody] QuestSchemaDto schema)
|
| 45 |
{
|
|
@@ -1,38 +1,55 @@
|
|
| 1 |
using FlowAPI.Application.DTOs.Edge;
|
| 2 |
using FlowAPI.Application.Interfaces;
|
|
|
|
| 3 |
using Microsoft.AspNetCore.Mvc;
|
|
|
|
| 4 |
|
| 5 |
namespace FlowAPI.Controllers
|
| 6 |
{
|
| 7 |
[ApiController]
|
|
|
|
| 8 |
[Route("api/[controller]")]
|
| 9 |
public class EdgesController : ControllerBase
|
| 10 |
{
|
| 11 |
private readonly IEdgeService _service;
|
|
|
|
| 12 |
|
| 13 |
-
public EdgesController(IEdgeService service)
|
| 14 |
{
|
| 15 |
_service = service;
|
|
|
|
| 16 |
}
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
[HttpGet("graph/{graphId:guid}")]
|
| 19 |
public async Task<ActionResult<IEnumerable<EdgeResponseDto>>> GetAllByGraphId(Guid graphId)
|
| 20 |
{
|
| 21 |
-
|
| 22 |
-
return Ok(
|
| 23 |
}
|
| 24 |
|
| 25 |
[HttpGet("{id:guid}")]
|
| 26 |
public async Task<ActionResult<EdgeResponseDto>> GetById(Guid id)
|
| 27 |
{
|
| 28 |
var edge = await _service.GetByIdAsync(id);
|
| 29 |
-
if (edge is null) return NotFound();
|
| 30 |
return Ok(edge);
|
| 31 |
}
|
| 32 |
|
| 33 |
[HttpPost]
|
| 34 |
public async Task<ActionResult<EdgeResponseDto>> Create([FromBody] CreateEdgeDto dto)
|
| 35 |
{
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
try
|
| 37 |
{
|
| 38 |
var edge = await _service.CreateAsync(dto);
|
|
@@ -47,8 +64,13 @@ namespace FlowAPI.Controllers
|
|
| 47 |
[HttpDelete("{id:guid}")]
|
| 48 |
public async Task<IActionResult> Delete(Guid id)
|
| 49 |
{
|
| 50 |
-
var
|
| 51 |
-
if (
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
return NoContent();
|
| 53 |
}
|
| 54 |
}
|
|
|
|
| 1 |
using FlowAPI.Application.DTOs.Edge;
|
| 2 |
using FlowAPI.Application.Interfaces;
|
| 3 |
+
using Microsoft.AspNetCore.Authorization;
|
| 4 |
using Microsoft.AspNetCore.Mvc;
|
| 5 |
+
using System.Security.Claims;
|
| 6 |
|
| 7 |
namespace FlowAPI.Controllers
|
| 8 |
{
|
| 9 |
[ApiController]
|
| 10 |
+
[Authorize]
|
| 11 |
[Route("api/[controller]")]
|
| 12 |
public class EdgesController : ControllerBase
|
| 13 |
{
|
| 14 |
private readonly IEdgeService _service;
|
| 15 |
+
private readonly IGraphService _graphService;
|
| 16 |
|
| 17 |
+
public EdgesController(IEdgeService service, IGraphService graphService)
|
| 18 |
{
|
| 19 |
_service = service;
|
| 20 |
+
_graphService = graphService;
|
| 21 |
}
|
| 22 |
|
| 23 |
+
private Guid CurrentUserId =>
|
| 24 |
+
Guid.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
|
| 25 |
+
|
| 26 |
+
private async Task<string?> GetPermissionAsync(Guid graphId) =>
|
| 27 |
+
(await _graphService.GetByIdAsync(graphId, CurrentUserId))?.Permission;
|
| 28 |
+
|
| 29 |
+
private static bool CanWrite(string? permission) => permission is "Owner" or "Edit";
|
| 30 |
+
|
| 31 |
[HttpGet("graph/{graphId:guid}")]
|
| 32 |
public async Task<ActionResult<IEnumerable<EdgeResponseDto>>> GetAllByGraphId(Guid graphId)
|
| 33 |
{
|
| 34 |
+
if (await GetPermissionAsync(graphId) is null) return NotFound();
|
| 35 |
+
return Ok(await _service.GetAllByGraphIdAsync(graphId));
|
| 36 |
}
|
| 37 |
|
| 38 |
[HttpGet("{id:guid}")]
|
| 39 |
public async Task<ActionResult<EdgeResponseDto>> GetById(Guid id)
|
| 40 |
{
|
| 41 |
var edge = await _service.GetByIdAsync(id);
|
| 42 |
+
if (edge is null || await GetPermissionAsync(edge.GraphId) is null) return NotFound();
|
| 43 |
return Ok(edge);
|
| 44 |
}
|
| 45 |
|
| 46 |
[HttpPost]
|
| 47 |
public async Task<ActionResult<EdgeResponseDto>> Create([FromBody] CreateEdgeDto dto)
|
| 48 |
{
|
| 49 |
+
var permission = await GetPermissionAsync(dto.GraphId);
|
| 50 |
+
if (permission is null) return NotFound();
|
| 51 |
+
if (!CanWrite(permission)) return Forbid();
|
| 52 |
+
|
| 53 |
try
|
| 54 |
{
|
| 55 |
var edge = await _service.CreateAsync(dto);
|
|
|
|
| 64 |
[HttpDelete("{id:guid}")]
|
| 65 |
public async Task<IActionResult> Delete(Guid id)
|
| 66 |
{
|
| 67 |
+
var edge = await _service.GetByIdAsync(id);
|
| 68 |
+
if (edge is null) return NotFound();
|
| 69 |
+
var permission = await GetPermissionAsync(edge.GraphId);
|
| 70 |
+
if (permission is null) return NotFound();
|
| 71 |
+
if (!CanWrite(permission)) return Forbid();
|
| 72 |
+
|
| 73 |
+
if (!await _service.DeleteAsync(id)) return NotFound();
|
| 74 |
return NoContent();
|
| 75 |
}
|
| 76 |
}
|
|
@@ -1,6 +1,5 @@
|
|
| 1 |
using FlowAPI.Application.DTOs.Graph;
|
| 2 |
using FlowAPI.Application.Interfaces;
|
| 3 |
-
using FlowAPI.Application.Services;
|
| 4 |
using Microsoft.AspNetCore.Authorization;
|
| 5 |
using Microsoft.AspNetCore.Mvc;
|
| 6 |
using System;
|
|
@@ -31,30 +30,6 @@ namespace FlowAPI.Controllers
|
|
| 31 |
}
|
| 32 |
}
|
| 33 |
|
| 34 |
-
[HttpGet("templates")]
|
| 35 |
-
public async Task<ActionResult<IEnumerable<TemplateInfoDto>>> GetTemplates()
|
| 36 |
-
{
|
| 37 |
-
var templates = TemplateLibrary.GetTemplateInfos().ToList();
|
| 38 |
-
|
| 39 |
-
var userIdStr = User.FindFirst(ClaimTypes.NameIdentifier)?.Value;
|
| 40 |
-
if (Guid.TryParse(userIdStr, out var userId))
|
| 41 |
-
{
|
| 42 |
-
var customTemplates = await _service.GetCustomTemplatesAsync(userId);
|
| 43 |
-
foreach (var t in customTemplates)
|
| 44 |
-
{
|
| 45 |
-
templates.Add(new TemplateInfoDto
|
| 46 |
-
{
|
| 47 |
-
Key = t.Id.ToString(),
|
| 48 |
-
Title = t.Title,
|
| 49 |
-
Description = t.Description,
|
| 50 |
-
Icon = t.Icon,
|
| 51 |
-
Category = t.Category
|
| 52 |
-
});
|
| 53 |
-
}
|
| 54 |
-
}
|
| 55 |
-
return Ok(templates);
|
| 56 |
-
}
|
| 57 |
-
|
| 58 |
[HttpGet("user/{userId:guid}")]
|
| 59 |
public async Task<ActionResult<IEnumerable<GraphResponseDto>>> GetAllByUserId(Guid userId)
|
| 60 |
{
|
|
@@ -173,31 +148,5 @@ namespace FlowAPI.Controllers
|
|
| 173 |
if (!result) return NotFound();
|
| 174 |
return NoContent();
|
| 175 |
}
|
| 176 |
-
|
| 177 |
-
[HttpPost("{id:guid}/save-as-template")]
|
| 178 |
-
public async Task<IActionResult> SaveAsTemplate(Guid id, [FromBody] SaveTemplateDto dto)
|
| 179 |
-
{
|
| 180 |
-
if (CurrentUserId == Guid.Empty) return Unauthorized();
|
| 181 |
-
|
| 182 |
-
try
|
| 183 |
-
{
|
| 184 |
-
var template = await _service.SaveAsTemplateAsync(id, CurrentUserId, dto.Title, dto.Description);
|
| 185 |
-
return Ok(new { message = "Template saved successfully", templateId = template.Id });
|
| 186 |
-
}
|
| 187 |
-
catch (InvalidOperationException ex)
|
| 188 |
-
{
|
| 189 |
-
return BadRequest(new { message = ex.Message });
|
| 190 |
-
}
|
| 191 |
-
catch (Exception ex)
|
| 192 |
-
{
|
| 193 |
-
return BadRequest(new { message = ex.Message });
|
| 194 |
-
}
|
| 195 |
-
}
|
| 196 |
-
}
|
| 197 |
-
|
| 198 |
-
public class SaveTemplateDto
|
| 199 |
-
{
|
| 200 |
-
public string Title { get; set; } = string.Empty;
|
| 201 |
-
public string Description { get; set; } = string.Empty;
|
| 202 |
}
|
| 203 |
}
|
|
|
|
| 1 |
using FlowAPI.Application.DTOs.Graph;
|
| 2 |
using FlowAPI.Application.Interfaces;
|
|
|
|
| 3 |
using Microsoft.AspNetCore.Authorization;
|
| 4 |
using Microsoft.AspNetCore.Mvc;
|
| 5 |
using System;
|
|
|
|
| 30 |
}
|
| 31 |
}
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
[HttpGet("user/{userId:guid}")]
|
| 34 |
public async Task<ActionResult<IEnumerable<GraphResponseDto>>> GetAllByUserId(Guid userId)
|
| 35 |
{
|
|
|
|
| 148 |
if (!result) return NotFound();
|
| 149 |
return NoContent();
|
| 150 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
}
|
| 152 |
}
|
|
@@ -1,10 +1,13 @@
|
|
| 1 |
using FlowAPI.Application.DTOs.Habit;
|
| 2 |
using FlowAPI.Application.Interfaces;
|
|
|
|
| 3 |
using Microsoft.AspNetCore.Mvc;
|
|
|
|
| 4 |
|
| 5 |
namespace FlowAPI.Controllers
|
| 6 |
{
|
| 7 |
[ApiController]
|
|
|
|
| 8 |
[Route("api/[controller]")]
|
| 9 |
public class HabitsController : ControllerBase
|
| 10 |
{
|
|
@@ -15,20 +18,24 @@ namespace FlowAPI.Controllers
|
|
| 15 |
_service = service;
|
| 16 |
}
|
| 17 |
|
|
|
|
|
|
|
|
|
|
| 18 |
[HttpGet("user/{userId:guid}")]
|
| 19 |
public async Task<ActionResult<IEnumerable<HabitRecordResponseDto>>> GetAllByUserId(Guid userId)
|
| 20 |
{
|
| 21 |
-
|
| 22 |
-
return Ok(
|
| 23 |
}
|
| 24 |
|
| 25 |
[HttpPost("record")]
|
| 26 |
public async Task<ActionResult<HabitRecordResponseDto>> Record([FromBody] CreateHabitRecordDto dto)
|
| 27 |
{
|
|
|
|
|
|
|
| 28 |
try
|
| 29 |
{
|
| 30 |
-
|
| 31 |
-
return Ok(record);
|
| 32 |
}
|
| 33 |
catch (InvalidOperationException ex)
|
| 34 |
{
|
|
@@ -39,8 +46,8 @@ namespace FlowAPI.Controllers
|
|
| 39 |
[HttpGet("streak/{userId:guid}/{habitName}")]
|
| 40 |
public async Task<ActionResult<int>> GetStreak(Guid userId, string habitName)
|
| 41 |
{
|
| 42 |
-
|
| 43 |
-
return Ok(
|
| 44 |
}
|
| 45 |
}
|
| 46 |
}
|
|
|
|
| 1 |
using FlowAPI.Application.DTOs.Habit;
|
| 2 |
using FlowAPI.Application.Interfaces;
|
| 3 |
+
using Microsoft.AspNetCore.Authorization;
|
| 4 |
using Microsoft.AspNetCore.Mvc;
|
| 5 |
+
using System.Security.Claims;
|
| 6 |
|
| 7 |
namespace FlowAPI.Controllers
|
| 8 |
{
|
| 9 |
[ApiController]
|
| 10 |
+
[Authorize]
|
| 11 |
[Route("api/[controller]")]
|
| 12 |
public class HabitsController : ControllerBase
|
| 13 |
{
|
|
|
|
| 18 |
_service = service;
|
| 19 |
}
|
| 20 |
|
| 21 |
+
private Guid CurrentUserId =>
|
| 22 |
+
Guid.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
|
| 23 |
+
|
| 24 |
[HttpGet("user/{userId:guid}")]
|
| 25 |
public async Task<ActionResult<IEnumerable<HabitRecordResponseDto>>> GetAllByUserId(Guid userId)
|
| 26 |
{
|
| 27 |
+
if (userId != CurrentUserId) return Forbid();
|
| 28 |
+
return Ok(await _service.GetAllByUserIdAsync(userId));
|
| 29 |
}
|
| 30 |
|
| 31 |
[HttpPost("record")]
|
| 32 |
public async Task<ActionResult<HabitRecordResponseDto>> Record([FromBody] CreateHabitRecordDto dto)
|
| 33 |
{
|
| 34 |
+
// Always record for the authenticated user, whatever the body says
|
| 35 |
+
dto.UserId = CurrentUserId;
|
| 36 |
try
|
| 37 |
{
|
| 38 |
+
return Ok(await _service.RecordHabitAsync(dto));
|
|
|
|
| 39 |
}
|
| 40 |
catch (InvalidOperationException ex)
|
| 41 |
{
|
|
|
|
| 46 |
[HttpGet("streak/{userId:guid}/{habitName}")]
|
| 47 |
public async Task<ActionResult<int>> GetStreak(Guid userId, string habitName)
|
| 48 |
{
|
| 49 |
+
if (userId != CurrentUserId) return Forbid();
|
| 50 |
+
return Ok(await _service.GetStreakAsync(userId, habitName));
|
| 51 |
}
|
| 52 |
}
|
| 53 |
}
|
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
using Microsoft.AspNetCore.Mvc;
|
| 2 |
+
|
| 3 |
+
namespace FlowAPI.Controllers
|
| 4 |
+
{
|
| 5 |
+
/// <summary>
|
| 6 |
+
/// Lightweight liveness endpoint; the web client pings it to keep the HF Space awake.
|
| 7 |
+
/// </summary>
|
| 8 |
+
[ApiController]
|
| 9 |
+
[Route("api/[controller]")]
|
| 10 |
+
public class HealthController : ControllerBase
|
| 11 |
+
{
|
| 12 |
+
[HttpGet]
|
| 13 |
+
public IActionResult Get() => Ok(new { status = "ok" });
|
| 14 |
+
}
|
| 15 |
+
}
|
|
@@ -1,65 +1,75 @@
|
|
| 1 |
using FlowAPI.Application.Interfaces;
|
|
|
|
|
|
|
| 2 |
using Microsoft.AspNetCore.Mvc;
|
|
|
|
| 3 |
|
| 4 |
namespace FlowAPI.Controllers
|
| 5 |
{
|
| 6 |
[ApiController]
|
|
|
|
| 7 |
[Route("api/[controller]")]
|
| 8 |
public class PaymentsController : ControllerBase
|
| 9 |
{
|
| 10 |
private readonly IPaymentService _paymentService;
|
| 11 |
private readonly IUserRepository _userRepo;
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
public PaymentsController(IPaymentService paymentService, IUserRepository userRepo)
|
| 14 |
{
|
| 15 |
_paymentService = paymentService;
|
| 16 |
_userRepo = userRepo;
|
|
|
|
|
|
|
| 17 |
}
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
| 21 |
{
|
| 22 |
-
|
|
|
|
| 23 |
return Ok(new { checkoutUrl = url });
|
| 24 |
}
|
| 25 |
|
|
|
|
|
|
|
|
|
|
| 26 |
[HttpPost("webhook")]
|
| 27 |
-
public
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
{
|
| 29 |
-
|
| 30 |
-
var signature = Request.Headers["Stripe-Signature"];
|
| 31 |
|
| 32 |
-
var
|
| 33 |
-
if (
|
| 34 |
-
|
| 35 |
-
|
|
|
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
{
|
| 40 |
-
var user = await _userRepo.GetByIdAsync(userId);
|
| 41 |
-
if (user == null) return NotFound("User not found.");
|
| 42 |
|
| 43 |
-
|
| 44 |
-
if (upperTier != "Free" && upperTier != "Pro" && upperTier != "Ultra")
|
| 45 |
{
|
| 46 |
-
return
|
| 47 |
}
|
| 48 |
|
| 49 |
-
user.SubscriptionTier =
|
| 50 |
-
user.IsPremium =
|
| 51 |
await _userRepo.UpdateAsync(user);
|
| 52 |
|
| 53 |
-
return Ok(
|
| 54 |
-
id = user.Id,
|
| 55 |
-
email = user.Email,
|
| 56 |
-
displayName = user.DisplayName,
|
| 57 |
-
isPremium = user.IsPremium,
|
| 58 |
-
avatarUrl = user.AvatarUrl,
|
| 59 |
-
createdAt = user.CreatedAt,
|
| 60 |
-
subscriptionTier = user.SubscriptionTier,
|
| 61 |
-
dailyAiGenerationsCount = user.DailyAiGenerationsCount
|
| 62 |
-
});
|
| 63 |
}
|
| 64 |
}
|
| 65 |
|
|
|
|
| 1 |
using FlowAPI.Application.Interfaces;
|
| 2 |
+
using FlowAPI.Application.Services;
|
| 3 |
+
using Microsoft.AspNetCore.Authorization;
|
| 4 |
using Microsoft.AspNetCore.Mvc;
|
| 5 |
+
using System.Security.Claims;
|
| 6 |
|
| 7 |
namespace FlowAPI.Controllers
|
| 8 |
{
|
| 9 |
[ApiController]
|
| 10 |
+
[Authorize]
|
| 11 |
[Route("api/[controller]")]
|
| 12 |
public class PaymentsController : ControllerBase
|
| 13 |
{
|
| 14 |
private readonly IPaymentService _paymentService;
|
| 15 |
private readonly IUserRepository _userRepo;
|
| 16 |
+
private readonly IUserService _userService;
|
| 17 |
+
private readonly IConfiguration _config;
|
| 18 |
|
| 19 |
+
public PaymentsController(IPaymentService paymentService, IUserRepository userRepo, IUserService userService, IConfiguration config)
|
| 20 |
{
|
| 21 |
_paymentService = paymentService;
|
| 22 |
_userRepo = userRepo;
|
| 23 |
+
_userService = userService;
|
| 24 |
+
_config = config;
|
| 25 |
}
|
| 26 |
|
| 27 |
+
private Guid CurrentUserId =>
|
| 28 |
+
Guid.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
|
| 29 |
+
|
| 30 |
+
[HttpPost("create-checkout-session")]
|
| 31 |
+
public async Task<ActionResult<object>> CreateCheckoutSession()
|
| 32 |
{
|
| 33 |
+
if (CurrentUserId == Guid.Empty) return Unauthorized();
|
| 34 |
+
var url = await _paymentService.CreateCheckoutSessionAsync(CurrentUserId);
|
| 35 |
return Ok(new { checkoutUrl = url });
|
| 36 |
}
|
| 37 |
|
| 38 |
+
// Disabled until Stripe signature verification is implemented: accepting unsigned
|
| 39 |
+
// webhooks would let anyone fake a successful payment.
|
| 40 |
+
[AllowAnonymous]
|
| 41 |
[HttpPost("webhook")]
|
| 42 |
+
public IActionResult Webhook() => StatusCode(StatusCodes.Status501NotImplemented);
|
| 43 |
+
|
| 44 |
+
/// <summary>
|
| 45 |
+
/// Switches the current user's plan. Downgrading to Free is always allowed.
|
| 46 |
+
/// Upgrading to Plus requires a payment, so without a payment provider it is only
|
| 47 |
+
/// allowed when Payments:AllowFreeUpgrade is true (local development / demos).
|
| 48 |
+
/// </summary>
|
| 49 |
+
[HttpPost("change-tier")]
|
| 50 |
+
public async Task<IActionResult> ChangeTier([FromBody] ChangeTierDto dto)
|
| 51 |
{
|
| 52 |
+
if (CurrentUserId == Guid.Empty) return Unauthorized();
|
|
|
|
| 53 |
|
| 54 |
+
var plan = dto.Tier?.Trim();
|
| 55 |
+
if (!Plans.IsValid(plan))
|
| 56 |
+
{
|
| 57 |
+
return BadRequest(new { message = $"Invalid plan. Must be '{Plans.Free}' or '{Plans.Plus}'." });
|
| 58 |
+
}
|
| 59 |
|
| 60 |
+
var user = await _userRepo.GetByIdAsync(CurrentUserId);
|
| 61 |
+
if (user == null) return NotFound(new { message = "User not found." });
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
+
if (plan == Plans.Plus && !Plans.IsPlus(user) && !_config.GetValue<bool>("Payments:AllowFreeUpgrade"))
|
|
|
|
| 64 |
{
|
| 65 |
+
return StatusCode(StatusCodes.Status402PaymentRequired, new { message = "Online payments are not connected yet." });
|
| 66 |
}
|
| 67 |
|
| 68 |
+
user.SubscriptionTier = plan!;
|
| 69 |
+
user.IsPremium = plan == Plans.Plus;
|
| 70 |
await _userRepo.UpdateAsync(user);
|
| 71 |
|
| 72 |
+
return Ok(await _userService.GetByIdAsync(user.Id));
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
}
|
| 74 |
}
|
| 75 |
|
|
@@ -64,9 +64,11 @@ namespace FlowAPI.Controllers
|
|
| 64 |
return true;
|
| 65 |
}
|
| 66 |
|
|
|
|
| 67 |
[HttpPost("{userId:guid}")]
|
| 68 |
public async Task<ActionResult<SyncResponseDto>> Sync(Guid userId, [FromBody] SyncRequestDto request)
|
| 69 |
{
|
|
|
|
| 70 |
var response = await _syncService.SyncChangesAsync(userId, request);
|
| 71 |
return Ok(response);
|
| 72 |
}
|
|
|
|
| 64 |
return true;
|
| 65 |
}
|
| 66 |
|
| 67 |
+
[Authorize]
|
| 68 |
[HttpPost("{userId:guid}")]
|
| 69 |
public async Task<ActionResult<SyncResponseDto>> Sync(Guid userId, [FromBody] SyncRequestDto request)
|
| 70 |
{
|
| 71 |
+
if (userId != CurrentUserId) return Forbid();
|
| 72 |
var response = await _syncService.SyncChangesAsync(userId, request);
|
| 73 |
return Ok(response);
|
| 74 |
}
|
|
@@ -1,38 +1,56 @@
|
|
| 1 |
using FlowAPI.Application.DTOs.TaskNode;
|
| 2 |
using FlowAPI.Application.Interfaces;
|
|
|
|
| 3 |
using Microsoft.AspNetCore.Mvc;
|
|
|
|
| 4 |
|
| 5 |
namespace FlowAPI.Controllers
|
| 6 |
{
|
| 7 |
[ApiController]
|
|
|
|
| 8 |
[Route("api/[controller]")]
|
| 9 |
public class TaskNodesController : ControllerBase
|
| 10 |
{
|
| 11 |
private readonly ITaskNodeService _service;
|
|
|
|
| 12 |
|
| 13 |
-
public TaskNodesController(ITaskNodeService service)
|
| 14 |
{
|
| 15 |
_service = service;
|
|
|
|
| 16 |
}
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
[HttpGet("graph/{graphId:guid}")]
|
| 19 |
public async Task<ActionResult<IEnumerable<TaskNodeResponseDto>>> GetAllByGraphId(Guid graphId)
|
| 20 |
{
|
| 21 |
-
|
| 22 |
-
return Ok(
|
| 23 |
}
|
| 24 |
|
| 25 |
[HttpGet("{id:guid}")]
|
| 26 |
public async Task<ActionResult<TaskNodeResponseDto>> GetById(Guid id)
|
| 27 |
{
|
| 28 |
var node = await _service.GetByIdAsync(id);
|
| 29 |
-
if (node is null) return NotFound();
|
| 30 |
return Ok(node);
|
| 31 |
}
|
| 32 |
|
| 33 |
[HttpPost]
|
| 34 |
public async Task<ActionResult<TaskNodeResponseDto>> Create([FromBody] CreateTaskNodeDto dto)
|
| 35 |
{
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
try
|
| 37 |
{
|
| 38 |
var node = await _service.CreateAsync(dto);
|
|
@@ -47,6 +65,12 @@ namespace FlowAPI.Controllers
|
|
| 47 |
[HttpPut("{id:guid}")]
|
| 48 |
public async Task<ActionResult<TaskNodeResponseDto>> Update(Guid id, [FromBody] UpdateTaskNodeDto dto)
|
| 49 |
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
var node = await _service.UpdateAsync(id, dto);
|
| 51 |
if (node is null) return NotFound();
|
| 52 |
return Ok(node);
|
|
@@ -55,20 +79,23 @@ namespace FlowAPI.Controllers
|
|
| 55 |
[HttpDelete("{id:guid}")]
|
| 56 |
public async Task<IActionResult> Delete(Guid id)
|
| 57 |
{
|
| 58 |
-
var
|
| 59 |
-
if (
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
return NoContent();
|
| 61 |
}
|
| 62 |
|
| 63 |
[HttpGet("{id:guid}/data")]
|
| 64 |
public async Task<ActionResult<object>> GetNodeData(Guid id)
|
| 65 |
{
|
|
|
|
|
|
|
|
|
|
| 66 |
var nodeData = await _service.GetNodeDataAsync(id);
|
| 67 |
-
if (nodeData is null)
|
| 68 |
-
{
|
| 69 |
-
var node = await _service.GetByIdAsync(id);
|
| 70 |
-
if (node is null) return NotFound();
|
| 71 |
-
}
|
| 72 |
return Ok(new { data = nodeData });
|
| 73 |
}
|
| 74 |
}
|
|
|
|
| 1 |
using FlowAPI.Application.DTOs.TaskNode;
|
| 2 |
using FlowAPI.Application.Interfaces;
|
| 3 |
+
using Microsoft.AspNetCore.Authorization;
|
| 4 |
using Microsoft.AspNetCore.Mvc;
|
| 5 |
+
using System.Security.Claims;
|
| 6 |
|
| 7 |
namespace FlowAPI.Controllers
|
| 8 |
{
|
| 9 |
[ApiController]
|
| 10 |
+
[Authorize]
|
| 11 |
[Route("api/[controller]")]
|
| 12 |
public class TaskNodesController : ControllerBase
|
| 13 |
{
|
| 14 |
private readonly ITaskNodeService _service;
|
| 15 |
+
private readonly IGraphService _graphService;
|
| 16 |
|
| 17 |
+
public TaskNodesController(ITaskNodeService service, IGraphService graphService)
|
| 18 |
{
|
| 19 |
_service = service;
|
| 20 |
+
_graphService = graphService;
|
| 21 |
}
|
| 22 |
|
| 23 |
+
private Guid CurrentUserId =>
|
| 24 |
+
Guid.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
|
| 25 |
+
|
| 26 |
+
// null = no access; otherwise the caller's permission on the board ("Owner", "Edit", "Read")
|
| 27 |
+
private async Task<string?> GetPermissionAsync(Guid graphId) =>
|
| 28 |
+
(await _graphService.GetByIdAsync(graphId, CurrentUserId))?.Permission;
|
| 29 |
+
|
| 30 |
+
private static bool CanWrite(string? permission) => permission is "Owner" or "Edit";
|
| 31 |
+
|
| 32 |
[HttpGet("graph/{graphId:guid}")]
|
| 33 |
public async Task<ActionResult<IEnumerable<TaskNodeResponseDto>>> GetAllByGraphId(Guid graphId)
|
| 34 |
{
|
| 35 |
+
if (await GetPermissionAsync(graphId) is null) return NotFound();
|
| 36 |
+
return Ok(await _service.GetAllByGraphIdAsync(graphId));
|
| 37 |
}
|
| 38 |
|
| 39 |
[HttpGet("{id:guid}")]
|
| 40 |
public async Task<ActionResult<TaskNodeResponseDto>> GetById(Guid id)
|
| 41 |
{
|
| 42 |
var node = await _service.GetByIdAsync(id);
|
| 43 |
+
if (node is null || await GetPermissionAsync(node.GraphId) is null) return NotFound();
|
| 44 |
return Ok(node);
|
| 45 |
}
|
| 46 |
|
| 47 |
[HttpPost]
|
| 48 |
public async Task<ActionResult<TaskNodeResponseDto>> Create([FromBody] CreateTaskNodeDto dto)
|
| 49 |
{
|
| 50 |
+
var permission = await GetPermissionAsync(dto.GraphId);
|
| 51 |
+
if (permission is null) return NotFound();
|
| 52 |
+
if (!CanWrite(permission)) return Forbid();
|
| 53 |
+
|
| 54 |
try
|
| 55 |
{
|
| 56 |
var node = await _service.CreateAsync(dto);
|
|
|
|
| 65 |
[HttpPut("{id:guid}")]
|
| 66 |
public async Task<ActionResult<TaskNodeResponseDto>> Update(Guid id, [FromBody] UpdateTaskNodeDto dto)
|
| 67 |
{
|
| 68 |
+
var existing = await _service.GetByIdAsync(id);
|
| 69 |
+
if (existing is null) return NotFound();
|
| 70 |
+
var permission = await GetPermissionAsync(existing.GraphId);
|
| 71 |
+
if (permission is null) return NotFound();
|
| 72 |
+
if (!CanWrite(permission)) return Forbid();
|
| 73 |
+
|
| 74 |
var node = await _service.UpdateAsync(id, dto);
|
| 75 |
if (node is null) return NotFound();
|
| 76 |
return Ok(node);
|
|
|
|
| 79 |
[HttpDelete("{id:guid}")]
|
| 80 |
public async Task<IActionResult> Delete(Guid id)
|
| 81 |
{
|
| 82 |
+
var existing = await _service.GetByIdAsync(id);
|
| 83 |
+
if (existing is null) return NotFound();
|
| 84 |
+
var permission = await GetPermissionAsync(existing.GraphId);
|
| 85 |
+
if (permission is null) return NotFound();
|
| 86 |
+
if (!CanWrite(permission)) return Forbid();
|
| 87 |
+
|
| 88 |
+
if (!await _service.DeleteAsync(id)) return NotFound();
|
| 89 |
return NoContent();
|
| 90 |
}
|
| 91 |
|
| 92 |
[HttpGet("{id:guid}/data")]
|
| 93 |
public async Task<ActionResult<object>> GetNodeData(Guid id)
|
| 94 |
{
|
| 95 |
+
var node = await _service.GetByIdAsync(id);
|
| 96 |
+
if (node is null || await GetPermissionAsync(node.GraphId) is null) return NotFound();
|
| 97 |
+
|
| 98 |
var nodeData = await _service.GetNodeDataAsync(id);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
return Ok(new { data = nodeData });
|
| 100 |
}
|
| 101 |
}
|
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
using FlowAPI.Application.DTOs.Template;
|
| 2 |
+
using FlowAPI.Application.Interfaces;
|
| 3 |
+
using Microsoft.AspNetCore.Authorization;
|
| 4 |
+
using Microsoft.AspNetCore.Mvc;
|
| 5 |
+
using System;
|
| 6 |
+
using System.Collections.Generic;
|
| 7 |
+
using System.Security.Claims;
|
| 8 |
+
using System.Threading.Tasks;
|
| 9 |
+
|
| 10 |
+
namespace FlowAPI.Controllers
|
| 11 |
+
{
|
| 12 |
+
/// <summary>
|
| 13 |
+
/// User-owned templates. Built-in templates live in the web client.
|
| 14 |
+
/// </summary>
|
| 15 |
+
[ApiController]
|
| 16 |
+
[Authorize]
|
| 17 |
+
[Route("api/[controller]")]
|
| 18 |
+
public class TemplatesController : ControllerBase
|
| 19 |
+
{
|
| 20 |
+
private readonly ITemplateService _service;
|
| 21 |
+
|
| 22 |
+
public TemplatesController(ITemplateService service)
|
| 23 |
+
{
|
| 24 |
+
_service = service;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
private Guid CurrentUserId =>
|
| 28 |
+
Guid.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
|
| 29 |
+
|
| 30 |
+
[HttpGet]
|
| 31 |
+
public async Task<ActionResult<IEnumerable<TemplateDto>>> GetMine()
|
| 32 |
+
{
|
| 33 |
+
if (CurrentUserId == Guid.Empty) return Unauthorized();
|
| 34 |
+
return Ok(await _service.GetMineAsync(CurrentUserId));
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
[HttpGet("{id:guid}")]
|
| 38 |
+
public async Task<ActionResult<TemplateDto>> Get(Guid id)
|
| 39 |
+
{
|
| 40 |
+
if (CurrentUserId == Guid.Empty) return Unauthorized();
|
| 41 |
+
var template = await _service.GetAsync(id, CurrentUserId);
|
| 42 |
+
if (template is null) return NotFound();
|
| 43 |
+
return Ok(template);
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
[HttpPost]
|
| 47 |
+
public async Task<ActionResult<TemplateDto>> Create([FromBody] CreateTemplateDto dto)
|
| 48 |
+
{
|
| 49 |
+
if (CurrentUserId == Guid.Empty) return Unauthorized();
|
| 50 |
+
try
|
| 51 |
+
{
|
| 52 |
+
var template = await _service.CreateAsync(dto, CurrentUserId);
|
| 53 |
+
return CreatedAtAction(nameof(Get), new { id = template.Id }, template);
|
| 54 |
+
}
|
| 55 |
+
catch (InvalidOperationException ex)
|
| 56 |
+
{
|
| 57 |
+
return BadRequest(new { message = ex.Message });
|
| 58 |
+
}
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
[HttpPut("{id:guid}")]
|
| 62 |
+
public async Task<ActionResult<TemplateDto>> Update(Guid id, [FromBody] UpdateTemplateDto dto)
|
| 63 |
+
{
|
| 64 |
+
if (CurrentUserId == Guid.Empty) return Unauthorized();
|
| 65 |
+
var template = await _service.UpdateAsync(id, dto, CurrentUserId);
|
| 66 |
+
if (template is null) return NotFound();
|
| 67 |
+
return Ok(template);
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
[HttpDelete("{id:guid}")]
|
| 71 |
+
public async Task<IActionResult> Delete(Guid id)
|
| 72 |
+
{
|
| 73 |
+
if (CurrentUserId == Guid.Empty) return Unauthorized();
|
| 74 |
+
if (!await _service.DeleteAsync(id, CurrentUserId)) return NotFound();
|
| 75 |
+
return NoContent();
|
| 76 |
+
}
|
| 77 |
+
}
|
| 78 |
+
}
|
|
@@ -33,16 +33,14 @@ namespace FlowAPI.Controllers
|
|
| 33 |
return Ok(user);
|
| 34 |
}
|
| 35 |
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
{
|
| 39 |
-
var users = await _service.GetAllAsync();
|
| 40 |
-
return Ok(users);
|
| 41 |
-
}
|
| 42 |
|
|
|
|
| 43 |
[HttpGet("{id:guid}")]
|
| 44 |
public async Task<ActionResult<UserResponseDto>> GetById(Guid id)
|
| 45 |
{
|
|
|
|
| 46 |
var user = await _service.GetByIdAsync(id);
|
| 47 |
if (user is null) return NotFound();
|
| 48 |
return Ok(user);
|
|
@@ -60,6 +58,10 @@ namespace FlowAPI.Controllers
|
|
| 60 |
{
|
| 61 |
return Conflict(new { message = ex.Message });
|
| 62 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
}
|
| 64 |
|
| 65 |
[HttpPost("login")]
|
|
@@ -84,17 +86,28 @@ namespace FlowAPI.Controllers
|
|
| 84 |
}
|
| 85 |
}
|
| 86 |
|
|
|
|
| 87 |
[HttpPut("{id:guid}")]
|
| 88 |
public async Task<ActionResult<UserResponseDto>> Update(Guid id, [FromBody] UpdateUserDto dto)
|
| 89 |
{
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
}
|
| 94 |
|
|
|
|
| 95 |
[HttpDelete("{id:guid}")]
|
| 96 |
public async Task<IActionResult> Delete(Guid id)
|
| 97 |
{
|
|
|
|
| 98 |
var result = await _service.DeleteAsync(id);
|
| 99 |
if (!result) return NotFound();
|
| 100 |
return NoContent();
|
|
|
|
| 33 |
return Ok(user);
|
| 34 |
}
|
| 35 |
|
| 36 |
+
private Guid CurrentUserId =>
|
| 37 |
+
Guid.TryParse(User.FindFirst(ClaimTypes.NameIdentifier)?.Value, out var id) ? id : Guid.Empty;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
[Authorize]
|
| 40 |
[HttpGet("{id:guid}")]
|
| 41 |
public async Task<ActionResult<UserResponseDto>> GetById(Guid id)
|
| 42 |
{
|
| 43 |
+
if (id != CurrentUserId) return Forbid();
|
| 44 |
var user = await _service.GetByIdAsync(id);
|
| 45 |
if (user is null) return NotFound();
|
| 46 |
return Ok(user);
|
|
|
|
| 58 |
{
|
| 59 |
return Conflict(new { message = ex.Message });
|
| 60 |
}
|
| 61 |
+
catch (ArgumentException ex)
|
| 62 |
+
{
|
| 63 |
+
return BadRequest(new { message = ex.Message });
|
| 64 |
+
}
|
| 65 |
}
|
| 66 |
|
| 67 |
[HttpPost("login")]
|
|
|
|
| 86 |
}
|
| 87 |
}
|
| 88 |
|
| 89 |
+
[Authorize]
|
| 90 |
[HttpPut("{id:guid}")]
|
| 91 |
public async Task<ActionResult<UserResponseDto>> Update(Guid id, [FromBody] UpdateUserDto dto)
|
| 92 |
{
|
| 93 |
+
if (id != CurrentUserId) return Forbid();
|
| 94 |
+
try
|
| 95 |
+
{
|
| 96 |
+
var user = await _service.UpdateAsync(id, dto);
|
| 97 |
+
if (user is null) return NotFound();
|
| 98 |
+
return Ok(user);
|
| 99 |
+
}
|
| 100 |
+
catch (ArgumentException ex)
|
| 101 |
+
{
|
| 102 |
+
return BadRequest(new { message = ex.Message });
|
| 103 |
+
}
|
| 104 |
}
|
| 105 |
|
| 106 |
+
[Authorize]
|
| 107 |
[HttpDelete("{id:guid}")]
|
| 108 |
public async Task<IActionResult> Delete(Guid id)
|
| 109 |
{
|
| 110 |
+
if (id != CurrentUserId) return Forbid();
|
| 111 |
var result = await _service.DeleteAsync(id);
|
| 112 |
if (!result) return NotFound();
|
| 113 |
return NoContent();
|
|
@@ -20,10 +20,4 @@
|
|
| 20 |
<ProjectReference Include="..\FlowAPI.Infrastructure\FlowAPI.Infrastructure.csproj" />
|
| 21 |
</ItemGroup>
|
| 22 |
|
| 23 |
-
<ItemGroup>
|
| 24 |
-
<None Update="FreeDeepseekAPI\**">
|
| 25 |
-
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
| 26 |
-
</None>
|
| 27 |
-
</ItemGroup>
|
| 28 |
-
|
| 29 |
</Project>
|
|
|
|
| 20 |
<ProjectReference Include="..\FlowAPI.Infrastructure\FlowAPI.Infrastructure.csproj" />
|
| 21 |
</ItemGroup>
|
| 22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
</Project>
|
|
@@ -1,6 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"name": "free-deepseek-api",
|
| 3 |
-
"version": "0.1.0",
|
| 4 |
-
"main": "server.js",
|
| 5 |
-
"type": "commonjs"
|
| 6 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -1,1400 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env node
|
| 2 |
-
/**
|
| 3 |
-
* OpenAI-compatible API server wrapping DeepSeek Web API
|
| 4 |
-
* Supports BOTH streaming (SSE) and non-streaming modes
|
| 5 |
-
* Includes tool calling: injects tool definitions into system prompt,
|
| 6 |
-
* parses LLM text responses for TOOL_CALL patterns, returns OpenAI tool_calls format.
|
| 7 |
-
*
|
| 8 |
-
* Per-agent sessions: each unique `user` field gets its own DeepSeek web session.
|
| 9 |
-
* Auto-reset: sessions reset when message chain > 50 messages or age > 2 hours.
|
| 10 |
-
* Listens on 0.0.0.0:9655
|
| 11 |
-
*/
|
| 12 |
-
|
| 13 |
-
const http = require('http');
|
| 14 |
-
const fs = require('fs');
|
| 15 |
-
const os = require('os');
|
| 16 |
-
const path = require('path');
|
| 17 |
-
const readline = require('readline');
|
| 18 |
-
const { spawnSync } = require('child_process');
|
| 19 |
-
|
| 20 |
-
const SERVER_HOST = os.hostname(); // Dynamic hostname detection
|
| 21 |
-
const SERVER_PUBLIC_IP = (() => {
|
| 22 |
-
try {
|
| 23 |
-
const interfaces = os.networkInterfaces();
|
| 24 |
-
for (const name of Object.keys(interfaces)) {
|
| 25 |
-
for (const iface of interfaces[name]) {
|
| 26 |
-
if (iface.family === 'IPv4' && !iface.internal) return iface.address;
|
| 27 |
-
}
|
| 28 |
-
}
|
| 29 |
-
} catch (e) {}
|
| 30 |
-
return 'localhost';
|
| 31 |
-
})();
|
| 32 |
-
|
| 33 |
-
const FORGETMEAI_WATERMARK = 't.me/forgetmeai';
|
| 34 |
-
const PORT = Number(process.env.PORT || 9655);
|
| 35 |
-
const HOST = process.env.HOST || '0.0.0.0';
|
| 36 |
-
function formatWatermark(prefix = 'ForgetMeAI') { return `${prefix}: ${FORGETMEAI_WATERMARK}`; }
|
| 37 |
-
function printBanner() {
|
| 38 |
-
console.log(`
|
| 39 |
-
███████ ██████ ███████ ███████ ██████ ███████ ███████ ███████ ██ ██
|
| 40 |
-
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
|
| 41 |
-
█████ ██████ █████ █████ ██ ██ █████ █████ █████ █████
|
| 42 |
-
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
|
| 43 |
-
██ ██ ██ ███████ ███████ ██████ ███████ ███████ ███████ ██ ██
|
| 44 |
-
|
| 45 |
-
FreeDeepseekAPI — API-прокси для DeepSeek Web Chat
|
| 46 |
-
${formatWatermark()}
|
| 47 |
-
`);
|
| 48 |
-
}
|
| 49 |
-
function prompt(question) {
|
| 50 |
-
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
| 51 |
-
return new Promise(resolve => rl.question(question, ans => { rl.close(); resolve(ans); }));
|
| 52 |
-
}
|
| 53 |
-
function isTruthy(value) { return typeof value === 'string' && ['1','true','yes','on'].includes(value.trim().toLowerCase()); }
|
| 54 |
-
|
| 55 |
-
// === Per-Agent Session Store ===
|
| 56 |
-
const sessions = new Map(); // keyed by agent ID (from `user` field)
|
| 57 |
-
const MAX_HISTORY_LENGTH = 15;
|
| 58 |
-
const MAX_HISTORY_CHARS = 10000;
|
| 59 |
-
const MAX_MESSAGE_DEPTH = 100; // auto-reset after this many messages
|
| 60 |
-
const SESSION_TTL_MS = 2 * 60 * 60 * 1000; // 2 hours
|
| 61 |
-
|
| 62 |
-
// === DeepSeek Web API Config — loaded from external config file ===
|
| 63 |
-
const DS_CONFIG_PATH = process.env.DEEPSEEK_AUTH_PATH || path.join(__dirname, 'deepseek-auth.json');
|
| 64 |
-
let DS_CONFIG = {};
|
| 65 |
-
let BASE_HEADERS = {};
|
| 66 |
-
function buildBaseHeaders() {
|
| 67 |
-
return {
|
| 68 |
-
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36",
|
| 69 |
-
"x-client-platform": "web",
|
| 70 |
-
"x-client-version": "2.0.0",
|
| 71 |
-
"x-client-locale": "ru",
|
| 72 |
-
"x-client-timezone-offset": "14400",
|
| 73 |
-
"x-app-version": "2.0.0",
|
| 74 |
-
"Authorization": `Bearer ${DS_CONFIG.token || ''}`,
|
| 75 |
-
"x-hif-dliq": DS_CONFIG.hif_dliq || '',
|
| 76 |
-
"x-hif-leim": DS_CONFIG.hif_leim || '',
|
| 77 |
-
"Origin": "https://chat.deepseek.com",
|
| 78 |
-
"Referer": "https://chat.deepseek.com/",
|
| 79 |
-
"Cookie": DS_CONFIG.cookie || '',
|
| 80 |
-
"Content-Type": "application/json",
|
| 81 |
-
};
|
| 82 |
-
}
|
| 83 |
-
function loadDeepSeekConfig({ fatal = true } = {}) {
|
| 84 |
-
try {
|
| 85 |
-
if (fs.existsSync(DS_CONFIG_PATH)) {
|
| 86 |
-
const raw = fs.readFileSync(DS_CONFIG_PATH, 'utf8');
|
| 87 |
-
DS_CONFIG = JSON.parse(raw);
|
| 88 |
-
console.log(`[DS-API] Loaded auth config from ${DS_CONFIG_PATH}`);
|
| 89 |
-
} else {
|
| 90 |
-
DS_CONFIG = {
|
| 91 |
-
token: process.env.DEEPSEEK_TOKEN || '',
|
| 92 |
-
cookie: process.env.DEEPSEEK_COOKIE || '',
|
| 93 |
-
hif_dliq: process.env.DEEPSEEK_HIF_DLIQ || '',
|
| 94 |
-
hif_leim: process.env.DEEPSEEK_HIF_LEIM || '',
|
| 95 |
-
wasmUrl: process.env.DEEPSEEK_WASM_URL || 'https://fe-static.deepseek.com/chat/static/sha3_wasm_bg.7b9ca65ddd.wasm',
|
| 96 |
-
};
|
| 97 |
-
console.log(`[DS-API] Loaded auth config from process.env`);
|
| 98 |
-
}
|
| 99 |
-
BASE_HEADERS = buildBaseHeaders();
|
| 100 |
-
return true;
|
| 101 |
-
} catch (e) {
|
| 102 |
-
DS_CONFIG = {};
|
| 103 |
-
BASE_HEADERS = buildBaseHeaders();
|
| 104 |
-
if (fatal) {
|
| 105 |
-
console.error(`[DS-API] FATAL: Could not load auth config: ${e.message}`);
|
| 106 |
-
process.exit(1);
|
| 107 |
-
}
|
| 108 |
-
return false;
|
| 109 |
-
}
|
| 110 |
-
}
|
| 111 |
-
function hasAuthConfig() { return !!(DS_CONFIG.token && DS_CONFIG.cookie); }
|
| 112 |
-
loadDeepSeekConfig({ fatal: false });
|
| 113 |
-
|
| 114 |
-
function createSession() {
|
| 115 |
-
return {
|
| 116 |
-
id: null,
|
| 117 |
-
parentMessageId: null,
|
| 118 |
-
createdAt: null,
|
| 119 |
-
messageCount: 0,
|
| 120 |
-
history: [],
|
| 121 |
-
};
|
| 122 |
-
}
|
| 123 |
-
|
| 124 |
-
function getOrCreateAgentSession(agentId) {
|
| 125 |
-
if (!sessions.has(agentId)) {
|
| 126 |
-
sessions.set(agentId, createSession());
|
| 127 |
-
}
|
| 128 |
-
return sessions.get(agentId);
|
| 129 |
-
}
|
| 130 |
-
|
| 131 |
-
async function solvePOW(challenge) {
|
| 132 |
-
const resp = await fetch(DS_CONFIG.wasmUrl);
|
| 133 |
-
const wasmBytes = await resp.arrayBuffer();
|
| 134 |
-
const mod = await WebAssembly.instantiate(wasmBytes, { wbg: {} });
|
| 135 |
-
const e = mod.instance.exports;
|
| 136 |
-
const encoder = new TextEncoder();
|
| 137 |
-
const prefix = challenge.salt + '_' + challenge.expire_at + '_';
|
| 138 |
-
const cBytes = encoder.encode(challenge.challenge);
|
| 139 |
-
const pBytes = encoder.encode(prefix);
|
| 140 |
-
const cP = e.__wbindgen_export_0(cBytes.length, 1) >>> 0;
|
| 141 |
-
const pP = e.__wbindgen_export_0(pBytes.length, 1) >>> 0;
|
| 142 |
-
new Uint8Array(e.memory.buffer, cP, cBytes.length).set(cBytes);
|
| 143 |
-
new Uint8Array(e.memory.buffer, pP, pBytes.length).set(pBytes);
|
| 144 |
-
const sp = e.__wbindgen_add_to_stack_pointer(-16);
|
| 145 |
-
e.wasm_solve(sp, cP, cBytes.length, pP, pBytes.length, challenge.difficulty);
|
| 146 |
-
const dv = new DataView(e.memory.buffer);
|
| 147 |
-
const code = dv.getInt32(sp, true);
|
| 148 |
-
const ans = dv.getFloat64(sp + 8, true);
|
| 149 |
-
e.__wbindgen_add_to_stack_pointer(16);
|
| 150 |
-
if (code === 0 || !Number.isFinite(ans) || ans <= 0) throw new Error('POW failed');
|
| 151 |
-
return Math.floor(ans);
|
| 152 |
-
}
|
| 153 |
-
|
| 154 |
-
const MODEL_CONFIGS = {
|
| 155 |
-
// DeepSeek Web real model_type: default / UI name: "Быстрый".
|
| 156 |
-
// Public model family: DeepSeek-V3.2-Exp chat mode (fast, no visible reasoning).
|
| 157 |
-
'deepseek-chat': {
|
| 158 |
-
model_type: 'default', thinking_enabled: false, search_enabled: false,
|
| 159 |
-
real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default)',
|
| 160 |
-
capabilities: { reasoning: false, web_search: false, files: true },
|
| 161 |
-
supported: true,
|
| 162 |
-
},
|
| 163 |
-
'deepseek-v3': {
|
| 164 |
-
model_type: 'default', thinking_enabled: false, search_enabled: false,
|
| 165 |
-
real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default)',
|
| 166 |
-
capabilities: { reasoning: false, web_search: false, files: true },
|
| 167 |
-
supported: true,
|
| 168 |
-
},
|
| 169 |
-
'deepseek-default': {
|
| 170 |
-
model_type: 'default', thinking_enabled: false, search_enabled: false,
|
| 171 |
-
real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default)',
|
| 172 |
-
capabilities: { reasoning: false, web_search: false, files: true },
|
| 173 |
-
supported: true,
|
| 174 |
-
},
|
| 175 |
-
// Same DeepSeek Web default model, but with thinking_enabled=true. UI exposes it as thinking/reasoning mode.
|
| 176 |
-
'deepseek-reasoner': {
|
| 177 |
-
model_type: 'default', thinking_enabled: true, search_enabled: false,
|
| 178 |
-
real_model: 'DeepSeek-V4-Flash thinking mode (DeepSeek Web “Быстрый” + thinking_enabled)',
|
| 179 |
-
capabilities: { reasoning: true, web_search: false, files: true },
|
| 180 |
-
supported: true,
|
| 181 |
-
},
|
| 182 |
-
'deepseek-r1': {
|
| 183 |
-
model_type: 'default', thinking_enabled: true, search_enabled: false,
|
| 184 |
-
real_model: 'DeepSeek-V4-Flash thinking mode; R1-compatible alias, not a separate R1 model_type in current Web API',
|
| 185 |
-
capabilities: { reasoning: true, web_search: false, files: true },
|
| 186 |
-
supported: true,
|
| 187 |
-
},
|
| 188 |
-
'deepseek-chat-search': {
|
| 189 |
-
model_type: 'default', thinking_enabled: false, search_enabled: true,
|
| 190 |
-
real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default) + web search',
|
| 191 |
-
capabilities: { reasoning: false, web_search: true, files: true },
|
| 192 |
-
supported: true,
|
| 193 |
-
},
|
| 194 |
-
'deepseek-default-search': {
|
| 195 |
-
model_type: 'default', thinking_enabled: false, search_enabled: true,
|
| 196 |
-
real_model: 'DeepSeek-V4-Flash non-thinking (DeepSeek Web “Быстрый” / default) + web search',
|
| 197 |
-
capabilities: { reasoning: false, web_search: true, files: true },
|
| 198 |
-
supported: true,
|
| 199 |
-
},
|
| 200 |
-
'deepseek-reasoner-search': {
|
| 201 |
-
model_type: 'default', thinking_enabled: true, search_enabled: true,
|
| 202 |
-
real_model: 'DeepSeek-V4-Flash thinking mode + web search',
|
| 203 |
-
capabilities: { reasoning: true, web_search: true, files: true },
|
| 204 |
-
supported: true,
|
| 205 |
-
},
|
| 206 |
-
'deepseek-r1-search': {
|
| 207 |
-
model_type: 'default', thinking_enabled: true, search_enabled: true,
|
| 208 |
-
real_model: 'DeepSeek-V4-Flash thinking mode + web search; R1-compatible alias',
|
| 209 |
-
capabilities: { reasoning: true, web_search: true, files: true },
|
| 210 |
-
supported: true,
|
| 211 |
-
},
|
| 212 |
-
// DeepSeek Web UI name: “Эксперт”. Requires current web client headers (x-client-version=2.0.0).
|
| 213 |
-
'deepseek-expert': {
|
| 214 |
-
model_type: 'expert', thinking_enabled: false, search_enabled: false,
|
| 215 |
-
real_model: 'DeepSeek Web “Эксперт” (limited resources)',
|
| 216 |
-
capabilities: { reasoning: false, web_search: false, files: false },
|
| 217 |
-
supported: true,
|
| 218 |
-
},
|
| 219 |
-
'deepseek-v4-pro': {
|
| 220 |
-
model_type: 'expert', thinking_enabled: true, search_enabled: false,
|
| 221 |
-
real_model: 'DeepSeek Web “Эксперт” + thinking mode (exposed as deepseek-v4-pro alias)',
|
| 222 |
-
capabilities: { reasoning: true, web_search: false, files: false },
|
| 223 |
-
supported: true,
|
| 224 |
-
},
|
| 225 |
-
'deepseek-expert-search': {
|
| 226 |
-
model_type: 'expert', thinking_enabled: false, search_enabled: true,
|
| 227 |
-
real_model: 'DeepSeek Web “Эксперт” + search requested, but Expert has search_feature=null in remote config',
|
| 228 |
-
capabilities: { reasoning: false, web_search: false, files: false },
|
| 229 |
-
supported: false,
|
| 230 |
-
unavailable_reason: 'Expert mode is rejected; remote config says search is not available for Expert.',
|
| 231 |
-
},
|
| 232 |
-
'deepseek-vision': {
|
| 233 |
-
model_type: 'vision', thinking_enabled: false, search_enabled: false,
|
| 234 |
-
real_model: 'DeepSeek Web “Распознавание” / image understanding beta',
|
| 235 |
-
capabilities: { reasoning: false, web_search: false, files: true, vision: true },
|
| 236 |
-
supported: false,
|
| 237 |
-
unavailable_reason: 'Current Web API returns: Vision is temporarily unavailable (backend_err_by_model).',
|
| 238 |
-
},
|
| 239 |
-
};
|
| 240 |
-
|
| 241 |
-
const SUPPORTED_MODEL_IDS = Object.keys(MODEL_CONFIGS).filter(id => MODEL_CONFIGS[id].supported);
|
| 242 |
-
const ALL_MODEL_CAPABILITIES = Object.fromEntries(Object.entries(MODEL_CONFIGS).map(([id, cfg]) => [id, {
|
| 243 |
-
id,
|
| 244 |
-
real_model: cfg.real_model,
|
| 245 |
-
model_type: cfg.model_type,
|
| 246 |
-
thinking_enabled: cfg.thinking_enabled,
|
| 247 |
-
search_enabled: cfg.search_enabled,
|
| 248 |
-
capabilities: cfg.capabilities,
|
| 249 |
-
supported: cfg.supported,
|
| 250 |
-
unavailable_reason: cfg.unavailable_reason || null,
|
| 251 |
-
}]));
|
| 252 |
-
|
| 253 |
-
function resolveModelConfig(model) {
|
| 254 |
-
const requested = String(model || 'deepseek-chat').toLowerCase();
|
| 255 |
-
return MODEL_CONFIGS[requested] || MODEL_CONFIGS['deepseek-chat'];
|
| 256 |
-
}
|
| 257 |
-
function isKnownModel(model) { return Object.prototype.hasOwnProperty.call(MODEL_CONFIGS, String(model || '').toLowerCase()); }
|
| 258 |
-
function isSupportedModel(model) { return resolveModelConfig(model).supported === true; }
|
| 259 |
-
|
| 260 |
-
async function askDeepSeekStream(prompt, agentId, model = 'deepseek-default') {
|
| 261 |
-
const modelCfg = resolveModelConfig(model);
|
| 262 |
-
const session = getOrCreateAgentSession(agentId);
|
| 263 |
-
const agentTag = `[${agentId}]`;
|
| 264 |
-
|
| 265 |
-
// Auto-reset on deep message chain
|
| 266 |
-
if (session.id && session.messageCount >= MAX_MESSAGE_DEPTH) {
|
| 267 |
-
console.log(`${agentTag} Session ${session.id} hit ${session.messageCount} messages. Auto-resetting.`);
|
| 268 |
-
session.id = null;
|
| 269 |
-
session.parentMessageId = null;
|
| 270 |
-
session.createdAt = null;
|
| 271 |
-
session.messageCount = 0;
|
| 272 |
-
// History preserved for context injection
|
| 273 |
-
}
|
| 274 |
-
|
| 275 |
-
// Reset expired sessions (DeepSeek web sessions last ~1-2 hours)
|
| 276 |
-
if (session.id && session.createdAt && (Date.now() - session.createdAt > SESSION_TTL_MS)) {
|
| 277 |
-
console.log(`${agentTag} Session ${session.id} expired (age: ${Math.round((Date.now() - session.createdAt) / 60000)}min). Creating new...`);
|
| 278 |
-
session.id = null;
|
| 279 |
-
session.parentMessageId = null;
|
| 280 |
-
session.createdAt = null;
|
| 281 |
-
session.messageCount = 0;
|
| 282 |
-
}
|
| 283 |
-
|
| 284 |
-
const cr = await fetch('https://chat.deepseek.com/api/v0/chat/create_pow_challenge', {
|
| 285 |
-
method: 'POST', headers: BASE_HEADERS,
|
| 286 |
-
body: JSON.stringify({ target_path: '/api/v0/chat/completion' })
|
| 287 |
-
});
|
| 288 |
-
const chalJson = JSON.parse(await cr.text());
|
| 289 |
-
const challenge = chalJson.data.biz_data.challenge;
|
| 290 |
-
const answer = await solvePOW(challenge);
|
| 291 |
-
|
| 292 |
-
if (!session.id) {
|
| 293 |
-
const sr = await fetch('https://chat.deepseek.com/api/v0/chat_session/create', {
|
| 294 |
-
method: 'POST', headers: BASE_HEADERS, body: '{}'
|
| 295 |
-
});
|
| 296 |
-
const sessionData = await sr.json();
|
| 297 |
-
session.id = sessionData.data.biz_data.chat_session?.id || sessionData.data.biz_data.id;
|
| 298 |
-
session.parentMessageId = null;
|
| 299 |
-
session.createdAt = Date.now();
|
| 300 |
-
session.messageCount = 0;
|
| 301 |
-
console.log(`${agentTag} Created new session: ${session.id}`);
|
| 302 |
-
} else {
|
| 303 |
-
console.log(`${agentTag} Reusing session: ${session.id} (parent: ${session.parentMessageId}, msg#${session.messageCount})`);
|
| 304 |
-
}
|
| 305 |
-
|
| 306 |
-
const powB64 = Buffer.from(JSON.stringify({
|
| 307 |
-
algorithm: challenge.algorithm, challenge: challenge.challenge,
|
| 308 |
-
salt: challenge.salt, answer: answer,
|
| 309 |
-
signature: challenge.signature, target_path: '/api/v0/chat/completion'
|
| 310 |
-
})).toString('base64');
|
| 311 |
-
const resp = await fetch('https://chat.deepseek.com/api/v0/chat/completion', {
|
| 312 |
-
method: 'POST',
|
| 313 |
-
headers: { ...BASE_HEADERS, 'X-DS-PoW-Response': powB64 },
|
| 314 |
-
body: JSON.stringify({
|
| 315 |
-
chat_session_id: session.id,
|
| 316 |
-
parent_message_id: session.parentMessageId,
|
| 317 |
-
model_type: modelCfg.model_type,
|
| 318 |
-
prompt: prompt, ref_file_ids: [],
|
| 319 |
-
thinking_enabled: modelCfg.thinking_enabled, search_enabled: modelCfg.search_enabled,
|
| 320 |
-
action: null, preempt: false,
|
| 321 |
-
})
|
| 322 |
-
});
|
| 323 |
-
|
| 324 |
-
// If session expired, reset and retry once
|
| 325 |
-
if (resp.status !== 200) {
|
| 326 |
-
const errText = await resp.text();
|
| 327 |
-
console.log(`${agentTag} Session error (${resp.status}): ${errText.substring(0, 100)}`);
|
| 328 |
-
if (resp.status === 400 || resp.status === 404 || resp.status === 500) {
|
| 329 |
-
console.log(`${agentTag} Session ${session.id} expired. Creating new session...`);
|
| 330 |
-
session.id = null;
|
| 331 |
-
session.parentMessageId = null;
|
| 332 |
-
session.createdAt = null;
|
| 333 |
-
session.messageCount = 0;
|
| 334 |
-
|
| 335 |
-
const sr2 = await fetch('https://chat.deepseek.com/api/v0/chat_session/create', {
|
| 336 |
-
method: 'POST', headers: BASE_HEADERS, body: '{}'
|
| 337 |
-
});
|
| 338 |
-
const sessionData2 = await sr2.json();
|
| 339 |
-
session.id = sessionData2.data.biz_data.chat_session?.id || sessionData2.data.biz_data.id;
|
| 340 |
-
session.parentMessageId = null;
|
| 341 |
-
session.createdAt = Date.now();
|
| 342 |
-
console.log(`${agentTag} Created new session: ${session.id}`);
|
| 343 |
-
|
| 344 |
-
const newPowB64 = Buffer.from(JSON.stringify({
|
| 345 |
-
algorithm: challenge.algorithm, challenge: challenge.challenge,
|
| 346 |
-
salt: challenge.salt, answer: answer,
|
| 347 |
-
signature: challenge.signature, target_path: '/api/v0/chat/completion'
|
| 348 |
-
})).toString('base64');
|
| 349 |
-
const resp2 = await fetch('https://chat.deepseek.com/api/v0/chat/completion', {
|
| 350 |
-
method: 'POST',
|
| 351 |
-
headers: { ...BASE_HEADERS, 'X-DS-PoW-Response': newPowB64 },
|
| 352 |
-
body: JSON.stringify({
|
| 353 |
-
chat_session_id: session.id,
|
| 354 |
-
parent_message_id: null,
|
| 355 |
-
model_type: modelCfg.model_type,
|
| 356 |
-
prompt: prompt, ref_file_ids: [],
|
| 357 |
-
thinking_enabled: modelCfg.thinking_enabled, search_enabled: modelCfg.search_enabled,
|
| 358 |
-
action: null, preempt: false,
|
| 359 |
-
})
|
| 360 |
-
});
|
| 361 |
-
return { resp: resp2, agentId };
|
| 362 |
-
}
|
| 363 |
-
}
|
| 364 |
-
|
| 365 |
-
return { resp, agentId };
|
| 366 |
-
}
|
| 367 |
-
|
| 368 |
-
// === Tool Calling Support ===
|
| 369 |
-
|
| 370 |
-
function formatToolDefinitions(tools) {
|
| 371 |
-
if (!tools || tools.length === 0) return '';
|
| 372 |
-
let text = '\n\n--- TOOL REQUEST SYSTEM ---\n';
|
| 373 |
-
text += 'You are an AI that ONLY REASONS and REQUESTS tool executions. You do NOT run any commands yourself.\n';
|
| 374 |
-
text += 'When you need data from the local server, REQUEST exactly one tool call. Prefer strict JSON:\n';
|
| 375 |
-
text += '{"tool_call":{"name":"<function_name>","arguments":{...}}}\n\n';
|
| 376 |
-
text += 'Legacy format is also accepted: TOOL_CALL: <function_name>\narguments: <JSON arguments>\n\n';
|
| 377 |
-
text += 'Your response will be sent to the local gateway, which executes the command and sends the output back in the next message.\n\n';
|
| 378 |
-
text += 'RULES:\n';
|
| 379 |
-
text += '1. You ONLY output the tool request — you never run anything yourself\n';
|
| 380 |
-
text += '2. Do NOT simulate, guess, or fabricate command output — wait for the actual result\n';
|
| 381 |
-
text += '3. The tool runs on ' + SERVER_HOST + ' (' + SERVER_PUBLIC_IP + '), the local server — NOT on DeepSeek\n';
|
| 382 |
-
text += '4. After the tool executes, the result will be sent to you as a new user/tool message\n';
|
| 383 |
-
text += '5. Never add explanation before or after the tool request when requesting a tool\n';
|
| 384 |
-
text += '6. Keep arguments compact. Do not include large file contents unless the tool schema requires it.\n\n';
|
| 385 |
-
text += 'Available functions:\n';
|
| 386 |
-
for (const tool of tools) {
|
| 387 |
-
if (tool.type === 'function' && tool.function) {
|
| 388 |
-
const fn = tool.function;
|
| 389 |
-
text += `\n## ${fn.name}\n`;
|
| 390 |
-
text += `${fn.description || ''}\n`;
|
| 391 |
-
if (fn.parameters) {
|
| 392 |
-
text += `Parameters: ${JSON.stringify(fn.parameters)}\n`;
|
| 393 |
-
}
|
| 394 |
-
}
|
| 395 |
-
}
|
| 396 |
-
text += '\n--- END TOOL REQUEST SYSTEM ---\n';
|
| 397 |
-
text += '\nREMEMBER: Request tools only with strict JSON or TOOL_CALL legacy format. Never simulate results.';
|
| 398 |
-
return text;
|
| 399 |
-
}
|
| 400 |
-
|
| 401 |
-
function extractBalancedJsonAt(text, startIndex) {
|
| 402 |
-
let braceDepth = 0;
|
| 403 |
-
let inString = false;
|
| 404 |
-
let escape = false;
|
| 405 |
-
for (let i = startIndex; i < text.length; i++) {
|
| 406 |
-
const ch = text[i];
|
| 407 |
-
if (escape) { escape = false; continue; }
|
| 408 |
-
if (ch === '\\' && inString) { escape = true; continue; }
|
| 409 |
-
if (ch === '"') { inString = !inString; continue; }
|
| 410 |
-
if (!inString) {
|
| 411 |
-
if (ch === '{') braceDepth++;
|
| 412 |
-
if (ch === '}') {
|
| 413 |
-
braceDepth--;
|
| 414 |
-
if (braceDepth === 0) return text.substring(startIndex, i + 1);
|
| 415 |
-
}
|
| 416 |
-
}
|
| 417 |
-
}
|
| 418 |
-
return null;
|
| 419 |
-
}
|
| 420 |
-
|
| 421 |
-
function coerceToolCallObject(obj) {
|
| 422 |
-
if (!obj || typeof obj !== 'object') return null;
|
| 423 |
-
const candidate = obj.tool_call || obj.tool || obj.function_call || obj;
|
| 424 |
-
if (!candidate || typeof candidate !== 'object') return null;
|
| 425 |
-
const fn = candidate.function && typeof candidate.function === 'object' ? candidate.function : candidate;
|
| 426 |
-
const name = fn.name || candidate.name || obj.name;
|
| 427 |
-
let args = fn.arguments ?? candidate.arguments ?? candidate.input ?? obj.arguments ?? obj.input ?? {};
|
| 428 |
-
if (!name || typeof name !== 'string') return null;
|
| 429 |
-
if (typeof args === 'string') {
|
| 430 |
-
try { args = JSON.parse(args); } catch (e) { args = { raw: args }; }
|
| 431 |
-
}
|
| 432 |
-
if (!args || typeof args !== 'object' || Array.isArray(args)) args = { value: args };
|
| 433 |
-
return { name, arguments: JSON.stringify(args) };
|
| 434 |
-
}
|
| 435 |
-
|
| 436 |
-
function parseJsonToolCandidate(raw, label = 'json') {
|
| 437 |
-
if (!raw) return null;
|
| 438 |
-
try {
|
| 439 |
-
const parsed = JSON.parse(raw);
|
| 440 |
-
const tc = coerceToolCallObject(parsed);
|
| 441 |
-
if (tc) {
|
| 442 |
-
console.log(`[parseToolCall] SUCCESS ${label}: ${tc.name} (args=${tc.arguments.length} chars)`);
|
| 443 |
-
return tc;
|
| 444 |
-
}
|
| 445 |
-
} catch (e) {
|
| 446 |
-
console.log(`[parseToolCall] ${label} JSON.parse failed: ${e.message.substring(0, 100)}`);
|
| 447 |
-
}
|
| 448 |
-
return null;
|
| 449 |
-
}
|
| 450 |
-
|
| 451 |
-
function parseToolCall(text) {
|
| 452 |
-
if (!text || typeof text !== 'string') return null;
|
| 453 |
-
|
| 454 |
-
// XML-ish wrappers used by some agent prompts.
|
| 455 |
-
const xmlMatch = text.match(/<tool_call[^>]*>([\s\S]*?)<\/tool_call>/i);
|
| 456 |
-
if (xmlMatch) {
|
| 457 |
-
const inner = xmlMatch[1].trim();
|
| 458 |
-
const tc = parseJsonToolCandidate(inner, 'xml');
|
| 459 |
-
if (tc) return tc;
|
| 460 |
-
}
|
| 461 |
-
|
| 462 |
-
// Fenced JSON blocks.
|
| 463 |
-
const fenceRe = /```(?:json)?\s*([\s\S]*?)```/gi;
|
| 464 |
-
let fence;
|
| 465 |
-
while ((fence = fenceRe.exec(text)) !== null) {
|
| 466 |
-
const tc = parseJsonToolCandidate(fence[1].trim(), 'fenced');
|
| 467 |
-
if (tc) return tc;
|
| 468 |
-
}
|
| 469 |
-
|
| 470 |
-
// Legacy TOOL_CALL: name + first balanced JSON object after it.
|
| 471 |
-
const match = text.match(/TOOL_CALL:\s*([\w-]+)\s*/i);
|
| 472 |
-
if (match) {
|
| 473 |
-
const name = match[1];
|
| 474 |
-
const afterMatch = text.substring(match.index + match[0].length);
|
| 475 |
-
const braceIdx = afterMatch.indexOf('{');
|
| 476 |
-
if (braceIdx !== -1) {
|
| 477 |
-
const rawJson = extractBalancedJsonAt(afterMatch, braceIdx);
|
| 478 |
-
if (rawJson) {
|
| 479 |
-
try {
|
| 480 |
-
const args = JSON.parse(rawJson);
|
| 481 |
-
console.log(`[parseToolCall] SUCCESS legacy: ${name} (args=${rawJson.length} chars)`);
|
| 482 |
-
return { name, arguments: JSON.stringify(args) };
|
| 483 |
-
} catch (e) {
|
| 484 |
-
console.log(`[parseToolCall] legacy JSON.parse failed: ${e.message.substring(0,100)}`);
|
| 485 |
-
}
|
| 486 |
-
} else {
|
| 487 |
-
console.log(`[parseToolCall] TOOL_CALL:${name} found but JSON braces are unbalanced`);
|
| 488 |
-
}
|
| 489 |
-
} else {
|
| 490 |
-
console.log(`[parseToolCall] TOOL_CALL:${name} found but no { after it`);
|
| 491 |
-
}
|
| 492 |
-
}
|
| 493 |
-
|
| 494 |
-
// First balanced JSON object in the whole response. Supports:
|
| 495 |
-
// {"tool_call":{"name":"...","arguments":{...}}}, {"name":"...","arguments":{...}}, etc.
|
| 496 |
-
for (let i = 0; i < text.length; i++) {
|
| 497 |
-
if (text[i] !== '{') continue;
|
| 498 |
-
const rawJson = extractBalancedJsonAt(text, i);
|
| 499 |
-
if (!rawJson) continue;
|
| 500 |
-
const tc = parseJsonToolCandidate(rawJson, 'inline');
|
| 501 |
-
if (tc) return tc;
|
| 502 |
-
}
|
| 503 |
-
|
| 504 |
-
console.log(`[parseToolCall] No tool call match in ${text.length} chars`);
|
| 505 |
-
return null;
|
| 506 |
-
}
|
| 507 |
-
|
| 508 |
-
/**
|
| 509 |
-
* Strip surrogate characters and other problematic Unicode from text
|
| 510 |
-
* to prevent httpx/urlencode crashes when the gateway sends to Telegram.
|
| 511 |
-
*/
|
| 512 |
-
function sanitizeContent(text) {
|
| 513 |
-
return text.replace(/[\ud800-\udfff]/g, '');
|
| 514 |
-
}
|
| 515 |
-
|
| 516 |
-
function estimateTokens(text) {
|
| 517 |
-
return text ? Math.ceil(String(text).length / 4) : 0;
|
| 518 |
-
}
|
| 519 |
-
|
| 520 |
-
function buildUsage(prompt, content, reasoningContent = '') {
|
| 521 |
-
const promptTokens = estimateTokens(prompt);
|
| 522 |
-
const contentTokens = estimateTokens(content);
|
| 523 |
-
const reasoningTokens = estimateTokens(reasoningContent);
|
| 524 |
-
const completionTokens = contentTokens + reasoningTokens;
|
| 525 |
-
return {
|
| 526 |
-
prompt_tokens: promptTokens,
|
| 527 |
-
completion_tokens: completionTokens,
|
| 528 |
-
total_tokens: promptTokens + completionTokens,
|
| 529 |
-
completion_tokens_details: {
|
| 530 |
-
reasoning_tokens: reasoningTokens
|
| 531 |
-
}
|
| 532 |
-
};
|
| 533 |
-
}
|
| 534 |
-
|
| 535 |
-
function buildToolCallResponse(toolCall, model = 'deepseek-default', prompt = '', reasoningContent = '') {
|
| 536 |
-
const id = 'call_' + Date.now() + '_' + Math.random().toString(36).substring(2, 8);
|
| 537 |
-
const message = {
|
| 538 |
-
role: 'assistant',
|
| 539 |
-
content: null,
|
| 540 |
-
tool_calls: [{
|
| 541 |
-
id: id,
|
| 542 |
-
type: 'function',
|
| 543 |
-
function: { name: toolCall.name, arguments: toolCall.arguments }
|
| 544 |
-
}]
|
| 545 |
-
};
|
| 546 |
-
// Do not attach reasoning to tool-call turns. Some agent clients treat any
|
| 547 |
-
// reasoning/text payload as a final assistant answer and stop their tool loop.
|
| 548 |
-
return {
|
| 549 |
-
id: 'ds-' + Date.now(),
|
| 550 |
-
object: 'chat.completion',
|
| 551 |
-
created: Math.floor(Date.now() / 1000),
|
| 552 |
-
model,
|
| 553 |
-
choices: [{
|
| 554 |
-
index: 0,
|
| 555 |
-
message,
|
| 556 |
-
finish_reason: 'tool_calls'
|
| 557 |
-
}],
|
| 558 |
-
usage: buildUsage(prompt, '', reasoningContent),
|
| 559 |
-
watermark: FORGETMEAI_WATERMARK
|
| 560 |
-
};
|
| 561 |
-
}
|
| 562 |
-
|
| 563 |
-
function buildTextResponse(content, prompt, model = 'deepseek-default', reasoningContent = '') {
|
| 564 |
-
const message = { role: 'assistant', content };
|
| 565 |
-
if (reasoningContent) message.reasoning_content = reasoningContent;
|
| 566 |
-
return {
|
| 567 |
-
id: 'ds-' + Date.now(),
|
| 568 |
-
object: 'chat.completion',
|
| 569 |
-
created: Math.floor(Date.now() / 1000),
|
| 570 |
-
model,
|
| 571 |
-
choices: [{
|
| 572 |
-
index: 0,
|
| 573 |
-
message,
|
| 574 |
-
finish_reason: 'stop'
|
| 575 |
-
}],
|
| 576 |
-
usage: buildUsage(prompt, content, reasoningContent),
|
| 577 |
-
watermark: FORGETMEAI_WATERMARK
|
| 578 |
-
};
|
| 579 |
-
}
|
| 580 |
-
|
| 581 |
-
function normalizeMessageContent(content) {
|
| 582 |
-
if (content === null || content === undefined) return '';
|
| 583 |
-
if (typeof content === 'string') return content;
|
| 584 |
-
if (Array.isArray(content)) {
|
| 585 |
-
return content.map(part => {
|
| 586 |
-
if (typeof part === 'string') return part;
|
| 587 |
-
if (!part || typeof part !== 'object') return '';
|
| 588 |
-
if (part.type === 'text' || part.type === 'input_text' || part.type === 'output_text') return part.text || '';
|
| 589 |
-
if (part.type === 'tool_result') return `[Tool Result ${part.tool_use_id || ''}]\n${normalizeMessageContent(part.content)}`;
|
| 590 |
-
if (part.type === 'image_url') return `[Image: ${part.image_url?.url || ''}]`;
|
| 591 |
-
return part.text || part.content || JSON.stringify(part);
|
| 592 |
-
}).filter(Boolean).join('\n');
|
| 593 |
-
}
|
| 594 |
-
return String(content);
|
| 595 |
-
}
|
| 596 |
-
|
| 597 |
-
function normalizeAnthropicTools(tools = []) {
|
| 598 |
-
return (tools || []).map(tool => ({
|
| 599 |
-
type: 'function',
|
| 600 |
-
function: {
|
| 601 |
-
name: tool.name,
|
| 602 |
-
description: tool.description || '',
|
| 603 |
-
parameters: tool.input_schema || tool.parameters || { type: 'object', properties: {} }
|
| 604 |
-
}
|
| 605 |
-
})).filter(tool => tool.function.name);
|
| 606 |
-
}
|
| 607 |
-
|
| 608 |
-
function normalizeResponsesTools(tools = []) {
|
| 609 |
-
return (tools || []).map(tool => {
|
| 610 |
-
if (tool.type === 'function' && tool.function) return tool;
|
| 611 |
-
if (tool.type === 'function' && tool.name) {
|
| 612 |
-
return { type: 'function', function: { name: tool.name, description: tool.description || '', parameters: tool.parameters || { type: 'object', properties: {} } } };
|
| 613 |
-
}
|
| 614 |
-
return null;
|
| 615 |
-
}).filter(Boolean);
|
| 616 |
-
}
|
| 617 |
-
|
| 618 |
-
function normalizeResponsesInput(input) {
|
| 619 |
-
if (typeof input === 'string') return [{ role: 'user', content: input }];
|
| 620 |
-
if (!Array.isArray(input)) return [];
|
| 621 |
-
const messages = [];
|
| 622 |
-
for (const item of input) {
|
| 623 |
-
if (!item || typeof item !== 'object') continue;
|
| 624 |
-
if (item.type === 'message') {
|
| 625 |
-
messages.push({ role: item.role || 'user', content: normalizeMessageContent(item.content) });
|
| 626 |
-
} else if (item.role) {
|
| 627 |
-
messages.push({ role: item.role, content: normalizeMessageContent(item.content) });
|
| 628 |
-
} else if (item.type === 'function_call_output') {
|
| 629 |
-
messages.push({ role: 'tool', tool_call_id: item.call_id, content: item.output || '' });
|
| 630 |
-
} else if (item.type === 'input_text') {
|
| 631 |
-
messages.push({ role: 'user', content: item.text || '' });
|
| 632 |
-
}
|
| 633 |
-
}
|
| 634 |
-
return messages;
|
| 635 |
-
}
|
| 636 |
-
|
| 637 |
-
function normalizeApiParams(params, apiMode) {
|
| 638 |
-
if (apiMode === 'anthropic') {
|
| 639 |
-
const messages = [];
|
| 640 |
-
if (params.system) messages.push({ role: 'system', content: normalizeMessageContent(params.system) });
|
| 641 |
-
for (const msg of params.messages || []) {
|
| 642 |
-
if (msg.role === 'assistant' && Array.isArray(msg.content)) {
|
| 643 |
-
const toolUses = msg.content.filter(part => part && part.type === 'tool_use');
|
| 644 |
-
const text = normalizeMessageContent(msg.content.filter(part => !part || part.type !== 'tool_use'));
|
| 645 |
-
if (text) messages.push({ role: 'assistant', content: text });
|
| 646 |
-
for (const tu of toolUses) {
|
| 647 |
-
messages.push({ role: 'assistant', content: null, tool_calls: [{ id: tu.id, type: 'function', function: { name: tu.name, arguments: JSON.stringify(tu.input || {}) } }] });
|
| 648 |
-
}
|
| 649 |
-
} else if (msg.role === 'user' && Array.isArray(msg.content) && msg.content.some(part => part && part.type === 'tool_result')) {
|
| 650 |
-
for (const part of msg.content) {
|
| 651 |
-
if (part && part.type === 'tool_result') messages.push({ role: 'tool', tool_call_id: part.tool_use_id, content: normalizeMessageContent(part.content) });
|
| 652 |
-
else messages.push({ role: 'user', content: normalizeMessageContent(part) });
|
| 653 |
-
}
|
| 654 |
-
} else {
|
| 655 |
-
messages.push({ role: msg.role || 'user', content: normalizeMessageContent(msg.content) });
|
| 656 |
-
}
|
| 657 |
-
}
|
| 658 |
-
return {
|
| 659 |
-
...params,
|
| 660 |
-
model: params.model || 'deepseek-chat',
|
| 661 |
-
messages,
|
| 662 |
-
tools: normalizeAnthropicTools(params.tools || []),
|
| 663 |
-
stream: params.stream === true,
|
| 664 |
-
user: params.metadata?.user_id || params.user,
|
| 665 |
-
};
|
| 666 |
-
}
|
| 667 |
-
if (apiMode === 'responses') {
|
| 668 |
-
const messages = normalizeResponsesInput(params.input);
|
| 669 |
-
if (params.instructions) messages.unshift({ role: 'system', content: params.instructions });
|
| 670 |
-
return {
|
| 671 |
-
...params,
|
| 672 |
-
model: params.model || 'deepseek-chat',
|
| 673 |
-
messages,
|
| 674 |
-
tools: normalizeResponsesTools(params.tools || []),
|
| 675 |
-
stream: params.stream === true,
|
| 676 |
-
user: params.user,
|
| 677 |
-
};
|
| 678 |
-
}
|
| 679 |
-
return params;
|
| 680 |
-
}
|
| 681 |
-
|
| 682 |
-
function safeJsonParseObject(text, fallback = {}) {
|
| 683 |
-
try {
|
| 684 |
-
const parsed = JSON.parse(text || '{}');
|
| 685 |
-
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : fallback;
|
| 686 |
-
} catch (e) {
|
| 687 |
-
return fallback;
|
| 688 |
-
}
|
| 689 |
-
}
|
| 690 |
-
|
| 691 |
-
function toAnthropicResponse(openaiResp) {
|
| 692 |
-
const choice = openaiResp.choices[0];
|
| 693 |
-
const msg = choice.message || {};
|
| 694 |
-
const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
|
| 695 |
-
const content = [];
|
| 696 |
-
if (hasToolCalls) {
|
| 697 |
-
for (const tc of msg.tool_calls) {
|
| 698 |
-
content.push({ type: 'tool_use', id: tc.id, name: tc.function.name, input: safeJsonParseObject(tc.function.arguments) });
|
| 699 |
-
}
|
| 700 |
-
} else {
|
| 701 |
-
content.push({ type: 'text', text: msg.content || '' });
|
| 702 |
-
}
|
| 703 |
-
const response = {
|
| 704 |
-
id: 'msg_' + openaiResp.id,
|
| 705 |
-
type: 'message',
|
| 706 |
-
role: 'assistant',
|
| 707 |
-
model: openaiResp.model,
|
| 708 |
-
content,
|
| 709 |
-
stop_reason: choice.finish_reason === 'tool_calls' ? 'tool_use' : 'end_turn',
|
| 710 |
-
stop_sequence: null,
|
| 711 |
-
usage: {
|
| 712 |
-
input_tokens: openaiResp.usage?.prompt_tokens || 0,
|
| 713 |
-
output_tokens: openaiResp.usage?.completion_tokens || 0,
|
| 714 |
-
},
|
| 715 |
-
watermark: FORGETMEAI_WATERMARK,
|
| 716 |
-
};
|
| 717 |
-
if (!hasToolCalls && msg.reasoning_content) response.reasoning_content = msg.reasoning_content;
|
| 718 |
-
return response;
|
| 719 |
-
}
|
| 720 |
-
|
| 721 |
-
function writeSse(res, event, data) {
|
| 722 |
-
if (event) res.write(`event: ${event}\n`);
|
| 723 |
-
res.write(`data: ${JSON.stringify(data)}\n\n`);
|
| 724 |
-
}
|
| 725 |
-
|
| 726 |
-
function sendAnthropicStream(res, openaiResp) {
|
| 727 |
-
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' });
|
| 728 |
-
const choice = openaiResp.choices[0];
|
| 729 |
-
const msg = choice.message || {};
|
| 730 |
-
const message = toAnthropicResponse(openaiResp);
|
| 731 |
-
const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
|
| 732 |
-
writeSse(res, 'message_start', { type: 'message_start', message: { ...message, content: [] } });
|
| 733 |
-
|
| 734 |
-
// Anthropic-compatible clients expect a tool turn to be made of tool_use
|
| 735 |
-
// content blocks. If we emit DeepSeek reasoning as a text block before the
|
| 736 |
-
// tool_use block, some agents treat the turn as a normal text answer and do
|
| 737 |
-
// not execute the tool. Keep tool streaming clean: tool_use blocks only.
|
| 738 |
-
if (hasToolCalls) {
|
| 739 |
-
msg.tool_calls.forEach((tc, i) => {
|
| 740 |
-
writeSse(res, 'content_block_start', { type: 'content_block_start', index: i, content_block: { type: 'tool_use', id: tc.id, name: tc.function.name, input: {} } });
|
| 741 |
-
writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: i, delta: { type: 'input_json_delta', partial_json: tc.function.arguments || '{}' } });
|
| 742 |
-
writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: i });
|
| 743 |
-
});
|
| 744 |
-
writeSse(res, 'message_delta', { type: 'message_delta', delta: { stop_reason: 'tool_use', stop_sequence: null }, usage: message.usage });
|
| 745 |
-
} else {
|
| 746 |
-
if (msg.reasoning_content) {
|
| 747 |
-
writeSse(res, 'content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } });
|
| 748 |
-
writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: `[reasoning]\n${msg.reasoning_content}\n[/reasoning]\n` } });
|
| 749 |
-
writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: 0 });
|
| 750 |
-
}
|
| 751 |
-
const offset = msg.reasoning_content ? 1 : 0;
|
| 752 |
-
writeSse(res, 'content_block_start', { type: 'content_block_start', index: offset, content_block: { type: 'text', text: '' } });
|
| 753 |
-
const text = msg.content || '';
|
| 754 |
-
for (let i = 0; i < text.length; i += 80) {
|
| 755 |
-
writeSse(res, 'content_block_delta', { type: 'content_block_delta', index: offset, delta: { type: 'text_delta', text: text.substring(i, i + 80) } });
|
| 756 |
-
}
|
| 757 |
-
writeSse(res, 'content_block_stop', { type: 'content_block_stop', index: offset });
|
| 758 |
-
writeSse(res, 'message_delta', { type: 'message_delta', delta: { stop_reason: 'end_turn', stop_sequence: null }, usage: message.usage });
|
| 759 |
-
}
|
| 760 |
-
writeSse(res, 'message_stop', { type: 'message_stop' });
|
| 761 |
-
res.end();
|
| 762 |
-
}
|
| 763 |
-
|
| 764 |
-
function toResponsesResponse(openaiResp) {
|
| 765 |
-
const choice = openaiResp.choices[0];
|
| 766 |
-
const msg = choice.message || {};
|
| 767 |
-
const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
|
| 768 |
-
const output = [];
|
| 769 |
-
if (!hasToolCalls && msg.reasoning_content) {
|
| 770 |
-
output.push({ id: 'rs_' + Date.now(), type: 'reasoning', summary: [{ type: 'summary_text', text: msg.reasoning_content }] });
|
| 771 |
-
}
|
| 772 |
-
if (hasToolCalls) {
|
| 773 |
-
for (const tc of msg.tool_calls) {
|
| 774 |
-
output.push({ type: 'function_call', id: 'fc_' + tc.id, call_id: tc.id, name: tc.function.name, arguments: tc.function.arguments || '{}' });
|
| 775 |
-
}
|
| 776 |
-
} else {
|
| 777 |
-
output.push({ id: 'msg_' + Date.now(), type: 'message', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text: msg.content || '', annotations: [] }] });
|
| 778 |
-
}
|
| 779 |
-
return {
|
| 780 |
-
id: openaiResp.id.replace(/^ds-/, 'resp_'),
|
| 781 |
-
object: 'response',
|
| 782 |
-
created_at: openaiResp.created,
|
| 783 |
-
status: 'completed',
|
| 784 |
-
model: openaiResp.model,
|
| 785 |
-
output,
|
| 786 |
-
output_text: msg.content || '',
|
| 787 |
-
usage: {
|
| 788 |
-
input_tokens: openaiResp.usage?.prompt_tokens || 0,
|
| 789 |
-
output_tokens: openaiResp.usage?.completion_tokens || 0,
|
| 790 |
-
total_tokens: openaiResp.usage?.total_tokens || 0,
|
| 791 |
-
output_tokens_details: { reasoning_tokens: openaiResp.usage?.completion_tokens_details?.reasoning_tokens || 0 },
|
| 792 |
-
},
|
| 793 |
-
watermark: FORGETMEAI_WATERMARK,
|
| 794 |
-
};
|
| 795 |
-
}
|
| 796 |
-
|
| 797 |
-
function sendResponsesStream(res, openaiResp) {
|
| 798 |
-
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' });
|
| 799 |
-
const response = toResponsesResponse(openaiResp);
|
| 800 |
-
const choice = openaiResp.choices[0];
|
| 801 |
-
const msg = choice.message || {};
|
| 802 |
-
const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
|
| 803 |
-
writeSse(res, 'response.created', { type: 'response.created', response: { ...response, status: 'in_progress', output: [] } });
|
| 804 |
-
writeSse(res, 'response.in_progress', { type: 'response.in_progress', response: { ...response, status: 'in_progress', output: [] } });
|
| 805 |
-
let outputIndex = 0;
|
| 806 |
-
if (!hasToolCalls && msg.reasoning_content) {
|
| 807 |
-
const reasoningItem = { id: 'rs_' + Date.now(), type: 'reasoning', summary: [], status: 'completed' };
|
| 808 |
-
writeSse(res, 'response.output_item.added', { type: 'response.output_item.added', output_index: outputIndex, item: { ...reasoningItem, status: 'in_progress' } });
|
| 809 |
-
writeSse(res, 'response.reasoning_summary_text.delta', { type: 'response.reasoning_summary_text.delta', output_index: outputIndex, summary_index: 0, delta: msg.reasoning_content });
|
| 810 |
-
writeSse(res, 'response.output_item.done', { type: 'response.output_item.done', output_index: outputIndex, item: { ...reasoningItem, summary: [{ type: 'summary_text', text: msg.reasoning_content }] } });
|
| 811 |
-
outputIndex++;
|
| 812 |
-
}
|
| 813 |
-
if (hasToolCalls) {
|
| 814 |
-
msg.tool_calls.forEach((tc) => {
|
| 815 |
-
const item = { type: 'function_call', id: 'fc_' + tc.id, call_id: tc.id, name: tc.function.name, arguments: tc.function.arguments || '{}', status: 'completed' };
|
| 816 |
-
writeSse(res, 'response.output_item.added', { type: 'response.output_item.added', output_index: outputIndex, item: { ...item, arguments: '', status: 'in_progress' } });
|
| 817 |
-
writeSse(res, 'response.function_call_arguments.delta', { type: 'response.function_call_arguments.delta', output_index: outputIndex, item_id: item.id, delta: item.arguments });
|
| 818 |
-
writeSse(res, 'response.function_call_arguments.done', { type: 'response.function_call_arguments.done', output_index: outputIndex, item_id: item.id, arguments: item.arguments });
|
| 819 |
-
writeSse(res, 'response.output_item.done', { type: 'response.output_item.done', output_index: outputIndex, item });
|
| 820 |
-
outputIndex++;
|
| 821 |
-
});
|
| 822 |
-
} else {
|
| 823 |
-
const text = msg.content || '';
|
| 824 |
-
const item = { id: 'msg_' + Date.now(), type: 'message', role: 'assistant', status: 'completed', content: [{ type: 'output_text', text, annotations: [] }] };
|
| 825 |
-
writeSse(res, 'response.output_item.added', { type: 'response.output_item.added', output_index: outputIndex, item: { ...item, status: 'in_progress', content: [] } });
|
| 826 |
-
writeSse(res, 'response.content_part.added', { type: 'response.content_part.added', output_index: outputIndex, content_index: 0, item_id: item.id, part: { type: 'output_text', text: '', annotations: [] } });
|
| 827 |
-
for (let i = 0; i < text.length; i += 80) {
|
| 828 |
-
writeSse(res, 'response.output_text.delta', { type: 'response.output_text.delta', output_index: outputIndex, content_index: 0, item_id: item.id, delta: text.substring(i, i + 80) });
|
| 829 |
-
}
|
| 830 |
-
writeSse(res, 'response.output_text.done', { type: 'response.output_text.done', output_index: outputIndex, content_index: 0, item_id: item.id, text });
|
| 831 |
-
writeSse(res, 'response.content_part.done', { type: 'response.content_part.done', output_index: outputIndex, content_index: 0, item_id: item.id, part: item.content[0] });
|
| 832 |
-
writeSse(res, 'response.output_item.done', { type: 'response.output_item.done', output_index: outputIndex, item });
|
| 833 |
-
}
|
| 834 |
-
writeSse(res, 'response.completed', { type: 'response.completed', response });
|
| 835 |
-
res.write('data: [DONE]\n\n');
|
| 836 |
-
res.end();
|
| 837 |
-
}
|
| 838 |
-
|
| 839 |
-
function sendOpenAIStream(res, openaiResp) {
|
| 840 |
-
res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive', 'Access-Control-Allow-Origin': '*' });
|
| 841 |
-
const choice = openaiResp.choices[0];
|
| 842 |
-
const msg = choice.message || {};
|
| 843 |
-
const id = openaiResp.id;
|
| 844 |
-
const created = openaiResp.created;
|
| 845 |
-
const model = openaiResp.model;
|
| 846 |
-
const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
|
| 847 |
-
if (!hasToolCalls && msg.reasoning_content) {
|
| 848 |
-
for (let i = 0; i < msg.reasoning_content.length; i += 50) {
|
| 849 |
-
const chunk = msg.reasoning_content.substring(i, i + 50);
|
| 850 |
-
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: { reasoning_content: chunk }, finish_reason: null }] })}\n\n`);
|
| 851 |
-
}
|
| 852 |
-
}
|
| 853 |
-
if (hasToolCalls) {
|
| 854 |
-
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: { role: 'assistant', content: null, tool_calls: msg.tool_calls }, finish_reason: null }] })}\n\n`);
|
| 855 |
-
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: {}, finish_reason: 'tool_calls' }] })}\n\ndata: [DONE]\n\n`);
|
| 856 |
-
} else {
|
| 857 |
-
for (let i = 0; i < (msg.content || '').length; i += 50) {
|
| 858 |
-
const chunk = msg.content.substring(i, i + 50);
|
| 859 |
-
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: { content: chunk }, finish_reason: null }] })}\n\n`);
|
| 860 |
-
}
|
| 861 |
-
res.write(`data: ${JSON.stringify({ id, object: 'chat.completion.chunk', created, model, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`);
|
| 862 |
-
}
|
| 863 |
-
res.end();
|
| 864 |
-
}
|
| 865 |
-
|
| 866 |
-
function storeHistory(agentId, prompt, content, toolCall) {
|
| 867 |
-
const session = getOrCreateAgentSession(agentId);
|
| 868 |
-
const assistantResponse = toolCall
|
| 869 |
-
? `TOOL_CALL: ${toolCall.name}\narguments: ${toolCall.arguments}`
|
| 870 |
-
: content;
|
| 871 |
-
// Save last 500 chars of the prompt for history context
|
| 872 |
-
const shortPrompt = prompt.length > 500 ? '...' + prompt.substring(prompt.length - 500) : prompt;
|
| 873 |
-
session.history.push({ user: shortPrompt, assistant: assistantResponse });
|
| 874 |
-
while (session.history.length > MAX_HISTORY_LENGTH) session.history.shift();
|
| 875 |
-
let historyChars = session.history.reduce((sum, e) => sum + e.user.length + e.assistant.length, 0);
|
| 876 |
-
while (historyChars > MAX_HISTORY_CHARS && session.history.length > 1) {
|
| 877 |
-
const removed = session.history.shift();
|
| 878 |
-
historyChars -= removed.user.length + removed.assistant.length;
|
| 879 |
-
}
|
| 880 |
-
}
|
| 881 |
-
|
| 882 |
-
// Extract MEDIA: paths from tool results that contain screenshot paths
|
| 883 |
-
function extractScreenshotPaths(messages) {
|
| 884 |
-
const paths = [];
|
| 885 |
-
const fs = require('fs');
|
| 886 |
-
for (const msg of messages) {
|
| 887 |
-
if (msg.role === 'tool' && msg.content) {
|
| 888 |
-
// Look for screenshot_path or path fields in JSON tool results
|
| 889 |
-
// These come DIRECTLY from browser_vision — always the real path
|
| 890 |
-
const pngMatch = msg.content.match(/["'](screenshot_path|path)["']\s*:\s*["']([^"']+\.(?:png|jpg|jpeg|webp|gif))["']/i);
|
| 891 |
-
if (pngMatch) {
|
| 892 |
-
const filePath = pngMatch[2];
|
| 893 |
-
if (filePath.startsWith('/') && fs.existsSync(filePath)) {
|
| 894 |
-
paths.push(`MEDIA:${filePath}`);
|
| 895 |
-
}
|
| 896 |
-
}
|
| 897 |
-
// Also catch plain MEDIA: tags
|
| 898 |
-
const mediaMatch = msg.content.match(/MEDIA:(\S+)/g);
|
| 899 |
-
if (mediaMatch) {
|
| 900 |
-
for (const tag of mediaMatch) {
|
| 901 |
-
const extractedPath = tag.replace(/^MEDIA:/, '');
|
| 902 |
-
if (fs.existsSync(extractedPath) && !paths.includes(tag)) {
|
| 903 |
-
paths.push(tag);
|
| 904 |
-
}
|
| 905 |
-
}
|
| 906 |
-
}
|
| 907 |
-
}
|
| 908 |
-
// Check user/assistant messages for paths mentioned in conversation text
|
| 909 |
-
// Only include if the file ACTUALLY EXISTS (DeepSeek hallucinates paths)
|
| 910 |
-
if ((msg.role === 'user' || msg.role === 'assistant') && msg.content) {
|
| 911 |
-
const content = typeof msg.content === 'string' ? msg.content : '';
|
| 912 |
-
const pathRegex = /(\/[^\s<>"']+\.(?:png|jpg|jpeg|webp|gif))/gi;
|
| 913 |
-
let match;
|
| 914 |
-
while ((match = pathRegex.exec(content)) !== null) {
|
| 915 |
-
const filePath = match[1];
|
| 916 |
-
if (filePath.startsWith('/') && fs.existsSync(filePath) && !paths.includes(`MEDIA:${filePath}`)) {
|
| 917 |
-
paths.push(`MEDIA:${filePath}`);
|
| 918 |
-
}
|
| 919 |
-
}
|
| 920 |
-
}
|
| 921 |
-
}
|
| 922 |
-
return paths;
|
| 923 |
-
}
|
| 924 |
-
|
| 925 |
-
function formatMessages(messages, tools) {
|
| 926 |
-
let systemPrompt = '';
|
| 927 |
-
for (const msg of messages) {
|
| 928 |
-
if (msg.role === 'system' && msg.content) {
|
| 929 |
-
systemPrompt += msg.content + '\n';
|
| 930 |
-
}
|
| 931 |
-
}
|
| 932 |
-
systemPrompt += formatToolDefinitions(tools);
|
| 933 |
-
|
| 934 |
-
// Build full conversation history for DeepSeek's context
|
| 935 |
-
let conversation = '';
|
| 936 |
-
for (const msg of messages) {
|
| 937 |
-
if (msg.role === 'system') continue; // already in systemPrompt
|
| 938 |
-
if (msg.role === 'user' && msg.content) {
|
| 939 |
-
conversation += `User: ${msg.content}\n\n`;
|
| 940 |
-
} else if (msg.role === 'assistant') {
|
| 941 |
-
if (msg.tool_calls && msg.tool_calls.length > 0) {
|
| 942 |
-
// This was a tool call response from a previous turn
|
| 943 |
-
for (const tc of msg.tool_calls) {
|
| 944 |
-
conversation += `Assistant: TOOL_CALL: ${tc.function.name}\narguments: ${tc.function.arguments}\n\n`;
|
| 945 |
-
}
|
| 946 |
-
} else if (msg.content) {
|
| 947 |
-
conversation += `Assistant: ${msg.content}\n\n`;
|
| 948 |
-
}
|
| 949 |
-
} else if (msg.role === 'tool' && msg.content) {
|
| 950 |
-
// Tool execution result — send back to DeepSeek as context
|
| 951 |
-
const truncated = msg.content.length > 8000
|
| 952 |
-
? msg.content.substring(0, 8000) + '\n...[truncated]'
|
| 953 |
-
: msg.content;
|
| 954 |
-
conversation += `[Tool Result]\n${truncated}\n\n`;
|
| 955 |
-
}
|
| 956 |
-
}
|
| 957 |
-
// The last user message + full conversation context
|
| 958 |
-
return { prompt: conversation.trim(), systemPrompt: systemPrompt.trim() };
|
| 959 |
-
}
|
| 960 |
-
|
| 961 |
-
// === HTTP Server ===
|
| 962 |
-
const server = http.createServer(async (req, res) => {
|
| 963 |
-
res.setHeader('Access-Control-Allow-Origin', '*');
|
| 964 |
-
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
|
| 965 |
-
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
|
| 966 |
-
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
|
| 967 |
-
|
| 968 |
-
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
| 969 |
-
|
| 970 |
-
// Health check
|
| 971 |
-
if (req.method === 'GET' && (url.pathname === '/' || url.pathname === '/health')) {
|
| 972 |
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
| 973 |
-
res.end(JSON.stringify({ status: 'ok', service: 'FreeDeepseekAPI', watermark: FORGETMEAI_WATERMARK, models: SUPPORTED_MODEL_IDS, unsupported_models: Object.keys(MODEL_CONFIGS).filter(id => !MODEL_CONFIGS[id].supported), agents: sessions.size, config_ready: hasAuthConfig() }));
|
| 974 |
-
return;
|
| 975 |
-
}
|
| 976 |
-
|
| 977 |
-
// Models: OpenAI-compatible list exposes only aliases verified to work through this proxy.
|
| 978 |
-
if (req.method === 'GET' && url.pathname === '/v1/models') {
|
| 979 |
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
| 980 |
-
res.end(JSON.stringify({ object: 'list', data: SUPPORTED_MODEL_IDS.map(id => ({ id, object: 'model', created: 1700000000, owned_by: 'deepseek-web', real_model: MODEL_CONFIGS[id].real_model, capabilities: MODEL_CONFIGS[id].capabilities })) }));
|
| 981 |
-
return;
|
| 982 |
-
}
|
| 983 |
-
|
| 984 |
-
// Full mapping, including Web models observed but not currently usable through the direct API.
|
| 985 |
-
if (req.method === 'GET' && (url.pathname === '/v1/model-capabilities' || url.pathname === '/api/model-capabilities')) {
|
| 986 |
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
| 987 |
-
res.end(JSON.stringify({ object: 'model_capabilities', watermark: FORGETMEAI_WATERMARK, data: ALL_MODEL_CAPABILITIES }));
|
| 988 |
-
return;
|
| 989 |
-
}
|
| 990 |
-
|
| 991 |
-
// Sessions status
|
| 992 |
-
if (req.method === 'GET' && url.pathname === '/v1/sessions') {
|
| 993 |
-
const agentList = [];
|
| 994 |
-
for (const [agentId, session] of sessions) {
|
| 995 |
-
agentList.push({
|
| 996 |
-
agent: agentId,
|
| 997 |
-
session_id: session.id,
|
| 998 |
-
message_count: session.messageCount,
|
| 999 |
-
history_size: session.history.length,
|
| 1000 |
-
age_min: session.createdAt ? Math.round((Date.now() - session.createdAt) / 60000) : 0,
|
| 1001 |
-
});
|
| 1002 |
-
}
|
| 1003 |
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
| 1004 |
-
res.end(JSON.stringify({ agents: agentList, total: agentList.length }));
|
| 1005 |
-
return;
|
| 1006 |
-
}
|
| 1007 |
-
|
| 1008 |
-
// Reset session for a specific agent (or all if no agent specified)
|
| 1009 |
-
if (req.method === 'POST' && url.pathname === '/reset-session') {
|
| 1010 |
-
const agentId = url.searchParams.get('agent') || 'default';
|
| 1011 |
-
if (agentId === 'all') {
|
| 1012 |
-
const count = sessions.size;
|
| 1013 |
-
sessions.clear();
|
| 1014 |
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
| 1015 |
-
res.end(JSON.stringify({ status: 'all_sessions_cleared', count }));
|
| 1016 |
-
return;
|
| 1017 |
-
}
|
| 1018 |
-
const session = sessions.get(agentId);
|
| 1019 |
-
if (!session) {
|
| 1020 |
-
res.writeHead(404, { 'Content-Type': 'application/json' });
|
| 1021 |
-
res.end(JSON.stringify({ error: `No session for agent: ${agentId}` }));
|
| 1022 |
-
return;
|
| 1023 |
-
}
|
| 1024 |
-
const historyCount = session.history.length;
|
| 1025 |
-
const historyPreview = session.history.map(e => e.user.substring(0, 40)).join(' | ');
|
| 1026 |
-
session.id = null;
|
| 1027 |
-
session.parentMessageId = null;
|
| 1028 |
-
session.createdAt = null;
|
| 1029 |
-
session.messageCount = 0;
|
| 1030 |
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
| 1031 |
-
res.end(JSON.stringify({ status: 'session_reset', agent: agentId, history_preserved: historyCount, history: historyPreview }));
|
| 1032 |
-
return;
|
| 1033 |
-
}
|
| 1034 |
-
|
| 1035 |
-
const apiMode = url.pathname === '/v1/messages'
|
| 1036 |
-
? 'anthropic'
|
| 1037 |
-
: (url.pathname === '/v1/responses' ? 'responses' : 'openai');
|
| 1038 |
-
const acceptedPostPaths = ['/v1/chat/completions', '/v1/messages', '/v1/responses'];
|
| 1039 |
-
if (req.method !== 'POST' || !acceptedPostPaths.includes(url.pathname)) {
|
| 1040 |
-
res.writeHead(404); res.end('Not found'); return;
|
| 1041 |
-
}
|
| 1042 |
-
|
| 1043 |
-
let body = '';
|
| 1044 |
-
req.on('data', chunk => body += chunk);
|
| 1045 |
-
req.on('end', async () => {
|
| 1046 |
-
try {
|
| 1047 |
-
const rawParams = JSON.parse(body || '{}');
|
| 1048 |
-
const params = normalizeApiParams(rawParams, apiMode);
|
| 1049 |
-
const messages = params.messages || [];
|
| 1050 |
-
const tools = params.tools || [];
|
| 1051 |
-
const stream = params.stream === true;
|
| 1052 |
-
const requestedModel = String(params.model || 'deepseek-chat').toLowerCase();
|
| 1053 |
-
if (!isKnownModel(requestedModel)) {
|
| 1054 |
-
res.writeHead(400, { 'Content-Type': 'application/json' });
|
| 1055 |
-
res.end(JSON.stringify({ error: { message: `Unknown model: ${requestedModel}`, type: 'invalid_model', supported_models: SUPPORTED_MODEL_IDS, model_capabilities_url: '/v1/model-capabilities' } }));
|
| 1056 |
-
return;
|
| 1057 |
-
}
|
| 1058 |
-
if (!isSupportedModel(requestedModel)) {
|
| 1059 |
-
const cfg = resolveModelConfig(requestedModel);
|
| 1060 |
-
res.writeHead(400, { 'Content-Type': 'application/json' });
|
| 1061 |
-
res.end(JSON.stringify({ error: { message: `${requestedModel} is not currently supported through this DeepSeek Web API path`, type: 'unsupported_model', model: requestedModel, real_model: cfg.real_model, reason: cfg.unavailable_reason, capabilities: cfg.capabilities, supported_models: SUPPORTED_MODEL_IDS } }));
|
| 1062 |
-
return;
|
| 1063 |
-
}
|
| 1064 |
-
// Use remote IP for session isolation (local gets 'dev-agent', external per-IP)
|
| 1065 |
-
const remoteAddr = req.socket.remoteAddress || 'unknown';
|
| 1066 |
-
const requestedSession = req.headers['x-agent-session'] || params.session || params.user;
|
| 1067 |
-
const agentId = requestedSession
|
| 1068 |
-
? String(requestedSession)
|
| 1069 |
-
: ((remoteAddr === '127.0.0.1' || remoteAddr === '::1' || remoteAddr === '::ffff:127.0.0.1') ? 'dev-agent' : remoteAddr);
|
| 1070 |
-
const agentTag = `[${agentId}]`;
|
| 1071 |
-
const { prompt, systemPrompt } = formatMessages(messages, tools);
|
| 1072 |
-
|
| 1073 |
-
const session = getOrCreateAgentSession(agentId);
|
| 1074 |
-
|
| 1075 |
-
// Build history prefix if starting fresh
|
| 1076 |
-
let historyPrefix = '';
|
| 1077 |
-
if (!session.id && session.history.length > 0) {
|
| 1078 |
-
historyPrefix = '[Previous conversation]\n';
|
| 1079 |
-
for (const exchange of session.history) {
|
| 1080 |
-
historyPrefix += `User: ${exchange.user}\nAssistant: ${exchange.assistant}\n\n`;
|
| 1081 |
-
}
|
| 1082 |
-
historyPrefix += '[Continue from here]\n\n';
|
| 1083 |
-
}
|
| 1084 |
-
|
| 1085 |
-
const fullPrompt = systemPrompt
|
| 1086 |
-
? `${systemPrompt}\n\n${historyPrefix}${prompt}`
|
| 1087 |
-
: `${historyPrefix}${prompt}`;
|
| 1088 |
-
|
| 1089 |
-
const startTime = Date.now();
|
| 1090 |
-
const { resp: dsResp } = await askDeepSeekStream(fullPrompt, agentId, requestedModel);
|
| 1091 |
-
|
| 1092 |
-
// Process streaming response from DeepSeek — returns { content, reasoningContent, messageId, finishReason }
|
| 1093 |
-
async function readDeepSeekResponse(readable) {
|
| 1094 |
-
let buffer = '';
|
| 1095 |
-
let lastPath = null;
|
| 1096 |
-
const fragments = [];
|
| 1097 |
-
let fullContent = '';
|
| 1098 |
-
let reasoningContent = '';
|
| 1099 |
-
let newMessageId = null;
|
| 1100 |
-
let finishReason = null;
|
| 1101 |
-
let modelError = null;
|
| 1102 |
-
|
| 1103 |
-
const rebuildFragmentText = () => {
|
| 1104 |
-
const responseText = fragments
|
| 1105 |
-
.filter(f => f && f.type === 'RESPONSE' && typeof f.content === 'string')
|
| 1106 |
-
.map(f => f.content)
|
| 1107 |
-
.join('');
|
| 1108 |
-
const thinkText = fragments
|
| 1109 |
-
.filter(f => f && (f.type === 'THINK' || f.type === 'REASONING') && typeof f.content === 'string')
|
| 1110 |
-
.map(f => f.content)
|
| 1111 |
-
.join('');
|
| 1112 |
-
if (responseText) fullContent = responseText;
|
| 1113 |
-
reasoningContent = thinkText;
|
| 1114 |
-
};
|
| 1115 |
-
|
| 1116 |
-
const appendFragments = (value) => {
|
| 1117 |
-
const incoming = Array.isArray(value) ? value : [value];
|
| 1118 |
-
for (const fragment of incoming) {
|
| 1119 |
-
if (fragment && typeof fragment === 'object') fragments.push({ ...fragment });
|
| 1120 |
-
}
|
| 1121 |
-
rebuildFragmentText();
|
| 1122 |
-
};
|
| 1123 |
-
|
| 1124 |
-
for await (const chunk of readable) {
|
| 1125 |
-
buffer += new TextDecoder().decode(chunk, { stream: true });
|
| 1126 |
-
const lines = buffer.split('\n');
|
| 1127 |
-
buffer = lines.pop() || '';
|
| 1128 |
-
for (const line of lines) {
|
| 1129 |
-
if (line.startsWith('data: ')) {
|
| 1130 |
-
try {
|
| 1131 |
-
const d = JSON.parse(line.slice(6));
|
| 1132 |
-
if (d.response_message_id !== undefined && !newMessageId) newMessageId = d.response_message_id;
|
| 1133 |
-
if (d.type === 'error' || d.finish_reason || d.content) {
|
| 1134 |
-
modelError = { type: d.type || 'error', content: d.content || '', finish_reason: d.finish_reason || null };
|
| 1135 |
-
if (d.finish_reason) finishReason = d.finish_reason;
|
| 1136 |
-
}
|
| 1137 |
-
if (d.p !== undefined) lastPath = d.p;
|
| 1138 |
-
if (d.v && typeof d.v === 'object' && d.v.response) {
|
| 1139 |
-
if (d.v.response.message_id !== undefined) {
|
| 1140 |
-
newMessageId = d.v.response.message_id;
|
| 1141 |
-
}
|
| 1142 |
-
if (d.v.response.content !== undefined) {
|
| 1143 |
-
fullContent = d.v.response.content;
|
| 1144 |
-
}
|
| 1145 |
-
if (Array.isArray(d.v.response.fragments)) {
|
| 1146 |
-
fragments.length = 0;
|
| 1147 |
-
appendFragments(d.v.response.fragments);
|
| 1148 |
-
}
|
| 1149 |
-
if (d.v.response.finish_reason !== undefined) {
|
| 1150 |
-
finishReason = d.v.response.finish_reason;
|
| 1151 |
-
}
|
| 1152 |
-
}
|
| 1153 |
-
if (lastPath === 'response/fragments' && d.v !== undefined) {
|
| 1154 |
-
appendFragments(d.v);
|
| 1155 |
-
}
|
| 1156 |
-
if (lastPath === 'response/fragments/-1/content' && d.v !== undefined && typeof d.v !== 'object') {
|
| 1157 |
-
if (fragments.length > 0) {
|
| 1158 |
-
const lastFragment = fragments[fragments.length - 1];
|
| 1159 |
-
lastFragment.content = `${lastFragment.content || ''}${d.v}`;
|
| 1160 |
-
rebuildFragmentText();
|
| 1161 |
-
}
|
| 1162 |
-
}
|
| 1163 |
-
if (lastPath === 'response/content' && d.v !== undefined && typeof d.v !== 'object') {
|
| 1164 |
-
fullContent += d.v;
|
| 1165 |
-
}
|
| 1166 |
-
if (lastPath === 'response/finish_reason' && d.v !== undefined) {
|
| 1167 |
-
finishReason = d.v;
|
| 1168 |
-
}
|
| 1169 |
-
if (lastPath === 'response/status' && d.v !== undefined && d.v !== 'FINISHED') {
|
| 1170 |
-
finishReason = d.v;
|
| 1171 |
-
}
|
| 1172 |
-
} catch (e) { }
|
| 1173 |
-
}
|
| 1174 |
-
}
|
| 1175 |
-
}
|
| 1176 |
-
|
| 1177 |
-
if (newMessageId) {
|
| 1178 |
-
session.parentMessageId = newMessageId;
|
| 1179 |
-
session.messageCount++;
|
| 1180 |
-
} else {
|
| 1181 |
-
console.log(`${agentTag} WARNING: could not extract message_id`);
|
| 1182 |
-
}
|
| 1183 |
-
|
| 1184 |
-
return { content: fullContent, reasoningContent, messageId: newMessageId, finishReason, modelError };
|
| 1185 |
-
}
|
| 1186 |
-
|
| 1187 |
-
let { content: fullContent, reasoningContent, finishReason, modelError } = await readDeepSeekResponse(dsResp.body);
|
| 1188 |
-
fullContent = sanitizeContent(fullContent);
|
| 1189 |
-
reasoningContent = sanitizeContent(reasoningContent || '');
|
| 1190 |
-
const elapsed = Date.now() - startTime;
|
| 1191 |
-
console.log(`${agentTag} Got ${fullContent.length} chars (+${reasoningContent.length} reasoning chars) in ${elapsed}ms (msg#${session.messageCount})`);
|
| 1192 |
-
|
| 1193 |
-
if ((!fullContent || fullContent.trim().length === 0) && modelError) {
|
| 1194 |
-
res.writeHead(502, { 'Content-Type': 'application/json' });
|
| 1195 |
-
res.end(JSON.stringify({ error: { message: modelError.content || 'DeepSeek returned an error without content', type: modelError.finish_reason || modelError.type || 'deepseek_model_error', model: requestedModel, real_model: resolveModelConfig(requestedModel).real_model } }));
|
| 1196 |
-
return;
|
| 1197 |
-
}
|
| 1198 |
-
|
| 1199 |
-
// Empty response — retry loop with fresh sessions
|
| 1200 |
-
let retryAttempt = 0;
|
| 1201 |
-
const MAX_RETRIES = 10;
|
| 1202 |
-
while (!fullContent || fullContent.trim().length === 0) {
|
| 1203 |
-
retryAttempt++;
|
| 1204 |
-
if (retryAttempt > MAX_RETRIES) {
|
| 1205 |
-
console.log(`${agentTag} Empty after ${MAX_RETRIES} retries. Giving up.`);
|
| 1206 |
-
res.writeHead(502, { 'Content-Type': 'application/json' });
|
| 1207 |
-
res.end(JSON.stringify({
|
| 1208 |
-
error: {
|
| 1209 |
-
message: `DeepSeek returned empty content after ${MAX_RETRIES} retries`,
|
| 1210 |
-
type: 'empty_response',
|
| 1211 |
-
agent: agentId,
|
| 1212 |
-
session_id: session.id,
|
| 1213 |
-
message_count: session.messageCount,
|
| 1214 |
-
history_length: session.history.length,
|
| 1215 |
-
retry_attempts: retryAttempt - 1,
|
| 1216 |
-
}
|
| 1217 |
-
}));
|
| 1218 |
-
return;
|
| 1219 |
-
}
|
| 1220 |
-
console.log(`${agentTag} Empty response (msg#${session.messageCount}, retry ${retryAttempt}/${MAX_RETRIES}). Resetting session...`);
|
| 1221 |
-
session.id = null;
|
| 1222 |
-
session.parentMessageId = null;
|
| 1223 |
-
session.createdAt = null;
|
| 1224 |
-
session.messageCount = 0;
|
| 1225 |
-
// Brief delay before retry to let DeepSeek breathe
|
| 1226 |
-
await new Promise(r => setTimeout(r, Math.min(1000 * retryAttempt, 5000)));
|
| 1227 |
-
const { resp: retryResp } = await askDeepSeekStream(fullPrompt, agentId, requestedModel);
|
| 1228 |
-
const retryResult = await readDeepSeekResponse(retryResp.body);
|
| 1229 |
-
const retryContent = retryResult && retryResult.content ? sanitizeContent(retryResult.content) : '';
|
| 1230 |
-
const retryReasoning = retryResult && retryResult.reasoningContent ? sanitizeContent(retryResult.reasoningContent) : '';
|
| 1231 |
-
if (retryContent && retryContent.trim().length > 0) {
|
| 1232 |
-
console.log(`${agentTag} Retry ${retryAttempt} succeeded`);
|
| 1233 |
-
fullContent = retryContent;
|
| 1234 |
-
reasoningContent = retryReasoning;
|
| 1235 |
-
}
|
| 1236 |
-
}
|
| 1237 |
-
|
| 1238 |
-
// Auto-continuation: if finish_reason is 'length' or content is very long (>25000 chars),
|
| 1239 |
-
// send a continuation request to get the rest of the response
|
| 1240 |
-
let continuationRounds = 0;
|
| 1241 |
-
const MAX_CONTINUATION = 2;
|
| 1242 |
-
while ((finishReason === 'length' || fullContent.length > 25000) && continuationRounds < MAX_CONTINUATION) {
|
| 1243 |
-
continuationRounds++;
|
| 1244 |
-
console.log(`${agentTag} Response ${fullContent.length} chars (finish=${finishReason}). Auto-continuing (${continuationRounds}/${MAX_CONTINUATION})...`);
|
| 1245 |
-
await new Promise(r => setTimeout(r, 500));
|
| 1246 |
-
const { resp: contResp } = await askDeepSeekStream('continue', agentId, requestedModel);
|
| 1247 |
-
const contResult = await readDeepSeekResponse(contResp.body);
|
| 1248 |
-
const contContent = contResult && contResult.content ? sanitizeContent(contResult.content) : '';
|
| 1249 |
-
const contReasoning = contResult && contResult.reasoningContent ? sanitizeContent(contResult.reasoningContent) : '';
|
| 1250 |
-
if (contContent && contContent.trim().length > 0 && !contContent.includes('I am an AI')) {
|
| 1251 |
-
fullContent += '\n' + contContent;
|
| 1252 |
-
if (contReasoning) reasoningContent += (reasoningContent ? '\n' : '') + contReasoning;
|
| 1253 |
-
finishReason = contResult.finishReason;
|
| 1254 |
-
console.log(`${agentTag} Continuation added ${contContent.length} chars (total: ${fullContent.length})`);
|
| 1255 |
-
} else {
|
| 1256 |
-
console.log(`${agentTag} Continuation returned nothing useful, stopping`);
|
| 1257 |
-
break;
|
| 1258 |
-
}
|
| 1259 |
-
}
|
| 1260 |
-
|
| 1261 |
-
let toolCall = parseToolCall(fullContent);
|
| 1262 |
-
|
| 1263 |
-
// Retry if TOOL_CALL was found but JSON was truncated/invalid
|
| 1264 |
-
if (!toolCall && /TOOL_CALL:\s*\w/i.test(fullContent)) {
|
| 1265 |
-
console.log(`${agentTag} TOOL_CALL detected but JSON invalid/truncated (${fullContent.length} chars). Retrying with stricter prompt...`);
|
| 1266 |
-
session.id = null;
|
| 1267 |
-
session.parentMessageId = null;
|
| 1268 |
-
session.createdAt = null;
|
| 1269 |
-
session.messageCount = 0;
|
| 1270 |
-
await new Promise(r => setTimeout(r, 1000));
|
| 1271 |
-
const strictPrompt = fullPrompt + '\n\n[STRICT INSTRUCTION] Your previous response had a TOOL_CALL but the arguments were too long and got cut off. Keep the arguments SHORT — no large file contents. Just use a minimal example or reference the file by name. Output ONLY: TOOL_CALL: <function>\narguments: <short JSON>';
|
| 1272 |
-
const { resp: retryResp2 } = await askDeepSeekStream(strictPrompt, agentId, requestedModel);
|
| 1273 |
-
const retryResult2 = await readDeepSeekResponse(retryResp2.body);
|
| 1274 |
-
const retryContent2 = retryResult2 && retryResult2.content ? sanitizeContent(retryResult2.content) : '';
|
| 1275 |
-
if (retryContent2 && retryContent2.trim()) {
|
| 1276 |
-
const retryTc = parseToolCall(retryContent2);
|
| 1277 |
-
if (retryTc) {
|
| 1278 |
-
console.log(`${agentTag} Retry with strict prompt succeeded: ${retryTc.name}`);
|
| 1279 |
-
fullContent = retryContent2;
|
| 1280 |
-
reasoningContent = retryResult2.reasoningContent ? sanitizeContent(retryResult2.reasoningContent) : '';
|
| 1281 |
-
toolCall = retryTc;
|
| 1282 |
-
} else {
|
| 1283 |
-
console.log(`${agentTag} Retry still has broken JSON. Sending as text.`);
|
| 1284 |
-
reasoningContent = retryResult2.reasoningContent ? sanitizeContent(retryResult2.reasoningContent) : reasoningContent;
|
| 1285 |
-
}
|
| 1286 |
-
}
|
| 1287 |
-
}
|
| 1288 |
-
|
| 1289 |
-
// Check if any tool results in the current conversation contained a screenshot path.
|
| 1290 |
-
// If so, and the response doesn't already have MEDIA:, inject it so the gateway
|
| 1291 |
-
// delivers the file to Telegram.
|
| 1292 |
-
if (!fullContent.includes('MEDIA:')) {
|
| 1293 |
-
const screenshotPaths = extractScreenshotPaths(messages);
|
| 1294 |
-
if (screenshotPaths.length > 0) {
|
| 1295 |
-
fullContent += '\n\n' + screenshotPaths.join('\n');
|
| 1296 |
-
console.log(`${agentTag} Injected MEDIA paths into response: ${screenshotPaths.join(', ')}`);
|
| 1297 |
-
}
|
| 1298 |
-
}
|
| 1299 |
-
|
| 1300 |
-
storeHistory(agentId, prompt, fullContent, toolCall);
|
| 1301 |
-
|
| 1302 |
-
const openaiResponse = toolCall
|
| 1303 |
-
? buildToolCallResponse(toolCall, requestedModel, fullPrompt, reasoningContent)
|
| 1304 |
-
: buildTextResponse(fullContent, fullPrompt, requestedModel, reasoningContent);
|
| 1305 |
-
|
| 1306 |
-
if (stream) {
|
| 1307 |
-
if (apiMode === 'anthropic') {
|
| 1308 |
-
sendAnthropicStream(res, openaiResponse);
|
| 1309 |
-
} else if (apiMode === 'responses') {
|
| 1310 |
-
sendResponsesStream(res, openaiResponse);
|
| 1311 |
-
} else {
|
| 1312 |
-
sendOpenAIStream(res, openaiResponse);
|
| 1313 |
-
}
|
| 1314 |
-
console.log(`${agentTag} Streamed ${apiMode} (tool=${!!toolCall}) in ${elapsed}ms`);
|
| 1315 |
-
} else {
|
| 1316 |
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
| 1317 |
-
if (apiMode === 'anthropic') {
|
| 1318 |
-
res.end(JSON.stringify(toAnthropicResponse(openaiResponse)));
|
| 1319 |
-
} else if (apiMode === 'responses') {
|
| 1320 |
-
res.end(JSON.stringify(toResponsesResponse(openaiResponse)));
|
| 1321 |
-
} else {
|
| 1322 |
-
res.end(JSON.stringify(openaiResponse));
|
| 1323 |
-
}
|
| 1324 |
-
console.log(`${agentTag} Response ${apiMode} (tool=${!!toolCall}, ${elapsed}ms, ${fullContent.length} chars)`);
|
| 1325 |
-
}
|
| 1326 |
-
} catch (e) {
|
| 1327 |
-
console.log('[DS-API] Error:', e.message);
|
| 1328 |
-
res.writeHead(500, { 'Content-Type': 'application/json' });
|
| 1329 |
-
res.end(JSON.stringify({ error: { message: e.message, type: 'server_error' } }));
|
| 1330 |
-
}
|
| 1331 |
-
});
|
| 1332 |
-
});
|
| 1333 |
-
|
| 1334 |
-
async function runAuthScript() {
|
| 1335 |
-
const script = path.join(__dirname, 'scripts', 'deepseek_chrome_auth.js');
|
| 1336 |
-
const result = spawnSync(process.execPath, [script], { stdio: 'inherit', env: process.env });
|
| 1337 |
-
loadDeepSeekConfig({ fatal: false });
|
| 1338 |
-
return result.status === 0 && hasAuthConfig();
|
| 1339 |
-
}
|
| 1340 |
-
|
| 1341 |
-
function printStatus() {
|
| 1342 |
-
console.log(`\n${formatWatermark()}`);
|
| 1343 |
-
console.log(`Auth: ${hasAuthConfig() ? '✅ OK' : '❌ не найден deepseek-auth.json'}`);
|
| 1344 |
-
console.log(`Auth file: ${DS_CONFIG_PATH}`);
|
| 1345 |
-
console.log(`Рабочие модели: ${SUPPORTED_MODEL_IDS.join(', ')}`);
|
| 1346 |
-
console.log('Нерабочие/скрытые aliases: ' + Object.keys(MODEL_CONFIGS).filter(id => !MODEL_CONFIGS[id].supported).join(', '));
|
| 1347 |
-
console.log('Capabilities: GET /v1/model-capabilities');
|
| 1348 |
-
}
|
| 1349 |
-
|
| 1350 |
-
async function showStartupMenu() {
|
| 1351 |
-
if (isTruthy(process.env.SKIP_ACCOUNT_MENU) || isTruthy(process.env.NON_INTERACTIVE)) {
|
| 1352 |
-
if (!hasAuthConfig()) loadDeepSeekConfig({ fatal: true });
|
| 1353 |
-
return true;
|
| 1354 |
-
}
|
| 1355 |
-
while (true) {
|
| 1356 |
-
printStatus();
|
| 1357 |
-
console.log('\n=== Меню ===');
|
| 1358 |
-
console.log(`ForgetMeAI: ${FORGETMEAI_WATERMARK}`);
|
| 1359 |
-
console.log('1 - Авторизоваться / обновить DeepSeek login');
|
| 1360 |
-
console.log('2 - Показать модели и статусы');
|
| 1361 |
-
console.log('3 - Запустить прокси (по умолчанию)');
|
| 1362 |
-
console.log('4 - Выход');
|
| 1363 |
-
let choice = await prompt('Ваш выбор (Enter = 3): ');
|
| 1364 |
-
if (!choice) choice = '3';
|
| 1365 |
-
if (choice === '1') {
|
| 1366 |
-
await runAuthScript();
|
| 1367 |
-
} else if (choice === '2') {
|
| 1368 |
-
console.log(JSON.stringify(ALL_MODEL_CAPABILITIES, null, 2));
|
| 1369 |
-
await prompt('\nНажмите Enter, чтобы вернуться в меню...');
|
| 1370 |
-
} else if (choice === '3') {
|
| 1371 |
-
if (!hasAuthConfig()) {
|
| 1372 |
-
console.log('Нужен deepseek-auth.json. Запустите пункт 1.');
|
| 1373 |
-
continue;
|
| 1374 |
-
}
|
| 1375 |
-
return true;
|
| 1376 |
-
} else if (choice === '4') {
|
| 1377 |
-
return false;
|
| 1378 |
-
}
|
| 1379 |
-
}
|
| 1380 |
-
}
|
| 1381 |
-
|
| 1382 |
-
async function main() {
|
| 1383 |
-
printBanner();
|
| 1384 |
-
const shouldStart = await showStartupMenu();
|
| 1385 |
-
if (!shouldStart) process.exit(0);
|
| 1386 |
-
server.listen(PORT, HOST, () => {
|
| 1387 |
-
console.log(`[DS-API] Server on http://${HOST}:${PORT} (multi-agent sessions enabled)`);
|
| 1388 |
-
console.log(`[DS-API] ${formatWatermark()}`);
|
| 1389 |
-
console.log('[DS-API] POST /v1/chat/completions (OpenAI Chat Completions, stream=true|false)');
|
| 1390 |
-
console.log('[DS-API] POST /v1/messages — Anthropic Messages shim for Claude Code');
|
| 1391 |
-
console.log('[DS-API] POST /v1/responses — OpenAI Responses API shim');
|
| 1392 |
-
console.log('[DS-API] GET /v1/models — supported OpenAI-compatible models');
|
| 1393 |
-
console.log('[DS-API] GET /v1/model-capabilities — real model mapping and capabilities');
|
| 1394 |
-
console.log('[DS-API] GET /v1/sessions — list active agent sessions');
|
| 1395 |
-
console.log('[DS-API] POST /reset-session?agent=<id> — reset agent session');
|
| 1396 |
-
console.log('[DS-API] POST /reset-session?agent=all — reset ALL sessions');
|
| 1397 |
-
});
|
| 1398 |
-
}
|
| 1399 |
-
|
| 1400 |
-
main().catch(err => { console.error('[DS-API] FATAL:', err); process.exit(1); });
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@@ -80,9 +80,15 @@ namespace FlowAPI.Hubs
|
|
| 80 |
await BroadcastPresence(boardId);
|
| 81 |
}
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
public async Task SendSignal(string boardId, string receiverUserId, string type, string data)
|
| 84 |
{
|
| 85 |
-
if (
|
| 86 |
if (BoardPresences.TryGetValue(boardId, out var groupPresence))
|
| 87 |
{
|
| 88 |
var receiverConns = groupPresence.Values
|
|
@@ -97,43 +103,43 @@ namespace FlowAPI.Hubs
|
|
| 97 |
|
| 98 |
public async Task SendCursor(string boardId, double x, double y)
|
| 99 |
{
|
| 100 |
-
if (
|
| 101 |
await Clients.OthersInGroup(boardId).SendAsync("CursorMoved", Context.ConnectionId, CurrentUserId.ToString(), x, y);
|
| 102 |
}
|
| 103 |
|
| 104 |
public async Task MoveNode(string boardId, string nodeId, double x, double y)
|
| 105 |
{
|
| 106 |
-
if (
|
| 107 |
await Clients.OthersInGroup(boardId).SendAsync("NodeMoved", nodeId, x, y);
|
| 108 |
}
|
| 109 |
|
| 110 |
public async Task UpdateNodeData(string boardId, string nodeId, string newDataJson)
|
| 111 |
{
|
| 112 |
-
if (
|
| 113 |
await Clients.OthersInGroup(boardId).SendAsync("NodeDataUpdated", nodeId, newDataJson);
|
| 114 |
}
|
| 115 |
|
| 116 |
public async Task AddNode(string boardId, string nodeJson)
|
| 117 |
{
|
| 118 |
-
if (
|
| 119 |
await Clients.OthersInGroup(boardId).SendAsync("NodeAdded", nodeJson);
|
| 120 |
}
|
| 121 |
|
| 122 |
public async Task DeleteNode(string boardId, string nodeId)
|
| 123 |
{
|
| 124 |
-
if (
|
| 125 |
await Clients.OthersInGroup(boardId).SendAsync("NodeDeleted", nodeId);
|
| 126 |
}
|
| 127 |
|
| 128 |
public async Task AddEdge(string boardId, string edgeJson)
|
| 129 |
{
|
| 130 |
-
if (
|
| 131 |
await Clients.OthersInGroup(boardId).SendAsync("EdgeAdded", edgeJson);
|
| 132 |
}
|
| 133 |
|
| 134 |
public async Task DeleteEdge(string boardId, string edgeId)
|
| 135 |
{
|
| 136 |
-
if (
|
| 137 |
await Clients.OthersInGroup(boardId).SendAsync("EdgeDeleted", edgeId);
|
| 138 |
}
|
| 139 |
|
|
|
|
| 80 |
await BroadcastPresence(boardId);
|
| 81 |
}
|
| 82 |
|
| 83 |
+
// Only connections that passed the access check in JoinBoard may broadcast to a board
|
| 84 |
+
private bool HasJoined(string boardId) =>
|
| 85 |
+
!string.IsNullOrEmpty(boardId)
|
| 86 |
+
&& BoardPresences.TryGetValue(boardId, out var presences)
|
| 87 |
+
&& presences.ContainsKey(Context.ConnectionId);
|
| 88 |
+
|
| 89 |
public async Task SendSignal(string boardId, string receiverUserId, string type, string data)
|
| 90 |
{
|
| 91 |
+
if (!HasJoined(boardId)) return;
|
| 92 |
if (BoardPresences.TryGetValue(boardId, out var groupPresence))
|
| 93 |
{
|
| 94 |
var receiverConns = groupPresence.Values
|
|
|
|
| 103 |
|
| 104 |
public async Task SendCursor(string boardId, double x, double y)
|
| 105 |
{
|
| 106 |
+
if (!HasJoined(boardId)) return;
|
| 107 |
await Clients.OthersInGroup(boardId).SendAsync("CursorMoved", Context.ConnectionId, CurrentUserId.ToString(), x, y);
|
| 108 |
}
|
| 109 |
|
| 110 |
public async Task MoveNode(string boardId, string nodeId, double x, double y)
|
| 111 |
{
|
| 112 |
+
if (!HasJoined(boardId)) return;
|
| 113 |
await Clients.OthersInGroup(boardId).SendAsync("NodeMoved", nodeId, x, y);
|
| 114 |
}
|
| 115 |
|
| 116 |
public async Task UpdateNodeData(string boardId, string nodeId, string newDataJson)
|
| 117 |
{
|
| 118 |
+
if (!HasJoined(boardId)) return;
|
| 119 |
await Clients.OthersInGroup(boardId).SendAsync("NodeDataUpdated", nodeId, newDataJson);
|
| 120 |
}
|
| 121 |
|
| 122 |
public async Task AddNode(string boardId, string nodeJson)
|
| 123 |
{
|
| 124 |
+
if (!HasJoined(boardId)) return;
|
| 125 |
await Clients.OthersInGroup(boardId).SendAsync("NodeAdded", nodeJson);
|
| 126 |
}
|
| 127 |
|
| 128 |
public async Task DeleteNode(string boardId, string nodeId)
|
| 129 |
{
|
| 130 |
+
if (!HasJoined(boardId)) return;
|
| 131 |
await Clients.OthersInGroup(boardId).SendAsync("NodeDeleted", nodeId);
|
| 132 |
}
|
| 133 |
|
| 134 |
public async Task AddEdge(string boardId, string edgeJson)
|
| 135 |
{
|
| 136 |
+
if (!HasJoined(boardId)) return;
|
| 137 |
await Clients.OthersInGroup(boardId).SendAsync("EdgeAdded", edgeJson);
|
| 138 |
}
|
| 139 |
|
| 140 |
public async Task DeleteEdge(string boardId, string edgeId)
|
| 141 |
{
|
| 142 |
+
if (!HasJoined(boardId)) return;
|
| 143 |
await Clients.OthersInGroup(boardId).SendAsync("EdgeDeleted", edgeId);
|
| 144 |
}
|
| 145 |
|
|
@@ -38,12 +38,9 @@ namespace FlowAPI
|
|
| 38 |
builder.Services.AddScoped<IEdgeService, EdgeService>();
|
| 39 |
builder.Services.AddScoped<IHabitService, HabitService>();
|
| 40 |
builder.Services.AddScoped<ISyncService, SyncService>();
|
| 41 |
-
builder.Services.AddScoped<IAIService, AIService>();
|
| 42 |
builder.Services.AddScoped<IPaymentService, PaymentService>();
|
| 43 |
builder.Services.AddScoped<IAchievementService, AchievementService>();
|
| 44 |
-
|
| 45 |
-
// --- Singletons ---
|
| 46 |
-
builder.Services.AddSingleton<IGeminiBridgeManager, GeminiBridgeManager>();
|
| 47 |
|
| 48 |
// --- SignalR ---
|
| 49 |
builder.Services.AddSignalR(options =>
|
|
@@ -97,11 +94,17 @@ namespace FlowAPI
|
|
| 97 |
builder.Services.AddOpenApi();
|
| 98 |
|
| 99 |
// --- CORS ---
|
|
|
|
|
|
|
|
|
|
| 100 |
builder.Services.AddCors(options =>
|
| 101 |
{
|
| 102 |
-
options.AddPolicy("
|
| 103 |
{
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
| 105 |
.AllowAnyMethod()
|
| 106 |
.AllowAnyHeader()
|
| 107 |
.AllowCredentials();
|
|
@@ -110,68 +113,6 @@ namespace FlowAPI
|
|
| 110 |
|
| 111 |
var app = builder.Build();
|
| 112 |
|
| 113 |
-
// --- Start FreeDeepseekAPI proxy in background ---
|
| 114 |
-
try
|
| 115 |
-
{
|
| 116 |
-
var dsPath = System.IO.Path.Combine(System.AppContext.BaseDirectory, "FreeDeepseekAPI", "server.js");
|
| 117 |
-
if (System.IO.File.Exists(dsPath))
|
| 118 |
-
{
|
| 119 |
-
System.Console.WriteLine($"[Main] Starting FreeDeepseekAPI proxy: node {dsPath}...");
|
| 120 |
-
var processStartInfo = new System.Diagnostics.ProcessStartInfo
|
| 121 |
-
{
|
| 122 |
-
FileName = "node",
|
| 123 |
-
Arguments = dsPath,
|
| 124 |
-
UseShellExecute = false,
|
| 125 |
-
CreateNoWindow = true,
|
| 126 |
-
RedirectStandardOutput = true,
|
| 127 |
-
RedirectStandardError = true
|
| 128 |
-
};
|
| 129 |
-
processStartInfo.EnvironmentVariables["NON_INTERACTIVE"] = "1";
|
| 130 |
-
processStartInfo.EnvironmentVariables["PORT"] = "9655";
|
| 131 |
-
|
| 132 |
-
// Forward any relevant DeepSeek vars to the proxy process
|
| 133 |
-
foreach (var key in new[] { "DEEPSEEK_TOKEN", "DEEPSEEK_COOKIE", "DEEPSEEK_HIF_DLIQ", "DEEPSEEK_HIF_LEIM", "DEEPSEEK_WASM_URL" })
|
| 134 |
-
{
|
| 135 |
-
var val = System.Environment.GetEnvironmentVariable(key);
|
| 136 |
-
if (!string.IsNullOrEmpty(val))
|
| 137 |
-
{
|
| 138 |
-
processStartInfo.EnvironmentVariables[key] = val;
|
| 139 |
-
}
|
| 140 |
-
}
|
| 141 |
-
|
| 142 |
-
var dsProcess = System.Diagnostics.Process.Start(processStartInfo);
|
| 143 |
-
if (dsProcess != null)
|
| 144 |
-
{
|
| 145 |
-
// Read output in background to prevent hanging
|
| 146 |
-
System.Threading.Tasks.Task.Run(() => {
|
| 147 |
-
try {
|
| 148 |
-
while (!dsProcess.StandardOutput.EndOfStream) {
|
| 149 |
-
var line = dsProcess.StandardOutput.ReadLine();
|
| 150 |
-
System.Console.WriteLine($"[DeepSeekProxy-Out] {line}");
|
| 151 |
-
}
|
| 152 |
-
} catch {}
|
| 153 |
-
});
|
| 154 |
-
System.Threading.Tasks.Task.Run(() => {
|
| 155 |
-
try {
|
| 156 |
-
while (!dsProcess.StandardError.EndOfStream) {
|
| 157 |
-
var line = dsProcess.StandardError.ReadLine();
|
| 158 |
-
System.Console.WriteLine($"[DeepSeekProxy-Err] {line}");
|
| 159 |
-
}
|
| 160 |
-
} catch {}
|
| 161 |
-
});
|
| 162 |
-
System.Console.WriteLine("[Main] FreeDeepseekAPI proxy started successfully.");
|
| 163 |
-
}
|
| 164 |
-
}
|
| 165 |
-
else
|
| 166 |
-
{
|
| 167 |
-
System.Console.WriteLine($"[Main] FreeDeepseekAPI proxy file not found at: {dsPath}");
|
| 168 |
-
}
|
| 169 |
-
}
|
| 170 |
-
catch (System.Exception ex)
|
| 171 |
-
{
|
| 172 |
-
System.Console.WriteLine($"[Main] Failed to start FreeDeepseekAPI proxy: {ex.Message}");
|
| 173 |
-
}
|
| 174 |
-
|
| 175 |
// --- Auto-migrate database and seed ---
|
| 176 |
using (var scope = app.Services.CreateScope())
|
| 177 |
{
|
|
@@ -194,6 +135,32 @@ namespace FlowAPI
|
|
| 194 |
}
|
| 195 |
}
|
| 196 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
// Emergency Cleanup & Optimization before Migration
|
| 198 |
try
|
| 199 |
{
|
|
@@ -233,23 +200,6 @@ namespace FlowAPI
|
|
| 233 |
db.Database.SetCommandTimeout(120); // 2 minutes
|
| 234 |
db.Database.Migrate();
|
| 235 |
|
| 236 |
-
// Manual lock clearing — use actual DB path from config
|
| 237 |
-
try {
|
| 238 |
-
var connStrForLock = builder.Configuration.GetConnectionString("DefaultConnection") ?? "";
|
| 239 |
-
var lockMatch = System.Text.RegularExpressions.Regex.Match(connStrForLock, @"Data Source=(.+?)(?:;|$)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
| 240 |
-
string dbPath = lockMatch.Success ? lockMatch.Groups[1].Value.Trim() : "/app/taskflow.db";
|
| 241 |
-
if (File.Exists(dbPath)) {
|
| 242 |
-
foreach (var s in new[] { "-wal", "-shm", "-journal" }) {
|
| 243 |
-
if (File.Exists(dbPath + s)) {
|
| 244 |
-
File.Delete(dbPath + s);
|
| 245 |
-
Console.WriteLine($"[Startup] Cleared stale lock file: {dbPath + s}");
|
| 246 |
-
}
|
| 247 |
-
}
|
| 248 |
-
}
|
| 249 |
-
} catch (Exception ex) {
|
| 250 |
-
Console.WriteLine($"[Startup] Lock clearing failed: {ex.Message}");
|
| 251 |
-
}
|
| 252 |
-
|
| 253 |
// Auto-seed achievements
|
| 254 |
var achievementService = scope.ServiceProvider.GetRequiredService<IAchievementService>();
|
| 255 |
achievementService.SeedAchievementsAsync().Wait();
|
|
@@ -261,7 +211,7 @@ namespace FlowAPI
|
|
| 261 |
app.MapOpenApi();
|
| 262 |
}
|
| 263 |
|
| 264 |
-
app.UseCors("
|
| 265 |
// Note: UseHttpsRedirection is intentionally omitted.
|
| 266 |
// HF Space handles TLS termination at the proxy level; the app runs on plain HTTP internally.
|
| 267 |
|
|
|
|
| 38 |
builder.Services.AddScoped<IEdgeService, EdgeService>();
|
| 39 |
builder.Services.AddScoped<IHabitService, HabitService>();
|
| 40 |
builder.Services.AddScoped<ISyncService, SyncService>();
|
|
|
|
| 41 |
builder.Services.AddScoped<IPaymentService, PaymentService>();
|
| 42 |
builder.Services.AddScoped<IAchievementService, AchievementService>();
|
| 43 |
+
builder.Services.AddScoped<ITemplateService, TemplateService>();
|
|
|
|
|
|
|
| 44 |
|
| 45 |
// --- SignalR ---
|
| 46 |
builder.Services.AddSignalR(options =>
|
|
|
|
| 94 |
builder.Services.AddOpenApi();
|
| 95 |
|
| 96 |
// --- CORS ---
|
| 97 |
+
// Only the web client may call the API from a browser. Override with Cors__AllowedOrigins__0=... env vars.
|
| 98 |
+
var allowedOrigins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>()
|
| 99 |
+
?? new[] { "https://danildrotik-flowweb.hf.space", "http://localhost:5173", "http://127.0.0.1:5173" };
|
| 100 |
builder.Services.AddCors(options =>
|
| 101 |
{
|
| 102 |
+
options.AddPolicy("WebClient", policy =>
|
| 103 |
{
|
| 104 |
+
var isDevelopment = builder.Environment.IsDevelopment();
|
| 105 |
+
policy.SetIsOriginAllowed(origin =>
|
| 106 |
+
allowedOrigins.Contains(origin, StringComparer.OrdinalIgnoreCase) ||
|
| 107 |
+
(isDevelopment && Uri.TryCreate(origin, UriKind.Absolute, out var uri) && uri.IsLoopback))
|
| 108 |
.AllowAnyMethod()
|
| 109 |
.AllowAnyHeader()
|
| 110 |
.AllowCredentials();
|
|
|
|
| 113 |
|
| 114 |
var app = builder.Build();
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
// --- Auto-migrate database and seed ---
|
| 117 |
using (var scope = app.Services.CreateScope())
|
| 118 |
{
|
|
|
|
| 135 |
}
|
| 136 |
}
|
| 137 |
|
| 138 |
+
// Clear stale SQLite lock files left by a crashed container. This must run before the
|
| 139 |
+
// first connection is opened: deleting the journal of an open database corrupts it.
|
| 140 |
+
if (!string.IsNullOrEmpty(connStr))
|
| 141 |
+
{
|
| 142 |
+
var lockMatch = System.Text.RegularExpressions.Regex.Match(connStr, @"Data Source=(.+?)(?:;|$)", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
| 143 |
+
var dbPath = lockMatch.Success ? lockMatch.Groups[1].Value.Trim() : null;
|
| 144 |
+
if (dbPath != null && File.Exists(dbPath))
|
| 145 |
+
{
|
| 146 |
+
foreach (var suffix in new[] { "-wal", "-shm", "-journal" })
|
| 147 |
+
{
|
| 148 |
+
try
|
| 149 |
+
{
|
| 150 |
+
if (File.Exists(dbPath + suffix))
|
| 151 |
+
{
|
| 152 |
+
File.Delete(dbPath + suffix);
|
| 153 |
+
Console.WriteLine($"[Startup] Cleared stale lock file: {dbPath + suffix}");
|
| 154 |
+
}
|
| 155 |
+
}
|
| 156 |
+
catch (Exception ex)
|
| 157 |
+
{
|
| 158 |
+
Console.WriteLine($"[Startup] Lock clearing failed: {ex.Message}");
|
| 159 |
+
}
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
// Emergency Cleanup & Optimization before Migration
|
| 165 |
try
|
| 166 |
{
|
|
|
|
| 200 |
db.Database.SetCommandTimeout(120); // 2 minutes
|
| 201 |
db.Database.Migrate();
|
| 202 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
// Auto-seed achievements
|
| 204 |
var achievementService = scope.ServiceProvider.GetRequiredService<IAchievementService>();
|
| 205 |
achievementService.SeedAchievementsAsync().Wait();
|
|
|
|
| 211 |
app.MapOpenApi();
|
| 212 |
}
|
| 213 |
|
| 214 |
+
app.UseCors("WebClient");
|
| 215 |
// Note: UseHttpsRedirection is intentionally omitted.
|
| 216 |
// HF Space handles TLS termination at the proxy level; the app runs on plain HTTP internally.
|
| 217 |
|
|
@@ -19,13 +19,6 @@
|
|
| 19 |
"Google": {
|
| 20 |
"ClientId": "181646538378-kbabhecenasb8pca0uh95prhk8b0vrbr.apps.googleusercontent.com"
|
| 21 |
},
|
| 22 |
-
"OpenAI": {
|
| 23 |
-
"ApiKey": ""
|
| 24 |
-
},
|
| 25 |
-
"Gemini": {
|
| 26 |
-
"ApiKey": "AQ.Ab8RN6KQ0DG4-5LtLVuMUvpOtKcK9nKX6CqyOXue_BVUL0bIeA",
|
| 27 |
-
"Model": "gemini-2.5-flash"
|
| 28 |
-
},
|
| 29 |
"Stripe": {
|
| 30 |
"SecretKey": "",
|
| 31 |
"WebhookSecret": ""
|
|
|
|
| 19 |
"Google": {
|
| 20 |
"ClientId": "181646538378-kbabhecenasb8pca0uh95prhk8b0vrbr.apps.googleusercontent.com"
|
| 21 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
"Stripe": {
|
| 23 |
"SecretKey": "",
|
| 24 |
"WebhookSecret": ""
|
|
@@ -1,473 +0,0 @@
|
|
| 1 |
-
import sys
|
| 2 |
-
import json
|
| 3 |
-
import time
|
| 4 |
-
import os
|
| 5 |
-
import signal
|
| 6 |
-
import datetime
|
| 7 |
-
import re
|
| 8 |
-
import argparse
|
| 9 |
-
import threading
|
| 10 |
-
import base64
|
| 11 |
-
import io
|
| 12 |
-
import queue
|
| 13 |
-
import ctypes
|
| 14 |
-
|
| 15 |
-
# Win32 Constants
|
| 16 |
-
SW_HIDE = 0
|
| 17 |
-
SW_SHOW = 5
|
| 18 |
-
SW_MINIMIZE = 6
|
| 19 |
-
SW_RESTORE = 9
|
| 20 |
-
|
| 21 |
-
# Add the current directory to sys.path to ensure we can import modules if needed
|
| 22 |
-
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
| 23 |
-
|
| 24 |
-
from camoufox.sync_api import Camoufox
|
| 25 |
-
|
| 26 |
-
def log_message(message):
|
| 27 |
-
"""Log messages to stderr and bridge_log.txt."""
|
| 28 |
-
timestamp = datetime.datetime.now().strftime("[%Y-%m-%d %H:%M:%S]")
|
| 29 |
-
log_line = f"{timestamp} [BRIDGE] {message}\n"
|
| 30 |
-
sys.stderr.write(log_line)
|
| 31 |
-
sys.stderr.flush()
|
| 32 |
-
try:
|
| 33 |
-
with open("bridge_log.txt", "a", encoding="utf-8") as f:
|
| 34 |
-
f.write(log_line)
|
| 35 |
-
except:
|
| 36 |
-
pass
|
| 37 |
-
|
| 38 |
-
def signal_handler(sig, frame):
|
| 39 |
-
log_message("Received signal to exit.")
|
| 40 |
-
sys.exit(0)
|
| 41 |
-
|
| 42 |
-
signal.signal(signal.SIGINT, signal_handler)
|
| 43 |
-
signal.signal(signal.SIGTERM, signal_handler)
|
| 44 |
-
|
| 45 |
-
# --- Browser Logic (Adapted from gemini_agent.py) ---
|
| 46 |
-
|
| 47 |
-
def get_message_count(page) -> int:
|
| 48 |
-
return page.locator('div[id^="model-response-message-content"]').count()
|
| 49 |
-
|
| 50 |
-
def wait_for_new_response(page, previous_count: int, msg_id: str, timeout: int = 120):
|
| 51 |
-
log_message(f"Waiting for new response (prev count: {previous_count})...")
|
| 52 |
-
start = time.time()
|
| 53 |
-
|
| 54 |
-
new_msg_detected = False
|
| 55 |
-
new_count = previous_count
|
| 56 |
-
|
| 57 |
-
# 1. Wait for the new message container to appear
|
| 58 |
-
while time.time() - start < timeout:
|
| 59 |
-
try:
|
| 60 |
-
current_count = get_message_count(page)
|
| 61 |
-
if current_count > previous_count:
|
| 62 |
-
new_msg_detected = True
|
| 63 |
-
new_count = current_count
|
| 64 |
-
log_message(f"New message detected! Count: {previous_count} -> {current_count}")
|
| 65 |
-
break
|
| 66 |
-
except Exception:
|
| 67 |
-
pass
|
| 68 |
-
time.sleep(1)
|
| 69 |
-
|
| 70 |
-
if not new_msg_detected:
|
| 71 |
-
log_message(f"TIMEOUT: No new message after {timeout}s")
|
| 72 |
-
return False, new_count
|
| 73 |
-
|
| 74 |
-
log_message("Monitoring generation for streaming...")
|
| 75 |
-
|
| 76 |
-
stable_checks = 0
|
| 77 |
-
last_len = 0
|
| 78 |
-
last_text = ""
|
| 79 |
-
|
| 80 |
-
# 2. Monitor for changes (Streaming)
|
| 81 |
-
while time.time() - start < timeout:
|
| 82 |
-
try:
|
| 83 |
-
# Check for generating indicators (stop button, progress bar, or sparkle)
|
| 84 |
-
# If these are gone, generation is likely done.
|
| 85 |
-
generating_selectors = [
|
| 86 |
-
'.mat-mdc-progress-bar',
|
| 87 |
-
'mat-progress-bar',
|
| 88 |
-
'.loading-indicator',
|
| 89 |
-
'button[aria-label*="Stop"]',
|
| 90 |
-
'button[aria-label*="stop"]',
|
| 91 |
-
'button[aria-label*="Cancel"]',
|
| 92 |
-
'button[aria-label*="cancel"]',
|
| 93 |
-
'img[src*="sparkle_thinking"]',
|
| 94 |
-
'.sparkle-loading'
|
| 95 |
-
]
|
| 96 |
-
|
| 97 |
-
is_generating = False
|
| 98 |
-
for sel in generating_selectors:
|
| 99 |
-
try:
|
| 100 |
-
if page.locator(sel).first.is_visible():
|
| 101 |
-
is_generating = True
|
| 102 |
-
break
|
| 103 |
-
except:
|
| 104 |
-
pass
|
| 105 |
-
|
| 106 |
-
els = page.locator('div[id^="model-response-message-content"]').all()
|
| 107 |
-
if not els:
|
| 108 |
-
time.sleep(0.5)
|
| 109 |
-
continue
|
| 110 |
-
|
| 111 |
-
# Get current text of the *last* message
|
| 112 |
-
curr_text = els[-1].inner_text()
|
| 113 |
-
curr_len = len(curr_text)
|
| 114 |
-
|
| 115 |
-
# Emit partial if changed
|
| 116 |
-
if curr_len > last_len:
|
| 117 |
-
if curr_text.startswith(last_text):
|
| 118 |
-
diff = curr_text[len(last_text):]
|
| 119 |
-
if diff:
|
| 120 |
-
print(json.dumps({
|
| 121 |
-
"type": "partial_response",
|
| 122 |
-
"id": msg_id,
|
| 123 |
-
"content": diff
|
| 124 |
-
}), flush=True)
|
| 125 |
-
|
| 126 |
-
last_text = curr_text
|
| 127 |
-
last_len = curr_len
|
| 128 |
-
stable_checks = 0 # Reset stability if text changed
|
| 129 |
-
|
| 130 |
-
if not is_generating:
|
| 131 |
-
# Double check stability
|
| 132 |
-
if curr_len > 0 and curr_len == last_len:
|
| 133 |
-
stable_checks += 1
|
| 134 |
-
# Robust warm-up protection: if length is very small (< 150 chars), require
|
| 135 |
-
# 12 stable checks (6.0 seconds of no change) before cut-off to allow the AI to think and start streaming.
|
| 136 |
-
# Otherwise, require 3 stable checks (1.5 seconds of no change) to finish.
|
| 137 |
-
required_checks = 12 if curr_len < 150 else 3
|
| 138 |
-
if stable_checks >= required_checks:
|
| 139 |
-
log_message(f"Generation complete (indicator gone). Length: {curr_len}")
|
| 140 |
-
return True, new_count
|
| 141 |
-
else:
|
| 142 |
-
# Still generating, but maybe paused?
|
| 143 |
-
if curr_len > 0 and curr_len == last_len:
|
| 144 |
-
stable_checks += 1
|
| 145 |
-
if stable_checks >= 10: # 5 seconds of no change even if indicator present?
|
| 146 |
-
pass
|
| 147 |
-
else:
|
| 148 |
-
stable_checks = 0 # Text changing, so active
|
| 149 |
-
|
| 150 |
-
except Exception as e:
|
| 151 |
-
pass
|
| 152 |
-
|
| 153 |
-
time.sleep(0.5) # Poll every 500ms
|
| 154 |
-
|
| 155 |
-
return True, new_count
|
| 156 |
-
|
| 157 |
-
def get_specific_response(page, index: int) -> str:
|
| 158 |
-
try:
|
| 159 |
-
els = page.locator('div[id^="model-response-message-content"]').all()
|
| 160 |
-
if len(els) > index:
|
| 161 |
-
return els[index].inner_text().strip()
|
| 162 |
-
elif len(els) > 0:
|
| 163 |
-
return els[-1].inner_text().strip()
|
| 164 |
-
except:
|
| 165 |
-
pass
|
| 166 |
-
return ""
|
| 167 |
-
|
| 168 |
-
def send_gemini_message(page, message: str) -> bool:
|
| 169 |
-
try:
|
| 170 |
-
page.bring_to_front()
|
| 171 |
-
# Find input box
|
| 172 |
-
input_el = page.locator('div[contenteditable="true"]').first
|
| 173 |
-
if not input_el.is_visible():
|
| 174 |
-
input_el = page.locator('textarea').first
|
| 175 |
-
|
| 176 |
-
if input_el.is_visible(timeout=5000):
|
| 177 |
-
input_el.click()
|
| 178 |
-
time.sleep(0.5)
|
| 179 |
-
input_el.fill(message)
|
| 180 |
-
time.sleep(0.5)
|
| 181 |
-
|
| 182 |
-
# Find send button
|
| 183 |
-
send_btn = page.locator('button[aria-label*="Send"], mat-icon[data-mat-icon-name="send"]').first
|
| 184 |
-
if send_btn.is_visible():
|
| 185 |
-
send_btn.click()
|
| 186 |
-
else:
|
| 187 |
-
input_el.press("Enter")
|
| 188 |
-
|
| 189 |
-
return True
|
| 190 |
-
else:
|
| 191 |
-
log_message("Input element not found!")
|
| 192 |
-
except Exception as e:
|
| 193 |
-
log_message(f"Send failed: {e}")
|
| 194 |
-
return False
|
| 195 |
-
|
| 196 |
-
def send_gemini_image_message(page, message: str, image_path: str) -> (bool, str):
|
| 197 |
-
try:
|
| 198 |
-
page.bring_to_front()
|
| 199 |
-
|
| 200 |
-
# Check if "Upload files" is already visible (menu open from previous attempt?)
|
| 201 |
-
upload_btn = page.locator('button[data-test-id="local-images-files-uploader-button"]').first
|
| 202 |
-
if not upload_btn.is_visible():
|
| 203 |
-
upload_btn = page.locator('div.menu-text:has-text("Upload files")').first
|
| 204 |
-
|
| 205 |
-
if not upload_btn.is_visible():
|
| 206 |
-
log_message("Upload button not visible, looking for Plus button...")
|
| 207 |
-
plus_btn = page.locator('button[aria-label*="Upload files"], button[aria-label*="Add"], button:has(mat-icon[fonticon="add"]), button:has(mat-icon[data-mat-icon-name="add"]), button:has(mat-icon[fonticon="add_circle"]), button:has(mat-icon[fonticon="add_2"]), button:has(mat-icon[data-mat-icon-name="add_2"])').first
|
| 208 |
-
|
| 209 |
-
if plus_btn.is_visible():
|
| 210 |
-
log_message(f"Clicking Plus button: {plus_btn.get_attribute('aria-label')}")
|
| 211 |
-
plus_btn.click()
|
| 212 |
-
time.sleep(1.0) # Wait for menu animation
|
| 213 |
-
|
| 214 |
-
# Re-check upload button
|
| 215 |
-
upload_btn = page.locator('button[data-test-id="local-images-files-uploader-button"]').first
|
| 216 |
-
if not upload_btn.is_visible():
|
| 217 |
-
upload_btn = page.locator('div.menu-text:has-text("Upload files")').first
|
| 218 |
-
else:
|
| 219 |
-
log_message("Plus button not found with standard selectors.")
|
| 220 |
-
return False, "Plus/Add button not found"
|
| 221 |
-
|
| 222 |
-
if upload_btn.is_visible():
|
| 223 |
-
log_message("Clicking Upload files button...")
|
| 224 |
-
try:
|
| 225 |
-
with page.expect_file_chooser(timeout=5000) as fc_info:
|
| 226 |
-
upload_btn.click()
|
| 227 |
-
except Exception as e:
|
| 228 |
-
return False, f"Timeout waiting for file chooser: {e}"
|
| 229 |
-
|
| 230 |
-
file_chooser = fc_info.value
|
| 231 |
-
log_message(f"Uploading image: {image_path}")
|
| 232 |
-
file_chooser.set_files(image_path)
|
| 233 |
-
|
| 234 |
-
# Wait for upload to process.
|
| 235 |
-
time.sleep(4)
|
| 236 |
-
|
| 237 |
-
if send_gemini_message(page, message):
|
| 238 |
-
return True, ""
|
| 239 |
-
else:
|
| 240 |
-
return False, "Failed to send text message after upload"
|
| 241 |
-
else:
|
| 242 |
-
log_message("Upload files button not found in menu!")
|
| 243 |
-
return False, "Upload files button not found in menu"
|
| 244 |
-
|
| 245 |
-
except Exception as e:
|
| 246 |
-
log_message(f"Send image failed: {e}")
|
| 247 |
-
return False, f"Exception: {str(e)}"
|
| 248 |
-
|
| 249 |
-
def get_active_page(context, url="https://gemini.google.com/app"):
|
| 250 |
-
"""Finds an existing Gemini page or creates a new one and ensures it's navigated."""
|
| 251 |
-
page = None
|
| 252 |
-
for p in context.pages:
|
| 253 |
-
try:
|
| 254 |
-
if not p.is_closed():
|
| 255 |
-
page = p
|
| 256 |
-
break
|
| 257 |
-
except:
|
| 258 |
-
continue
|
| 259 |
-
|
| 260 |
-
if not page:
|
| 261 |
-
log_message("No active page found, creating new one...")
|
| 262 |
-
page = context.new_page()
|
| 263 |
-
page.add_init_script("Object.defineProperty(document, 'hidden', { get: () => false });")
|
| 264 |
-
|
| 265 |
-
try:
|
| 266 |
-
current_url = page.url
|
| 267 |
-
# If we are on Google login or account setup, DO NOT redirect/reload!
|
| 268 |
-
if "accounts.google" in current_url or "google.com/accounts" in current_url:
|
| 269 |
-
return page
|
| 270 |
-
|
| 271 |
-
if url not in current_url:
|
| 272 |
-
log_message(f"Navigating to {url} (current: {current_url})...")
|
| 273 |
-
page.goto(url, timeout=60000)
|
| 274 |
-
time.sleep(2)
|
| 275 |
-
except Exception as e:
|
| 276 |
-
log_message(f"Navigation check/error: {e}")
|
| 277 |
-
|
| 278 |
-
return page
|
| 279 |
-
|
| 280 |
-
def stdin_reader(q):
|
| 281 |
-
"""Reads stdin lines in a background thread and puts them in a queue."""
|
| 282 |
-
while True:
|
| 283 |
-
line = sys.stdin.readline()
|
| 284 |
-
if not line:
|
| 285 |
-
q.put(None)
|
| 286 |
-
break
|
| 287 |
-
q.put(line)
|
| 288 |
-
|
| 289 |
-
def set_browser_window_visibility(visible):
|
| 290 |
-
"""Находит окно браузера и скрывает/показывает его через Win32 API"""
|
| 291 |
-
if sys.platform != 'win32':
|
| 292 |
-
return
|
| 293 |
-
|
| 294 |
-
log_message(f"Starting window search (visibility={visible})...")
|
| 295 |
-
found_count = [0]
|
| 296 |
-
|
| 297 |
-
def foreach_window(hwnd, lParam):
|
| 298 |
-
class_name = ctypes.create_unicode_buffer(256)
|
| 299 |
-
ctypes.windll.user32.GetClassNameW(hwnd, class_name, 256)
|
| 300 |
-
|
| 301 |
-
length = ctypes.windll.user32.GetWindowTextLengthW(hwnd)
|
| 302 |
-
title = ""
|
| 303 |
-
if length > 0:
|
| 304 |
-
buff = ctypes.create_unicode_buffer(length + 1)
|
| 305 |
-
ctypes.windll.user32.GetWindowTextW(hwnd, buff, length + 1)
|
| 306 |
-
title = buff.value
|
| 307 |
-
|
| 308 |
-
is_browser = (class_name.value == "MozillaWindowClass")
|
| 309 |
-
|
| 310 |
-
if is_browser:
|
| 311 |
-
log_message(f"Checking window: '{title}' (Class: {class_name.value})")
|
| 312 |
-
is_match = any(term in title for term in ["Gemini", "Camoufox", "Firefox", "Nightly", "Google"])
|
| 313 |
-
if is_match or not title:
|
| 314 |
-
log_message(f"Found target browser window! Setting visibility: {visible}")
|
| 315 |
-
found_count[0] += 1
|
| 316 |
-
if visible:
|
| 317 |
-
log_message(f"Restoring window: '{title}'")
|
| 318 |
-
ctypes.windll.user32.ShowWindow(hwnd, SW_RESTORE)
|
| 319 |
-
ctypes.windll.user32.SetForegroundWindow(hwnd)
|
| 320 |
-
else:
|
| 321 |
-
log_message(f"Minimizing window: '{title}'")
|
| 322 |
-
ctypes.windll.user32.ShowWindow(hwnd, SW_MINIMIZE)
|
| 323 |
-
return True
|
| 324 |
-
|
| 325 |
-
enum_proc = ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_void_p, ctypes.c_void_p)(foreach_window)
|
| 326 |
-
ctypes.windll.user32.EnumWindows(enum_proc, 0)
|
| 327 |
-
log_message(f"Window search finished. Found {found_count[0]} windows.")
|
| 328 |
-
|
| 329 |
-
def main():
|
| 330 |
-
parser = argparse.ArgumentParser()
|
| 331 |
-
parser.add_argument("--headless", action="store_true", help="Run in headless mode")
|
| 332 |
-
args_parsed = parser.parse_args()
|
| 333 |
-
|
| 334 |
-
# Use the profile folder relative to this script's directory
|
| 335 |
-
profile_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gemini_profile_bridge")
|
| 336 |
-
|
| 337 |
-
headless_to_use = args_parsed.headless
|
| 338 |
-
log_message(f"Starting Gemini Bridge (Headless: {headless_to_use})...")
|
| 339 |
-
|
| 340 |
-
if not os.path.exists(profile_path):
|
| 341 |
-
os.makedirs(profile_path, exist_ok=True)
|
| 342 |
-
|
| 343 |
-
log_message(f"Initializing Camoufox with profile: {profile_path}")
|
| 344 |
-
|
| 345 |
-
try:
|
| 346 |
-
with Camoufox(
|
| 347 |
-
headless=headless_to_use,
|
| 348 |
-
persistent_context=True,
|
| 349 |
-
user_data_dir=profile_path,
|
| 350 |
-
viewport={'width': 1280, 'height': 1000},
|
| 351 |
-
humanize=False,
|
| 352 |
-
geoip=False,
|
| 353 |
-
args=["--no-sandbox", "--disable-setuid-sandbox"]
|
| 354 |
-
) as context:
|
| 355 |
-
|
| 356 |
-
page = get_active_page(context)
|
| 357 |
-
|
| 358 |
-
if "accounts.google.com" in page.url:
|
| 359 |
-
log_message("WARNING: Login required! Please log in manually in the browser window.")
|
| 360 |
-
|
| 361 |
-
log_message("Browser ready. Waiting for input on stdin...")
|
| 362 |
-
print(json.dumps({"type": "ready"}), flush=True)
|
| 363 |
-
|
| 364 |
-
input_queue = queue.Queue()
|
| 365 |
-
threading.Thread(target=stdin_reader, args=(input_queue,), daemon=True).start()
|
| 366 |
-
|
| 367 |
-
def delayed_hide():
|
| 368 |
-
time.sleep(3)
|
| 369 |
-
log_message("Attempting initial window hide...")
|
| 370 |
-
set_browser_window_visibility(False)
|
| 371 |
-
|
| 372 |
-
if not headless_to_use:
|
| 373 |
-
threading.Thread(target=delayed_hide, daemon=True).start()
|
| 374 |
-
|
| 375 |
-
# Screenshots disabled
|
| 376 |
-
|
| 377 |
-
while True:
|
| 378 |
-
try:
|
| 379 |
-
while not input_queue.empty():
|
| 380 |
-
line = input_queue.get_nowait()
|
| 381 |
-
if line is None: return
|
| 382 |
-
|
| 383 |
-
line = line.strip()
|
| 384 |
-
if not line: continue
|
| 385 |
-
|
| 386 |
-
log_message(f"Received JSON: {line[:50]}...")
|
| 387 |
-
try:
|
| 388 |
-
data = json.loads(line)
|
| 389 |
-
msg_type = data.get("type")
|
| 390 |
-
|
| 391 |
-
if msg_type == "prompt" or msg_type == "prompt_with_image":
|
| 392 |
-
prompt, msg_id = data.get("content"), data.get("id")
|
| 393 |
-
image_path = data.get("image_path")
|
| 394 |
-
is_new_chat = data.get("new_chat", False)
|
| 395 |
-
|
| 396 |
-
page = get_active_page(context)
|
| 397 |
-
|
| 398 |
-
if is_new_chat:
|
| 399 |
-
log_message("Request implies new chat. Searching for 'New Chat' button...")
|
| 400 |
-
try:
|
| 401 |
-
new_chat_btn = page.locator('side-nav-action-button[data-test-id="new-chat-button"]').first
|
| 402 |
-
if new_chat_btn.is_visible():
|
| 403 |
-
log_message("Clicking 'New Chat' button.")
|
| 404 |
-
new_chat_btn.click()
|
| 405 |
-
# Wait for old messages to disappear
|
| 406 |
-
log_message("Waiting for old messages to clear...")
|
| 407 |
-
start_wait = time.time()
|
| 408 |
-
while time.time() - start_wait < 10:
|
| 409 |
-
if get_message_count(page) == 0:
|
| 410 |
-
break
|
| 411 |
-
time.sleep(0.5)
|
| 412 |
-
time.sleep(1.0) # Additional settling time
|
| 413 |
-
else:
|
| 414 |
-
log_message("'New Chat' button not visible. Assuming already on a fresh chat.")
|
| 415 |
-
except Exception as e:
|
| 416 |
-
log_message(f"Warning: Failed to click new chat: {e}")
|
| 417 |
-
|
| 418 |
-
initial_count = get_message_count(page)
|
| 419 |
-
|
| 420 |
-
sent, error_msg = False, ""
|
| 421 |
-
if msg_type == "prompt_with_image" and image_path:
|
| 422 |
-
sent, error_msg = send_gemini_image_message(page, prompt, image_path)
|
| 423 |
-
else:
|
| 424 |
-
sent = send_gemini_message(page, prompt)
|
| 425 |
-
if not sent: error_msg = "Failed to send"
|
| 426 |
-
|
| 427 |
-
if sent:
|
| 428 |
-
success, new_count = wait_for_new_response(page, initial_count, msg_id, timeout=120)
|
| 429 |
-
if success:
|
| 430 |
-
resp = get_specific_response(page, new_count - 1)
|
| 431 |
-
print(json.dumps({"type": "response", "id": msg_id, "status": "success", "content": resp}), flush=True)
|
| 432 |
-
else:
|
| 433 |
-
print(json.dumps({"type": "response", "id": msg_id, "status": "timeout"}), flush=True)
|
| 434 |
-
else:
|
| 435 |
-
print(json.dumps({"type": "response", "id": msg_id, "status": "error", "error": error_msg}), flush=True)
|
| 436 |
-
|
| 437 |
-
elif msg_type == "click":
|
| 438 |
-
x, y = data.get("x"), data.get("y")
|
| 439 |
-
if x is not None and y is not None:
|
| 440 |
-
p = get_active_page(context)
|
| 441 |
-
if p:
|
| 442 |
-
p.bring_to_front()
|
| 443 |
-
p.mouse.move(x, y)
|
| 444 |
-
time.sleep(0.1)
|
| 445 |
-
p.mouse.click(x, y)
|
| 446 |
-
log_message(f"Hover & Click at {x}, {y}")
|
| 447 |
-
|
| 448 |
-
elif msg_type == "set_visibility":
|
| 449 |
-
visible = data.get("visible", True)
|
| 450 |
-
set_browser_window_visibility(visible)
|
| 451 |
-
log_message(f"Window visibility set to: {visible}")
|
| 452 |
-
|
| 453 |
-
elif msg_type == "ping":
|
| 454 |
-
print(json.dumps({"type": "pong"}), flush=True)
|
| 455 |
-
elif msg_type == "exit":
|
| 456 |
-
return
|
| 457 |
-
except Exception as inner_e:
|
| 458 |
-
log_message(f"Msg error: {inner_e}")
|
| 459 |
-
|
| 460 |
-
# Periodic screenshot disabled
|
| 461 |
-
|
| 462 |
-
time.sleep(0.1)
|
| 463 |
-
except Exception as e:
|
| 464 |
-
log_message(f"Loop error: {e}")
|
| 465 |
-
time.sleep(1)
|
| 466 |
-
|
| 467 |
-
except Exception as e:
|
| 468 |
-
log_message(f"Fatal Error: {e}")
|
| 469 |
-
print(json.dumps({"type": "fatal_error", "error": str(e)}), flush=True)
|
| 470 |
-
sys.exit(1)
|
| 471 |
-
|
| 472 |
-
if __name__ == "__main__":
|
| 473 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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