Skip to content

Commit

Permalink
add AppUpdater
Browse files Browse the repository at this point in the history
  • Loading branch information
Ethosa committed Mar 31, 2022
1 parent 3deb038 commit 858220b
Show file tree
Hide file tree
Showing 20 changed files with 211 additions and 14 deletions.
6 changes: 6 additions & 0 deletions .idea/inspectionProfiles/Project_Default.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
package="com.ethosa.ktc">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
tools:ignore="ScopedStorage" />

<application
android:allowBackup="true"
Expand Down
19 changes: 19 additions & 0 deletions app/src/main/java/com/ethosa/ktc/college/ActualAppVersion.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package com.ethosa.ktc.college

/**
* JSON:
* { "actual_version": [0, 6, 0] }
*/
data class ActualAppVersion(
val actual_version: List<Int>,
val download_url: String
) {
fun isActual(): Boolean {
for (i in 0..2) {
if (actual_version[i] > CollegeApi.VERSION[i]) {
return false
}
}
return true
}
}
22 changes: 22 additions & 0 deletions app/src/main/java/com/ethosa/ktc/college/CollegeApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,12 @@ class CollegeApi {
private const val BRANCHES = "$MY_API/branches"
private const val COURSES = "$MY_API/courses"
private const val TIMETABLE = "$MY_API/timetable"
private const val TEACHER_TIMETABLE = "$MY_API/teacher-timetable"
private const val ACTUAL_VERSION = "$MY_API/actual-version"

// version Major.Minor.Patch
val VERSION = arrayOf(0, 6, 0)
val version = "v${VERSION[0]}.${VERSION[1]}.${VERSION[2]}"

/**
* Sends GET request to url.
Expand All @@ -30,6 +36,13 @@ class CollegeApi {
}
}

/**
* Fetches JSON with actual app version.
*/
fun fetchActualVersion(callback: CollegeCallback) {
sendRequest(ACTUAL_VERSION, callback)
}

/**
* Fetches all albums
*/
Expand Down Expand Up @@ -86,4 +99,13 @@ class CollegeApi {
else
sendRequest("$TIMETABLE/$groupId/$week", callback)
}

/**
* Fetches the teacher's timetable.
* @param branchId branch ID.
* @param teacherId unique teacher ID.
*/
fun fetchTeacherTimetable(branchId: Int, teacherId: Int, callback: CollegeCallback) {
sendRequest("$TEACHER_TIMETABLE/$branchId/$teacherId", callback)
}
}
2 changes: 1 addition & 1 deletion app/src/main/java/com/ethosa/ktc/college/ProCollege.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import android.annotation.SuppressLint
import android.content.Context
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar

