package net.frinst.demiryoluklavuzu.games import org.json.JSONObject import org.json.JSONArray import java.net.URL import javax.net.ssl.HttpsURLConnection import java.util.concurrent.Executors /** Uses HTTPS and the current Firebase ID token, never a service account key. */ object OyunHttp { private const val ENDPOINT = "https://oyun.frinst.net/index.php" private val executor = Executors.newSingleThreadExecutor() private fun decode(v:Any?):Any? = when(v){ null,JSONObject.NULL -> null is JSONObject -> v.keys().asSequence().associateWith { decode(v.get(it)) } is JSONArray -> (0 until v.length()).map { decode(v.get(it)) } else -> v } fun call(name:String,data:Map,callback:(Map<*,*>?,String?)->Unit){ val user=OyunVeri.auth.currentUser if(user==null){callback(null,"Önce giriş yap.");return} user.getIdToken(false).addOnCompleteListener { task -> val token=if(task.isSuccessful) task.result?.token else null if(token.isNullOrBlank()){callback(null,"Firebase oturumu doğrulanamadı.");return@addOnCompleteListener} executor.execute { var connection:HttpsURLConnection?=null var result:Map<*,*>?=null var error:String?=null try { val c=URL(ENDPOINT).openConnection() as HttpsURLConnection connection=c c.requestMethod="POST" c.instanceFollowRedirects=false c.connectTimeout=12000 c.readTimeout=45000 c.doOutput=true c.setRequestProperty("Content-Type","application/json; charset=utf-8") c.setRequestProperty("Accept","application/json") val payload=JSONObject().put("action",name).put("token",token).put("data",JSONObject(data)).toString().toByteArray(Charsets.UTF_8) c.setFixedLengthStreamingMode(payload.size) c.outputStream.use { it.write(payload) } val code=c.responseCode val stream=if(code in 200..299)c.inputStream else c.errorStream val body=stream?.bufferedReader(Charsets.UTF_8)?.use { reader -> val buffer=CharArray(4096) val out=StringBuilder() while(true){val n=reader.read(buffer);if(n<0)break;out.append(buffer,0,n);if(out.length>128000)throw IllegalStateException("response")} out.toString() }.orEmpty() val json=runCatching { JSONObject(body) }.getOrNull() if(code in 200..299){result=decode(json?.optJSONObject("result")) as? Map<*,*>;if(result==null)error="Sunucu yanıtı geçersiz."} else error=json?.optString("error")?.takeIf{it.isNotBlank()}?.take(300)?:"Sunucu hatası ($code)." }catch(e:Exception){error="Oyun sunucusuna bağlanılamadı. HTTPS ve interneti kontrol et."} finally{connection?.disconnect()} callback(result,error) } } } }