package im.jfr.i import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Parcelable import android.widget.TextView import android.widget.Toast import org.json.JSONObject import java.net.HttpURLConnection import java.net.URL import kotlin.system.exitProcess class ShareActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_share) when (intent?.action) { Intent.ACTION_SEND -> { if (intent.type?.startsWith("image/") == true) { Thread { handleImage(intent) }.start() } else { assert(false) { "Uhoh! Unsupported MIME" } } } else -> { assert(false) { "Uhoh! Unsupported intent" } } } } private fun handleImage(intent: Intent) { val hyphens = "--".toByteArray() val boundary = "o3C5AoN2J8vyaYPh9Ewd4xvQwS5DjpJFSeRNF6sAPhS4QrbNL".toByteArray() val crlf = "\r\n".toByteArray() val url = URL("https://i.jfr.im/upload.php").openConnection() as HttpURLConnection url.doOutput = true url.requestMethod = "POST" url.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary.toString(Charsets.UTF_8)) val output = url.outputStream output.write(hyphens + boundary + crlf) (intent.getParcelableExtra(Intent.EXTRA_STREAM) as? Uri)?.let { output.write("Content-Disposition: form-data; name=\"files[]\";filename=\"$it\"\r\n".toByteArray()) output.write(("Content-Type: "+intent.type+"\r\n").toByteArray()) output.write(crlf) val input = contentResolver.openInputStream(it) input?.copyTo(output) /* val buffer = ByteArray(102400) var len = input.read(buffer) while (len != -1) { output.write(buffer, 0, len) len = input.read(buffer) } */ input?.close() output.write(crlf) output.write(hyphens + boundary + hyphens + crlf) } assert(url.responseCode == 200) { "Response was not 200, " + url.responseCode.toString() + " " + url.responseMessage } val tv = findViewById(R.id.resultView) val jsonStr = url.inputStream.readBytes().toString(Charsets.UTF_8) val jsonObj = JSONObject(jsonStr) assert(jsonObj.optBoolean("success", false)) { "Response JSON not success" } val uploadedLink = jsonObj.getJSONArray("files").getJSONObject(0).getString("url") (getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(ClipData.newPlainText(uploadedLink, uploadedLink)) tv.post { tv.text = uploadedLink if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.S_V2) Toast.makeText(applicationContext, "Copied", Toast.LENGTH_SHORT).show() runOnUiThread { exitProcess(0) } } } }