// download - the download interface // Copyright (C) 2024 Ian Cowburn // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using Npgsql; using System.Net; namespace download; public class ApiController : Controller { public IActionResult Get(string? key) { FileObject? file = GetDownload(key); if (file == null) { return StatusCode((int)HttpStatusCode.NotFound, String.Empty); } RecordDownload(key, Request?.HttpContext?.Connection?.RemoteIpAddress?.ToString() ?? "IP address unknown", Request?.Headers?.UserAgent.ToString() ?? "User agent unknown", DateTime.UtcNow); return File(file.Data, file.MimeType, file.FileName); } private FileObject? GetDownload(string key) { FileObject? ret = null; try { using var conn = new NpgsqlConnection(Config.Settings["ConnectionStrings:download"]); conn.Open(); using var cmd = new NpgsqlCommand("SELECT mime_type, file_name, data FROM file_object WHERE key = @key", conn); cmd.Parameters.AddWithValue("key", NpgsqlTypes.NpgsqlDbType.Varchar, key); using var reader = cmd.ExecuteReader(); if(reader.Read()) { ret = new FileObject(key, (string)reader["mime_type"], (string)reader["file_name"], (byte[])reader["data"]); } } catch(Exception e) { System.Diagnostics.Debug.WriteLine("GetDownload: Caught exception {0} - {1}", e.GetType().ToString(), e.Message); } return ret; } private void RecordDownload(string key, string ip_address, string user_agent, DateTime time) { try { using var conn = new NpgsqlConnection(Config.Settings["ConnectionStrings:download"]); conn.Open(); using var cmd = new NpgsqlCommand("INSERT INTO file_object (key, ip_address, user_agent, time) VALUES (@key, @ip_address, @user_agent, @time)", conn); if (user_agent.Length > 256) { user_agent = user_agent.Substring(0,256); } cmd.Parameters.AddWithValue("key", NpgsqlTypes.NpgsqlDbType.Varchar, key); cmd.Parameters.AddWithValue("ip_address", NpgsqlTypes.NpgsqlDbType.Varchar, ip_address); cmd.Parameters.AddWithValue("user_agent", NpgsqlTypes.NpgsqlDbType.Varchar, user_agent); cmd.Parameters.AddWithValue("time", NpgsqlTypes.NpgsqlDbType.Timestamp, time); cmd.ExecuteNonQuery(); } catch(Exception e) { System.Diagnostics.Debug.WriteLine("RecordDownload: Caught exception {0} - {1}", e.GetType().ToString(), e.Message); } } }