Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.nepravprofilechooser
- import android.app.Activity
- import android.content.Context
- import android.content.ContextWrapper
- import android.content.Intent
- import android.graphics.Bitmap
- import android.graphics.BitmapFactory
- import android.net.Uri
- import android.os.Environment
- import android.os.Looper
- import android.os.Parcel
- import android.os.Parcelable
- import android.util.Log
- import android.widget.ProgressBar
- import android.widget.Toast
- import com.google.gson.Gson
- import com.google.gson.reflect.TypeToken
- import kotlinx.android.synthetic.main.activity_picture.*
- import okhttp3.*
- import okhttp3.MediaType.Companion.toMediaTypeOrNull
- import okhttp3.RequestBody.Companion.toRequestBody
- import okhttp3.logging.HttpLoggingInterceptor
- import okio.ByteString
- import java.io.*
- class ServerConnection():Parcelable {
- private var APP_TOKEN:String? = ""
- private var APP_USER_ID:Int = 0
- private var SOCIAL_TOKEN:String? = ""
- private var SOCIAL_ID:Int = 0
- private var EMAIL:String? = ""
- private var EXPIRY_TIME:Int = 0
- private var AUTH_TYPE:String? = ""
- private val MAIN_URL = "http://neprav.fun:8080/api/v0/"
- private val NORMAL_CLOSURE_STATUS = 1000
- private var webSocket:WebSocket? = null
- private var logging = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
- override fun log(message: String) {
- Log.d("LOGGER", message)
- }
- }).setLevel(HttpLoggingInterceptor.Level.HEADERS)
- val gson = Gson()
- private val client = OkHttpClient.Builder()
- .addInterceptor(logging)
- .retryOnConnectionFailure(retryOnConnectionFailure = true)
- .build()
- constructor(parcel: Parcel) : this() {
- APP_TOKEN = parcel.readString()
- APP_USER_ID = parcel.readInt()
- SOCIAL_TOKEN = parcel.readString()
- SOCIAL_ID = parcel.readInt()
- EMAIL = parcel.readString()
- EXPIRY_TIME = parcel.readInt()
- AUTH_TYPE = parcel.readString()
- }
- private fun loadAppTokenFromMemory(activity: Activity) {
- // Подгрузка апптокена и юзер айди из памяти
- val sharedPreferences = activity.getPreferences(Context.MODE_PRIVATE)
- APP_TOKEN = sharedPreferences.getString("app_token", APP_TOKEN)
- APP_USER_ID = sharedPreferences.getInt("app_user_id", APP_USER_ID)
- Log.d("LoadingTag", "App token: $APP_TOKEN and App_user id: $APP_USER_ID")
- }
- private fun loadSocialFromMemory(activity:Activity) {
- // Подгрузка инфы о социальной сети из памяти
- val sharedPreferences = activity.getPreferences(Context.MODE_PRIVATE)
- SOCIAL_ID = sharedPreferences.getInt("social_id", SOCIAL_ID)
- SOCIAL_TOKEN = sharedPreferences.getString("social_token", SOCIAL_TOKEN)
- EMAIL = sharedPreferences.getString("email", EMAIL)
- EXPIRY_TIME = sharedPreferences.getInt("expiry_time", EXPIRY_TIME)
- AUTH_TYPE = sharedPreferences.getString("auth_type", AUTH_TYPE)
- Log.d("LoadingTag", "SOCIAL_ID: $SOCIAL_ID \n SOCIAL_TOKEN: $SOCIAL_TOKEN \n EMAIN: $EMAIL")
- }
- private fun saveLoginData(activity: Activity, appToken: String, appUserId: Int) {
- val pref = activity.getPreferences(Context.MODE_PRIVATE)
- with(pref.edit()) {
- putString("app_token", appToken)
- putInt("app_user_id", appUserId)
- commit()
- }
- }
- // https://stackoverflow.com/questions/649154/save-bitmap-to-location
- private fun saveBitmap(bitmap: Bitmap, activity: Activity) {
- val cw = ContextWrapper(activity.application)
- val directory: File = cw.getDir("profile", Context.MODE_PRIVATE)
- if (!directory.exists()) {
- directory.mkdir()
- }
- val mypath = File(directory, "profilePicture.png")
- Log.d("SavePicture", mypath.absolutePath)
- var fos: FileOutputStream? = null
- try {
- fos = FileOutputStream(mypath)
- bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
- fos!!.close()
- } catch (e: Exception) {
- Log.d("SavePicture", e.message, e)
- }
- }
- fun loadBitmap(activity: Activity):Bitmap? {
- var bitmap:Bitmap? = null
- val cw = ContextWrapper(activity.application)
- val directory: File = cw.getDir("profile", Context.MODE_PRIVATE)
- val mypath = File(directory, "profilePicture.png")
- if (!mypath.exists()) {
- // пикча отсутствует
- return null
- }
- var fil: FileInputStream? = null
- try {
- fil = FileInputStream(mypath)
- bitmap = BitmapFactory.decodeFile(mypath.absolutePath)
- fil.close()
- } catch (e:java.lang.Exception) {
- Log.e("LoadPicture", e.message, e)
- return null
- }
- return bitmap
- }
- fun socialNetworkAuthorize(activity:LoginActivity, authType:String, authToken:String, email:String, socialUserId:Int, expiresIn: Int) {
- // Наполнение запроса информацией
- val mapItems: MutableMap<String, Any> = HashMap()
- mapItems["auth_type"] = authType
- mapItems["auth_token"] = authToken
- mapItems["email"] = email
- mapItems["social_user_id"] = socialUserId
- mapItems["expires_in"] = expiresIn
- val json = gson.toJson(mapItems)
- val url = MAIN_URL + "signup"
- Log.d("serverConnection", "the auth json is: " + json)
- val formBody = json.toString().toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
- val request = Request.Builder()
- .url(url)
- .post(formBody)
- .build()
- client.newCall(request).enqueue(object: Callback {
- override fun onFailure(call: Call, e: IOException) {
- // val pref = activity.getPreferences(Context.MODE_PRIVATE)
- // with (pref.edit()) {
- // putString("app_token", "kek")
- // putString("user_id", "kek")
- // commit()
- // }
- val errors = StringWriter()
- e.printStackTrace(PrintWriter(errors))
- Log.d("serverConnection", errors.toString())
- }
- override fun onResponse(call: Call, response: Response) {
- Log.d("serverConnection", "Response code is: " + response.code)
- // Если код 200 и все класс на авторизации через соцсеть
- if (response.code == 200) {
- val body = response.body!!.string()
- response.body!!.close()
- Log.d("testConnection", "response body is $body")
- val data = gson.fromJson(body, Map::class.java)
- Log.d("testConnection", data.toString())
- APP_TOKEN = data["app_token"] as String
- APP_USER_ID = (data["app_user_id"] as Double).toInt()
- Log.d("testConnection", APP_TOKEN + " " + APP_USER_ID)
- saveLoginData(activity, APP_TOKEN!!, APP_USER_ID)
- // отправить на проверку авы
- getProfilePicture(activity)
- //
- } else if (response.code == 409) {
- Log.d("serverConnection", "SOCIAL NETWORK TOKEN IS INVALID")
- }
- }
- })
- }
- // МЕТОД LOGIN, вызывается при старте, если есть юзер айди и токен
- fun login(activity:LoginActivity) {
- loadAppTokenFromMemory(activity)
- // выход, если нет юзер айди
- if (APP_USER_ID == 0) return
- val mapItems: MutableMap<String, Any?> = HashMap()
- mapItems["app_token"] = APP_TOKEN
- mapItems["app_user_id"] = APP_USER_ID
- val json = gson.toJson(mapItems)
- val url = MAIN_URL + "login"
- Log.d("serverConnection", "Login sending: " + json)
- val formBody = json.toString().toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
- val request = Request.Builder()
- .url(url)
- .post(formBody)
- .build()
- client.newCall(request).enqueue(object: Callback {
- override fun onFailure(call: Call, e: IOException) {
- val errors = StringWriter()
- e.printStackTrace(PrintWriter(errors))
- Log.d("serverConnection", errors.toString())
- }
- override fun onResponse(call: Call, response: Response) {
- Log.d("serverConnection", "Response code is: " + response.code)
- // если все данные верны - пропускаем
- if (response.code == 200) {
- getProfilePicture(activity)
- // ЕСЛИ С АПП ТОКЕНОМ ВООБЩЕ ЧТО ЛИБО НЕ ТАК
- } else if (response.code == 401) {
- Log.d("serverConnection", "App token is invalid, trying with saved social info...")
- activity.run {
- runOnUiThread {
- Toast.makeText(
- applicationContext,
- "Response code is " + response.code + "\n App token is invalid, trying with saved social info...",
- Toast.LENGTH_SHORT
- ).show()
- }
- }
- // Достаем креды сети из памяти
- loadSocialFromMemory(activity)
- // Авторизуемся с локальными кредами социалки:
- socialNetworkAuthorize(activity, AUTH_TYPE!!, SOCIAL_TOKEN!!, EMAIL!!, SOCIAL_ID, EXPIRY_TIME)
- }
- }
- })
- }
- // Получить аватарку пользователя
- fun getProfilePicture(activity: LoginActivity) {
- val url = Uri.parse(MAIN_URL + "get_profile_picture")
- .buildUpon()
- .appendQueryParameter("app_token", APP_TOKEN)
- .appendQueryParameter("app_user_id", APP_USER_ID.toString())
- .build().toString()
- Log.d("serverConnection", url)
- val request = Request.Builder()
- .url(url)
- .build()
- client.newCall(request).enqueue(object: Callback {
- override fun onFailure(call: Call, e: IOException) {
- Log.d("serverConnection", e.message)
- }
- override fun onResponse(call: Call, response: Response) {
- if (response.code == 200) {
- // Если ава на сервере есть - пытаемся достать из памяти
- var profilePicture = loadBitmap(activity)
- if (profilePicture != null) {
- activity.run {
- runOnUiThread {
- val intent = Intent(
- activity.applicationContext,
- CarouselActivity::class.java
- )
- intent.putExtra("server_connection", this.serverConnection)
- intent.putExtra("profile_picture", ProfilePicture.encodeBitmap(profilePicture as Bitmap))
- startActivity(intent)
- }
- }
- return
- }
- val body = response.body!!.string()
- response.body!!.close()
- Log.d("serverConnection", "getProfilePicture: $body")
- var tempMap: Map<String, Any> = gson.fromJson(body, object : TypeToken<Map<String, Any>>() {}.type)
- val pictures = gson.fromJson(tempMap.getValue("data").toString(), Array<ProfilePicture>::class.java)
- Log.d("serverConnection", pictures.joinToString())
- var humanPicture: ProfilePicture = pictures[1]
- var animalPicture: ProfilePicture = pictures[0]
- Log.d("SavePicture", humanPicture.type + animalPicture.type)
- for (picture in pictures) {
- downloadImage(picture, activity)
- if (picture.type.equals("people")) humanPicture = picture
- else animalPicture = picture
- Log.d("SavePicture",picture.name + " " + picture.type + " " + picture.nose + " " + picture.id)
- }
- Log.d("SavePicture", "saving...")
- profilePicture = ProfilePicture.moveImage(humanPicture, animalPicture)
- saveBitmap(profilePicture, activity)
- if (activity is LoginActivity) {
- activity.run {
- runOnUiThread {
- val intent = Intent(
- activity.applicationContext,
- CarouselActivity::class.java
- )
- intent.putExtra("server_connection", this.serverConnection)
- intent.putExtra("profile_picture", ProfilePicture.encodeBitmap(profilePicture))
- startActivity(intent)
- }
- }
- }
- } else if (response.code == 409) {
- activity.run {
- runOnUiThread {
- val intent = Intent(activity.applicationContext, PictureActivity::class.java)
- intent.putExtra("server_connection", this.serverConnection)
- startActivity(intent)
- }
- }
- }
- }
- })
- }
- internal fun downloadImage(picture : ProfilePicture, activity: Activity){
- Log.d("looper_tag", (Looper.myLooper() == Looper.getMainLooper()).toString())
- // Creating the URL
- val url = Uri.parse(MAIN_URL + "get_image")
- .buildUpon()
- .appendQueryParameter("app_token", APP_TOKEN)
- .appendQueryParameter("app_user_id", APP_USER_ID.toString())
- .appendQueryParameter("image_id", picture.id.toString())
- .build().toString()
- Log.d("serverConnection", url)
- val request = Request.Builder()
- .url(url)
- .build()
- val response = client.newCall(request).execute()
- if (response.code == 200) {
- Log.d("serverConnection", response.message)
- val responseBody = response.body!!
- val bitmap = BitmapFactory.decodeStream(responseBody.byteStream())
- response.body!!.close()
- Log.d("serverConnection", bitmap.toString())
- picture.bitmap = bitmap
- // если вызвано из PictureActivity, то функция выставляет все фото4ки в списки
- if (activity is PictureActivity) {
- activity.run {
- runOnUiThread {
- Log.d("looper_tag", "inRunOnUI"+(Looper.myLooper() == Looper.getMainLooper()).toString())
- if (picture.type == "animals") {
- animals.add(picture)
- } else {
- humans.add(picture)
- }
- Log.d("MainPictures", "" + animals.size + " " + humans.size)
- if (imageView.drawable == null && humans.size != 0 && animals.size != 0) {
- imageView.setImageBitmap(
- ProfilePicture.moveImage(
- humans[0],
- animals[0]
- )
- )
- progressBar.visibility = ProgressBar.GONE
- }
- }
- }
- }
- } else {
- Log.d("serverConnection", response.code.toString())
- val responseBody = response.body!!
- Log.d("serverConnection", responseBody.string())
- }
- }
- fun downloadImagesInfo(activity: Activity){
- val url = Uri.parse(MAIN_URL + "get_images")
- .buildUpon()
- .appendQueryParameter("app_token", APP_TOKEN)
- .appendQueryParameter("app_user_id", APP_USER_ID.toString())
- .build().toString()
- val request = Request.Builder()
- .url(url)
- .build()
- client.newCall(request).enqueue(object : Callback {
- override fun onFailure(call: Call, e: IOException) {
- // val errors = StringWriter()
- // e.printStackTrace(PrintWriter(errors))
- // Log.d("Pictures_info", errors.toString())
- activity.run {
- runOnUiThread {
- Toast.makeText(
- this.applicationContext,
- "Failed to download image info",
- Toast.LENGTH_LONG
- ).show()
- floatingActionButton.show()
- }
- }
- }
- override fun onResponse(call: Call, response: Response) {
- if (response.code == 200) {
- val body = response.body!!.string()
- var tempMap: Map<String, Any> = gson.fromJson(body, object : TypeToken<Map<String, Any>>() {}.type)
- val pictures = gson.fromJson(tempMap.getValue("data").toString(), Array<ProfilePicture>::class.java)
- response.body!!.close()
- pictures.joinToString()
- if (activity is PictureActivity) {
- for (picture in pictures) {
- downloadImage(picture, activity)
- Log.d(
- "serverConnection",
- picture.name + " " + picture.type + " " + picture.nose + " " + picture.id
- )
- }
- }
- } else {
- // Log.d("Pictures_info", "${response.code}")
- activity.run{
- runOnUiThread{
- floatingActionButton.show()
- }
- }
- }
- }
- })
- }
- fun sendAvatar(activity: PictureActivity, human_picture:ProfilePicture, animal_picture:ProfilePicture) {
- val url = MAIN_URL + "set_avatar"
- val mapItems: MutableMap<String, Any> = HashMap()
- mapItems["app_token"] = APP_TOKEN!!
- mapItems["app_user_id"] = APP_USER_ID
- mapItems["human_id"] = human_picture.id
- mapItems["animal_id"] = animal_picture.id
- val json = gson.toJson(mapItems)
- Log.d("serverConnection", "the send_avatar json is: " + json)
- val formBody = json.toString().toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
- val request = Request.Builder()
- .url(url)
- .post(formBody)
- .build()
- client.newCall(request).enqueue(object: Callback {
- override fun onFailure(call: Call, e: IOException) {
- val errors = StringWriter()
- e.printStackTrace(PrintWriter(errors))
- Log.d("serverConnection", errors.toString())
- }
- override fun onResponse(call: Call, response: Response) {
- Log.d("serverConnection", "Response code is: " + response.code)
- if (response.code == 200) {
- activity.run {
- runOnUiThread {
- val intent = Intent(activity.applicationContext, CarouselActivity::class.java)
- intent.putExtra("server_connection", this@ServerConnection)
- val tempbitmap = ProfilePicture.moveImage(human_picture, animal_picture)
- this@ServerConnection.saveBitmap(tempbitmap, activity)
- intent.putExtra("profile_picture", ProfilePicture.encodeBitmap(tempbitmap))
- finish()
- startActivity(intent)
- }
- }
- }
- }
- })
- }
- // Метод для тестирования запросов
- fun test() {
- val mapItems: MutableMap<String, Any?> = HashMap()
- mapItems["app_token"] = "kek"
- mapItems["app_user_id"] = "lol"
- val json = gson.toJson(mapItems)
- val url = "http://neprav.fun:8080/api/test"
- Log.d("serverConnection", "test sending: " + json)
- val formBody = json.toString().toRequestBody("application/json; charset=utf-8".toMediaTypeOrNull())
- val request = Request.Builder()
- .url(url)
- .post(formBody)
- .build()
- client.newCall(request).enqueue(object: Callback {
- override fun onFailure(call: Call, e: IOException) {
- val errors = StringWriter()
- e.printStackTrace(PrintWriter(errors))
- Log.d("serverConnection", errors.toString())
- }
- override fun onResponse(call: Call, response: Response) {
- Log.d("serverConnection", "Response code is: " + response.code)
- if (response.code == 200) {
- val body = response.body!!.string()
- Log.d("serverConnection", body)
- } else if(response.code == 202) {
- val body = response.body!!.string()
- Log.d("serverConnection", body)
- }
- response.body!!.close()
- }
- })
- }
- // Чтобы передавать объект между активитями
- override fun writeToParcel(p0: Parcel?, p1: Int) {
- p0?.writeString(APP_TOKEN)
- p0?.writeInt(APP_USER_ID)
- p0?.writeString(SOCIAL_TOKEN)
- p0?.writeInt(SOCIAL_ID)
- p0?.writeString(EMAIL)
- p0?.writeInt(EXPIRY_TIME)
- p0?.writeString(AUTH_TYPE)
- }
- override fun describeContents(): Int {
- return 0
- }
- companion object CREATOR : Parcelable.Creator<ServerConnection> {
- override fun createFromParcel(parcel: Parcel): ServerConnection {
- return ServerConnection(parcel)
- }
- override fun newArray(size: Int): Array<ServerConnection?> {
- return arrayOfNulls(size)
- }
- }
- val request = Request.Builder()
- .url("http://192.168.0.194:5000")
- .build()
- fun openWebSocket(activity: Activity) {
- webSocket = OkHttpClient().newWebSocket(request, object : WebSocketListener() {
- override fun onOpen(webSocket: WebSocket, response: Response) {
- //тост о том, что есть вебсокет соединение
- activity.run {
- runOnUiThread {
- Toast.makeText(this.applicationContext,"есть вебсокет соединение", Toast.LENGTH_LONG).show()
- }
- }
- webSocket.send("Hello!")
- webSocket.send("Yasno?")
- webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !")
- }
- override fun onMessage(webSocket: WebSocket, text: String) {
- super.onMessage(webSocket, text)
- }
- override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
- super.onMessage(webSocket, bytes)
- }
- override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
- val errors = StringWriter()
- t.printStackTrace(PrintWriter(errors))
- Log.d("Messages_info", errors.toString())
- }
- override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
- webSocket!!.close(NORMAL_CLOSURE_STATUS, "because why not")
- Log.d("Messages_info", code.toString() + " " + reason)
- }
- override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
- super.onClosed(webSocket, code, reason)
- }
- })
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement