package com.protecgames.htmleditorpro;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class Neocities {
public static void upload(Context context, String apiKey, String filePath, String fileName) {
String boundary = "----WebKitFormBoundary" + System.currentTimeMillis();
String lineEnd = "\r\n";
String twoHyphens = "--";
String apiUrl = "https://neocities.org/api/upload";
new Thread(() -> {
try {
File file = new File(filePath);
if (!file.exists()) {
showToast(context, "File not found: " + filePath);
return;
}
HttpURLConnection connection = (HttpURLConnection) new URL(apiUrl).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Authorization", "Bearer " + apiKey);
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
FileInputStream fileInputStream = new FileInputStream(file)) {
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + fileName + "\"; filename=\"" + file.getName() + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: application/octet-stream" + lineEnd + lineEnd);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
outputStream.flush();
}
int responseCode = connection.getResponseCode();
InputStream responseStream = responseCode >= 400 ? connection.getErrorStream() : connection.getInputStream();
StringBuilder response = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(responseStream))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}
if (responseCode == 200) {
showToast(context, "Upload successful!");
} else {
showToast(context, "Upload failed: " + response);
}
} catch (IOException e) {
showToast(context, "Upload error: " + e.getMessage());
}
}).start();
}
private static void showToast(Context context, String message) {
new Handler(Looper.getMainLooper()).post(() ->
Toast.makeText(context, message, Toast.LENGTH_LONG).show()
);
}
}