#include "screens/components/AttachmentUploader.hpp"
#include <algorithm>
#include "core/Log.hpp"
#include "screens/AppContext.hpp"
#include "screens/components/AccessibleLabel.hpp"
#include "screens/components/AlertPresenter.hpp"
#include "screens/components/AttachmentFileDialogs.hpp"
#include "screens/components/Box.hpp"
#include "spec/ComposeSpec.hpp"
#include "spec/ModelLimits.hpp"
#include "ui/Overlays.hpp"
#include "ui/Palette.hpp"
namespace dp {
using namespace ui;
using spec::ComposeSpec;
AttachmentUploader::AttachmentUploader(Options options)
: options_(std::move(options)), attachments_(options_.attachments), alive_(std::make_shared<bool>(true)) {
if (attachments_.size() > spec::ModelLimits::kMaxAttachmentsCount) attachments_.resize(spec::ModelLimits::kMaxAttachmentsCount);
}
AttachmentUploader::~AttachmentUploader() { *alive_ = false; }
bool AttachmentUploader::canAddMore() const { return attachments_.size() < spec::ModelLimits::kMaxAttachmentsCount; }
void AttachmentUploader::changed() {
if (options_.onAttachmentsChange) options_.onAttachmentsChange(attachments_);
}
std::string AttachmentUploader::iconFor(const UploadResponse& a) {
if (a.isImage) return "photo";
if (a.isVideo) return "film";
return "doc";
}
std::string AttachmentUploader::mimeTypeForFilename(const std::string& filename) {
static const std::pair<const char*, const char*> kTypes[] = {
{"png", "image/png"}, {"jpg", "image/jpeg"}, {"jpeg", "image/jpeg"}, {"gif", "image/gif"},
{"webp", "image/webp"}, {"bmp", "image/bmp"}, {"svg", "image/svg+xml"}, {"heic", "image/heic"},
{"mp4", "video/mp4"}, {"m4v", "video/x-m4v"}, {"mov", "video/quicktime"}, {"webm", "video/webm"},
{"mp3", "audio/mpeg"}, {"wav", "audio/wav"}, {"pdf", "application/pdf"}, {"txt", "text/plain"},
{"json", "application/json"}, {"zip", "application/zip"}};
const std::size_t dot = filename.find_last_of('.');
if (dot == std::string::npos) return ComposeSpec::kFallbackMime;
std::string ext = filename.substr(dot + 1);
for (char& c : ext) if (c >= 'A' && c <= 'Z') c = static_cast<char>(c + 32);
for (const auto& t : kTypes) if (ext == t.first) return t.second;
return ComposeSpec::kFallbackMime;
}
void AttachmentUploader::finishUpload(Result<UploadResponse> result) {
busy_ = false;
if (result.ok()) {
if (canAddMore()) attachments_.push_back(result.value());
changed();
} else {
AlertPresenter::showError(result.error());
}
}
void AttachmentUploader::uploadFromUrl(const std::string& url) {
if (!canAddMore() || busy_) return;
std::size_t a = 0, b = url.size();
while (a < b && std::isspace(static_cast<unsigned char>(url[a]))) ++a;
while (b > a && std::isspace(static_cast<unsigned char>(url[b - 1]))) --b;
const std::string trimmed = url.substr(a, b - a);
if (trimmed.empty()) return;
busy_ = true;
auto alive = alive_;
AppContext::api().uploadFromUrl(trimmed, std::nullopt, [this, alive](Result<UploadResponse> r) {
if (*alive) finishUpload(std::move(r));
});
}
void AttachmentUploader::uploadFile(const std::string& data, const std::string& filename, const std::string& mimeType) {
if (!canAddMore() || busy_) return;
busy_ = true;
auto alive = alive_;
AppContext::api().uploadFile(data, filename, mimeType, [this, alive](Result<UploadResponse> r) {
if (*alive) finishUpload(std::move(r));
});
}
void AttachmentUploader::uploadPath(const std::string& path) {
if (!canAddMore() || busy_) return;
const auto data = AttachmentFileDialogs::readFile(path, ComposeSpec::kMaxUploadFileBytes);
if (!data) {
AlertPresenter::showError(std::string(ComposeSpec::kFileRejected));
return;
}
const std::string name = AttachmentFileDialogs::lastPathComponent(path);
uploadFile(*data, name, mimeTypeForFilename(name));
}
void AttachmentUploader::remove(const UploadResponse& attachment) {
if (busy_) return;
busy_ = true;
auto alive = alive_;
const std::string uid = attachment.id;
AppContext::api().deleteAttachment(uid, [this, alive, uid](Result<Unit> r) {
if (!*alive) return;
busy_ = false;
if (r.ok()) {
attachments_.erase(std::remove_if(attachments_.begin(), attachments_.end(), [&](const UploadResponse& a) { return a.id == uid; }),
attachments_.end());
changed();
} else {
AlertPresenter::showError(r.error());
}
});
}
void AttachmentUploader::deleteUnsubmittedAttachments() {
const std::vector<UploadResponse> pending = attachments_;
attachments_.clear();
for (const UploadResponse& a : pending) {
const std::string uid = a.id;
AppContext::api().deleteAttachment(uid, [uid](Result<Unit> r) {
if (!r.ok()) Log::warn("Failed to delete unsubmitted attachment " + uid + ": " + r.error().message);
});
}
if (!pending.empty()) changed();
}
void AttachmentUploader::forget() {
if (attachments_.empty()) return;
attachments_.clear();
changed();
}
void AttachmentUploader::pickFile(bool mediaOnly) {
auto alive = alive_;
AttachmentFileDialogs::openFile(mediaOnly, [this, alive](const std::string& path) {
if (*alive && !path.empty()) uploadPath(path);
});
}
void AttachmentUploader::showUrlPrompt() {
AlertSpec a;
a.title = ComposeSpec::kAddFromUrlTitle;
a.message = ComposeSpec::kAddFromUrlMessage;
AlertField field;
field.placeholder = ComposeSpec::kUrlPlaceholder;
a.fields.push_back(field);
auto text = a.fields[0].text;
auto alive = alive_;
a.buttons.push_back({ComposeSpec::kCancel, AlertButton::Role::Cancel, [text] { text->clear(); }});
a.buttons.push_back({ComposeSpec::kAdd, AlertButton::Role::Normal, [this, alive, text] {
const std::string url = *text;
text->clear();
if (*alive) uploadFromUrl(url);
}});
Overlays::instance().alert(std::move(a));
}
void AttachmentUploader::showAddChoice() {
auto alive = alive_;
std::vector<AlertButton> buttons;
buttons.push_back({ComposeSpec::kPhotoLibrary, AlertButton::Role::Normal, [this, alive] { if (*alive) pickFile(true); }});
buttons.push_back({ComposeSpec::kFiles, AlertButton::Role::Normal, [this, alive] { if (*alive) pickFile(false); }});
buttons.push_back({ComposeSpec::kFromUrl, AlertButton::Role::Normal, [this, alive] { if (*alive) showUrlPrompt(); }});
buttons.push_back({ComposeSpec::kCancel, AlertButton::Role::Cancel, nullptr});
Overlays::instance().confirmationDialog(ComposeSpec::kAddAttachment, "", std::move(buttons));
}
ViewPtr AttachmentUploader::addButton() {
ViewPtr label;
if (options_.isSmall) {
label = Icon("paperclip", ComposeSpec::kUploaderSmallIcon)->foreground(Palette::fg2());
} else {
label = HStack({Icon("paperclip", 15), Text(ComposeSpec::kAddAttachment)}, 6);
}
return Button(label, [this] { showAddChoice(); }, ButtonStyles::automatic())->disabled(busy_)->id("add-attachment");
}
ViewPtr AttachmentUploader::row(const UploadResponse& a) {
const UploadResponse copy = a;
ViewPtr trash = WithAccessibleLabel(Button(Icon("trash", 16)->foreground(Palette::red()), [this, copy] { remove(copy); }, ButtonStyles::plain())
->disabled(busy_)->id("delete-" + a.id), ComposeSpec::kLabelDelete);
return HStack({Icon(iconFor(a), 16)->foreground(Palette::fg2()),
Text(a.filename.value_or(ComposeSpec::kFallbackFilename))->lineLimit(1)->maxWidth(Alignment::leading()),
trash},
ComposeSpec::kUploaderRowSpacing);
}
ViewPtr AttachmentUploader::view() {
if (options_.isSmall && attachments_.empty()) {
return busy_ ? ProgressSpinner(18) : addButton();
}
std::vector<ViewPtr> col;
for (const UploadResponse& a : attachments_) col.push_back(row(a));
if (busy_) col.push_back(ProgressSpinner(20)->maxWidth());
if (canAddMore()) col.push_back(addButton());
return BoxView(VStack(col, ComposeSpec::kUploaderRowSpacing, HAlign::Leading)->maxWidth(Alignment::leading()));
}
} // namespace dp