/**
* Provides work with pro college.
Expand All @@ -21,6 +20,7 @@ class ProCollege(
/**
* Authorization in pro college using WebView.
*/
@Suppress("DEPRECATION")
@SuppressLint("SetJavaScriptEnabled")
fun auth(username: String, password: String) {
authInterface.webView = wb
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import com.ethosa.ktc.college.CollegeCallback
import com.ethosa.ktc.college.gallery.Album
import com.ethosa.ktc.databinding.ActivityAlbumBinding
import com.ethosa.ktc.ui.adapters.AlbumAdapter
import com.ethosa.ktc.utils.SpacingItemDecoration
import com.ethosa.ktc.ui.decoration.SpacingItemDecoration
import com.google.gson.Gson
import jp.wasabeef.glide.transformations.BlurTransformation
import okhttp3.Call
Expand Down
45 changes: 44 additions & 1 deletion app/src/main/java/com/ethosa/ktc/ui/activities/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,18 +1,33 @@
package com.ethosa.ktc.ui.activities

import android.os.Bundle
import com.google.android.material.bottomnavigation.BottomNavigationView
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.ethosa.ktc.R
import com.ethosa.ktc.college.ActualAppVersion
import com.ethosa.ktc.college.CollegeApi
import com.ethosa.ktc.college.CollegeCallback
import com.ethosa.ktc.databinding.ActivityMainBinding
import com.ethosa.ktc.utils.AppUpdater
import com.ethosa.ktc.utils.Permissions
import com.google.android.material.bottomnavigation.BottomNavigationView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Response

/**
* The main app activity.
*/
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val collegeApi = CollegeApi()
private val permissions = Permissions()

companion object {
const val PERMISSION_STORAGE = 101
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Expand All @@ -23,5 +38,33 @@ class MainActivity : AppCompatActivity() {
val navView: BottomNavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_activity_main)
navView.setupWithNavController(navController)

// Check to actual version
collegeApi.fetchActualVersion(object : CollegeCallback {
override fun onResponse(call: Call, response: Response) {
val body = response.body?.string()
val actual = Gson().fromJson(body, ActualAppVersion::class.java)
val newVersion = "v${actual.actual_version[0]}.${actual.actual_version[1]}.${actual.actual_version[2]}"

if (actual.isActual())
return
runOnUiThread {
MaterialAlertDialogBuilder(this@MainActivity)
.setTitle("Доступно обновление")
.setMessage("Текущая версия: ${CollegeApi.version}, Актуальная: $newVersion.")
.setNegativeButton("Не сейчас") { dialog, _ ->
dialog.dismiss()
}
.setPositiveButton("Скачать обновление") { dialog, _ ->
permissions.requestPermissions(this@MainActivity, PERMISSION_STORAGE)
if (!permissions.hasPermissions(this@MainActivity))
return@setPositiveButton
AppUpdater(this@MainActivity).update(actual.download_url)
dialog.dismiss()
}
.show()
}
}
})
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.ethosa.ktc.R
import com.ethosa.ktc.databinding.LayoutAlbumImageBinding
import com.ethosa.ktc.utils.AlbumPhotoDialog
import com.ethosa.ktc.ui.dialog.AlbumPhotoDialog


/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.ethosa.ktc.utils
package com.ethosa.ktc.ui.decoration

import android.graphics.Rect
import android.view.View
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package com.ethosa.ktc.utils
package com.ethosa.ktc.ui.dialog

import android.animation.ObjectAnimator
import android.animation.PropertyValuesHolder
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import com.ethosa.ktc.college.CollegeCallback
import com.ethosa.ktc.college.gallery.Albums
import com.ethosa.ktc.databinding.FragmentGalleryBinding
import com.ethosa.ktc.ui.adapters.AlbumsPreviewAdapter
import com.ethosa.ktc.utils.SpacingItemDecoration
import com.ethosa.ktc.ui.decoration.SpacingItemDecoration
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Response
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import com.ethosa.ktc.college.CollegeCallback
import com.ethosa.ktc.college.news.LastNews
import com.ethosa.ktc.databinding.FragmentNewsBinding
import com.ethosa.ktc.ui.adapters.NewsAdapter
import com.ethosa.ktc.utils.SpacingItemDecoration
import com.ethosa.ktc.ui.decoration.SpacingItemDecoration
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Response
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,10 @@ import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.ethosa.ktc.R
import com.ethosa.ktc.databinding.FragmentSettingsBinding
import com.ethosa.ktc.ui.adapters.SettingsAdapter
import com.ethosa.ktc.utils.SpacingItemDecoration
import com.ethosa.ktc.ui.decoration.SpacingItemDecoration

/**
* Provides working with KTC last news.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import com.ethosa.ktc.ui.adapters.BranchAdapter
import com.ethosa.ktc.ui.adapters.CourseAdapter
import com.ethosa.ktc.ui.adapters.TimetableAdapter
import com.ethosa.ktc.utils.IOFragmentBackPressed
import com.ethosa.ktc.utils.SpacingItemDecoration
import com.ethosa.ktc.ui.decoration.SpacingItemDecoration
import com.google.gson.Gson
import okhttp3.Call
import okhttp3.Response
Expand Down
46 changes: 46 additions & 0 deletions app/src/main/java/com/ethosa/ktc/utils/AppUpdater.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.ethosa.ktc.utils

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import com.ethosa.ktc.college.CollegeCallback
import okhttp3.Call
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File


class AppUpdater(
private val context: Context
) {
fun update(url: String) {
val path = Environment.getDownloadCacheDirectory().toString() + "/KTC/"
val req = Request.Builder()
.url(url)
.get()
.build()
OkHttpClient().newCall(req).enqueue(object : CollegeCallback {
override fun onResponse(call: Call, response: Response) {
val file = File(path)
file.mkdirs()
val apkFile = File(file, "actual_app.apk")
val output = apkFile.outputStream()
val input = response.body?.byteStream()
val buffer = ByteArray(1024)
var len1: Int
while (input!!.read(buffer).also { len1 = it } != -1) {
output.write(buffer, 0, len1)
}
output.close()
input.close()

val install = Intent(Intent.ACTION_VIEW)
.setData(Uri.parse(path + "app.apk"))
.setType("application/android.com.app")
context.startActivity(install)
}
})
}
}
51 changes: 51 additions & 0 deletions app/src/main/java/com/ethosa/ktc/utils/Permissions.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.ethosa.ktc.utils

import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat


class Permissions {
fun hasPermissions(context: Context?): Boolean {
return when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
Environment.isExternalStorageManager()
}
Build.VERSION.SDK_INT >= Build.VERSION_CODES.M -> {
(ContextCompat.checkSelfPermission(context!!, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED)
}
else -> {
true
}
}
}

fun requestPermissions(activity: Activity, requestCode: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
try {
val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
intent.addCategory("android.intent.category.DEFAULT")
intent.data = Uri.parse(String.format("package:%s", activity.packageName))
activity.startActivityForResult(intent, requestCode)
} catch (e: Exception) {
val intent = Intent()
intent.action = Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION
activity.startActivityForResult(intent, requestCode)
}
} else {
ActivityCompat.requestPermissions(
activity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
requestCode
)
}
}
}
3 changes: 2 additions & 1 deletion app/src/main/res/layout/timetable_widget.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
android:src="@drawable/ic_reload"
app:srcCompat="@drawable/ic_reload"
app:tint="@color/primary"
tools:ignore="ContentDescription,ImageContrastCheck" />
android:tint="@color/primary"
tools:ignore="ContentDescription,ImageContrastCheck,UseAppTint" />
</LinearLayout>

<LinearLayout
Expand Down
Loading

0 comments on commit 858220b

Please sign in to comment.