content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package com.unblu.brandeableagentapp.model
import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.android.material.snackbar.Snackbar
import com.unblu.brandeableagentapp.api.UnbluController
import com.unblu.brandeableagentapp.data.AppConfiguration
import com.unblu.brandeableagentapp.login.direct.LoginHelper
import com.unblu.brandeableagentapp.login.direct.util.validatePassword
import com.unblu.brandeableagentapp.login.direct.util.validateUsername
import com.unblu.brandeableagentapp.data.Storage.UNBLU_USERNAME
import com.unblu.sdk.core.Unblu
import com.unblu.sdk.core.callback.InitializeExceptionCallback
import com.unblu.sdk.core.configuration.UnbluClientConfiguration
import com.unblu.sdk.core.configuration.UnbluCookie
import com.unblu.sdk.core.errortype.UnbluClientErrorType
import io.reactivex.rxjava3.disposables.CompositeDisposable
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
/**
* edit this class aaccording to the [AuthenticationType] that will be used:
* if you are using [AuthenticationType.OAuth] you should only keep the following properties and methods:
* [LoginViewModel.customTabsOpen]
* [LoginViewModel._customTabsOpen]
* [LoginViewModel.resetSSOLogin]
* [LoginViewModel.launchSSO]
*
* if you are using [AuthenticationType.Direct]:
* [LoginViewModel.password]
* [LoginViewModel.username]
* [LoginViewModel.passwordVisiblity]
* [LoginViewModel._passwordVisiblity]
* [LoginViewModel.startUnblu]
* [LoginViewModel.login]
* [LoginViewModel.setPasswordVisiblity]
*
* Finalliy if you are using [AuthenticationType.WebProxy]
* [LoginViewModel.startUnblu]
* [LoginViewModel._showWebview]
* [LoginViewModel.showWebview]
* [LoginViewModel.onCookieReceived]
* [LoginViewModel.launchSSO]
*
* then you can delete the properties/methods that refer to the other authentication types and it's subsequent references.
*/
class LoginViewModel : ViewModel() {
private lateinit var unbluController: UnbluController
private val _navigationState = MutableStateFlow<NavigationState?>(null)
val navigationState: StateFlow<NavigationState?> = _navigationState
private val _loginState = MutableStateFlow<LoginState>(LoginState.LoggedOut)
val loginState: StateFlow<LoginState> = _loginState
private val resources = CompositeDisposable()
//oAuth
private val _customTabsOpen = MutableStateFlow(false)
val customTabsOpen: StateFlow<Boolean> = _customTabsOpen
//WebProxy
private val _showWebview = MutableStateFlow(false)
val showWebview: StateFlow<Boolean> = _showWebview
val onCookieReceived: (Set<UnbluCookie>?) -> Unit = { cookies ->
startUnblu(cookies)
}
//Direct
val password = mutableStateOf("harmless-squire-spotter")
val username = mutableStateOf("superadmin")
//Direct login
private val _passwordVisiblity = MutableStateFlow(false)
val passwordVisiblity: StateFlow<Boolean> = _passwordVisiblity
fun startUnblu(cookies: Set<UnbluCookie>?) {
viewModelScope.launch {
_showWebview.emit(false)
}
val config = cookies?.let {
UnbluClientConfiguration.Builder(unbluController.getConfiguration())
.setUnbluBaseUrl(AppConfiguration.unbluServerUrl)
.setApiKey(AppConfiguration.unbluApiKey)
.setEntryPath(AppConfiguration.entryPath)
.setCustomCookies(cookies).build()
} ?: unbluController.getConfiguration()
unbluController.start(config, {
viewModelScope.launch {
_loginState.emit(LoginState.LoggedIn)
_navigationState.emit(NavigationState.Success(it.mainView))
}
}, object : InitializeExceptionCallback {
override fun onConfigureNotCalled() {
_navigationState.value =
NavigationState.Failure("Error message: onConfigureNotCalled")
resetSSOLogin()
}
override fun onInErrorState() {
_navigationState.value =
NavigationState.Failure("Error message: onInErrorState")
resetSSOLogin()
}
override fun onInitFailed(
errorType: UnbluClientErrorType,
details: String?
) {
_navigationState.value = NavigationState.Failure("Error message: $details")
resetSSOLogin()
}
})
}
init {
resources.add(Unblu.onError().subscribe {
NavigationState.Failure("Error message: Check ${it.message}")
viewModelScope.launch {
delay(500)
_navigationState.emit(null)
}
})
}
fun login(username: String, password: String) {
if (loginState.value.isLoggingIn()) return
val user = validateUsername(username)
if (!user || !validatePassword(password)) {
val wrongData = if (!user) "Username" else "Password"
_navigationState.value = NavigationState.Failure("Error message: Check $wrongData")
} else {
viewModelScope.launch {
_loginState.emit(LoginState.LoggingIn)
LoginHelper.login(
unbluController.getConfiguration(),
username,
password,
{ cookies ->
unbluController.getPreferencesStorage().put(UNBLU_USERNAME, username)
startUnblu(cookies)
},
{ error ->
_navigationState.value = NavigationState.Failure("Error message: $error")
_loginState.value = LoginState.LoggedOut
})
}
}
}
fun onPasswordChange(newPassword: String) {
password.value = newPassword
}
fun onUsernameChange(newUsername: String) {
username.value = newUsername
}
fun setPasswordVisiblity(show: Boolean) {
viewModelScope.launch {
_passwordVisiblity.emit(show)
}
}
fun launchSSO() {
viewModelScope.launch {
_loginState.emit(LoginState.LoggingIn)
}
viewModelScope.launch {
/**
* edit this code aaccording to the [AuthenticationType]
* if you are using [AuthenticationType.OAuth] replace it with :
* _customTabsOpen.emit(true)
*
* Otherwise replace it with:
* _showWebview.emit(true)
*/
if (AppConfiguration.authType is AuthenticationType.OAuth)
_customTabsOpen.emit(true)
else
_showWebview.emit(true)
}
}
fun resetSSOLogin() {
viewModelScope.launch {
_loginState.emit(LoginState.LoggedOut)
_customTabsOpen.emit(false)
_showWebview.emit(false)
_navigationState.emit(null)
}
}
override fun onCleared() {
resources.clear()
super.onCleared()
}
private suspend fun doResetLoginState() {
_navigationState.emit(null)
_loginState.emit(LoginState.LoggedOut)
}
fun stopUnblu() {
unbluController.stop {
viewModelScope.launch {
doResetLoginState()
}
}
}
fun setUnbluController(unbluController: UnbluController) {
this.unbluController = unbluController
if (AppConfiguration.authType == AuthenticationType.Direct)
unbluController.getPreferencesStorage().get(UNBLU_USERNAME)?.apply {
onUsernameChange(this)
}
}
fun setErrorMessage(message: String) {
_navigationState.value = NavigationState.Failure("Error message: $message")
}
}
private fun LoginState?.isLoggingIn(): Boolean {
Log.d("LOGIN STATE", "will return as we are already loggin")
return this is LoginState.LoggingIn
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/model/LoginViewModel.kt
|
2340716089
|
package com.unblu.brandeableagentapp.model
/**
* you should only keep this class if the selected [AuthenticationType] is [AuthenticationType.OAuth]
*/
sealed class TokenEvent {
data class TokenReceived(val token: String) : TokenEvent()
data class ErrorReceived(val error: String) : TokenEvent()
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/model/TokenEvent.kt
|
1296043689
|
package com.unblu.brandeableagentapp.model
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.unblu.brandeableagentapp.data.AppConfiguration
import com.unblu.brandeableagentapp.data.Storage.UNBLU_SETTINGS
import com.unblu.brandeableagentapp.login.sso.deleteAuthState
import com.unblu.brandeableagentapp.util.AuthenticationTypeAdapter
import com.unblu.sdk.core.configuration.UnbluPreferencesStorage
class SettingsViewModel : ViewModel() {
private lateinit var unbluPreferencesStorage: UnbluPreferencesStorage
private val _settingsModel = mutableStateOf(SettingsModel())
val settingsModel: State<SettingsModel> get() = _settingsModel
fun fetchSettingsModel(unbluPreferencesStorage : UnbluPreferencesStorage) {
this.unbluPreferencesStorage = unbluPreferencesStorage
val storedSettingsJson = unbluPreferencesStorage.get(UNBLU_SETTINGS)
val gson = GsonBuilder()
.registerTypeAdapter(AuthenticationType::class.java, AuthenticationTypeAdapter())
.create()
_settingsModel.value = storedSettingsJson?.let {
gson.fromJson(it, SettingsModel::class.java)
}?: SettingsModel()
updateSettingsModel(_settingsModel.value)
}
fun updateSettingsModel(updatedModel: SettingsModel) {
_settingsModel.value = updatedModel
}
fun saveModel() {
if(_settingsModel.value.authType != AuthenticationType.OAuth)
deleteAuthState(unbluPreferencesStorage)
unbluPreferencesStorage.put(UNBLU_SETTINGS, Gson().toJson(_settingsModel.value))
AppConfiguration.updateFromSettingsModel(_settingsModel.value)
}
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/model/SettingsViewModel.kt
|
3913397376
|
package com.unblu.brandeableagentapp.model
sealed class LoginState {
object LoggedOut : LoginState()
object LoggedIn : LoginState()
object LoggingIn : LoginState()
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/model/LoginState.kt
|
225488649
|
package com.unblu.brandeableagentapp.model
sealed class AuthenticationType(var name: String) {
object Direct : AuthenticationType("Direct")
object OAuth : AuthenticationType("OAuth")
object WebProxy : AuthenticationType("WebProxy")
}
fun authTypeFromName(string: String) :AuthenticationType{
return when(string){
AuthenticationType.Direct.name-> AuthenticationType.Direct
AuthenticationType.WebProxy.name -> AuthenticationType.WebProxy
AuthenticationType.OAuth.name-> AuthenticationType.OAuth
else -> AuthenticationType.Direct
}
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/model/AuthenticationType.kt
|
184948649
|
package com.unblu.brandeableagentapp.model
import android.view.View
sealed class NavigationState {
data class Success(val view : View) : NavigationState()
data class Failure(val message: String) : NavigationState()
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/model/NavigationState.kt
|
3242437966
|
package com.unblu.brandeableagentapp.model
import com.unblu.brandeableagentapp.data.AppConfiguration
data class SettingsModel(
var unbluServerUrl: String = AppConfiguration.unbluServerUrl,
var unbluApiKey: String = AppConfiguration.unbluApiKey,
var entryPath: String = AppConfiguration.entryPath,
var authType: AuthenticationType = AppConfiguration.authType,
var webAuthProxyServerAddress : String = AppConfiguration.webAuthProxyServerAddress,
val oAuthClientId: String = AppConfiguration.oAuthClientId,
val oAuthRedirectUri: String = AppConfiguration.oAuthRedirectUri,
val oAuthEndpoint: String = AppConfiguration.oAuthEndpoint,
val oAuthTokenEndpoint: String = AppConfiguration.oAuthTokenEndpoint
)
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/model/SettingsModel.kt
|
271835696
|
package com.unblu.brandeableagentapp.model
import android.view.View
import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.unblu.sdk.core.agent.UnbluAgentClient
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.launch
class UnbluScreenViewModel : ViewModel() {
private var _showDialog = mutableStateOf(false)
val showDialog : State<Boolean> get() = _showDialog
private val _sessionEnded = MutableSharedFlow<Unit>()
val sessionEnded = _sessionEnded.asSharedFlow()
private var _chatUiOpen = mutableStateOf(false)
val chatUiOpen: State<Boolean> = _chatUiOpen
private lateinit var agentClient: UnbluAgentClient
fun setClient(agentClient: UnbluAgentClient) {
this.agentClient = agentClient
}
fun setShowDialog(show: Boolean) {
_showDialog.value = show
}
fun endSession(){
viewModelScope.launch {
_sessionEnded.emit(Unit)
}
}
fun emitChatOpen(chatUiOpen: Boolean) {
_chatUiOpen.value = chatUiOpen
}
fun getView() : View{
return agentClient.mainView
}
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/model/UnbluScreenViewModel.kt
|
3883257503
|
package com.unblu.brandeableagentapp.api
import android.app.Application
import android.util.Log
import android.view.View
import com.unblu.brandeableagentapp.AgentApplication
import com.unblu.brandeableagentapp.data.AppConfiguration
import com.unblu.livekitmodule.LiveKitModuleProvider
import com.unblu.sdk.core.Unblu
import com.unblu.sdk.core.agent.UnbluAgentClient
import com.unblu.sdk.core.callback.InitializeExceptionCallback
import com.unblu.sdk.core.callback.InitializeSuccessCallback
import com.unblu.sdk.core.configuration.UnbluClientConfiguration
import com.unblu.sdk.core.configuration.UnbluDownloadHandler
import com.unblu.sdk.core.configuration.UnbluPreferencesStorage
import com.unblu.sdk.core.links.UnbluPatternMatchingExternalLinkHandler
import com.unblu.sdk.core.module.call.CallModuleProviderFactory
import com.unblu.sdk.core.notification.UnbluNotificationApi
import com.unblu.sdk.module.call.CallModule
import com.unblu.sdk.module.call.CallModuleProvider
import com.unblu.sdk.module.mobilecobrowsing.MobileCoBrowsingModule
import com.unblu.sdk.module.mobilecobrowsing.MobileCoBrowsingModuleProvider
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.subjects.BehaviorSubject
import java.util.*
class UnbluController(
var agentApplication: AgentApplication
) {
private val unbluDownloadHandler: UnbluDownloadHandler = UnbluDownloadHandler.createExternalStorageDownloadHandler(agentApplication)
private var unbluClientConfiguration: UnbluClientConfiguration = createUnbluClientConfiguration()
//Store uiShowRequests as you may receive them when you don't have a client running
//or the Unblu Ui isn't attached
private var onUiShowRequest = BehaviorSubject.createDefault(false)
private var agentClient: UnbluAgentClient? = null
private lateinit var callModule: CallModule
private lateinit var coBrowsingModule: MobileCoBrowsingModule
private var unbluNotificationApi: UnbluNotificationApi =
//Use line below if you will be using UnbluFirebaseNotificationService to receive push notifications. Also make sure you have your google-services.json in the app/ folder.
//UnbluFirebaseNotificationService.getNotificationApi()
UnbluNotificationApi.createNotificationApi()
fun start(
config: UnbluClientConfiguration,
successVoidCallback: InitializeSuccessCallback<UnbluAgentClient>,
deinitializeExceptionCallback: InitializeExceptionCallback
) {
unbluClientConfiguration = config
//create your Client Instance
createClient(successVoidCallback, deinitializeExceptionCallback)
}
private fun createClient(
successCallback: InitializeSuccessCallback<UnbluAgentClient>,
initializeExceptionCallback: InitializeExceptionCallback
) {
Unblu.createAgentClient(
agentApplication as Application,
unbluClientConfiguration,
unbluNotificationApi,
{
agentClient = it
successCallback.onSuccess(it)
},
initializeExceptionCallback
)
}
private fun createUnbluClientConfiguration (): UnbluClientConfiguration {
callModule = CallModuleProviderFactory.createDynamic(
CallModuleProvider.createForDynamic(),
LiveKitModuleProvider.createForDynamic()
)
coBrowsingModule = MobileCoBrowsingModuleProvider.create()
return UnbluClientConfiguration.Builder(
AppConfiguration.unbluServerUrl,
AppConfiguration.unbluApiKey,
agentApplication.getUnbluPrefs(),
unbluDownloadHandler,
UnbluPatternMatchingExternalLinkHandler()
)
.setEntryPath(AppConfiguration.entryPath)
//.setInternalUrlPatternWhitelist(listOf(Pattern.compile("https://agent-sso-trusted\\.cloud\\.unblu-env\\.com")))
.registerModule(callModule)
.registerModule(coBrowsingModule).build()
}
fun getClient(): UnbluAgentClient? {
return if (Objects.isNull(agentClient) || (agentClient!!.isDeInitialized)) null else agentClient
}
fun getCallModule(): CallModule {
return callModule
}
fun getCoBrowsingModule(): MobileCoBrowsingModule {
return coBrowsingModule
}
fun getUnbluUi(): View? {
return agentClient?.mainView
}
fun setRequestedUiShow() {
onUiShowRequest.onNext(true)
}
fun hasUiShowRequest(): Observable<Boolean> {
return onUiShowRequest
}
fun clearUiShowRequest() {
onUiShowRequest.onNext(false)
}
fun getHasUiShowRequestValueAndReset(): Boolean {
val showUiVal = onUiShowRequest.value!!
clearUiShowRequest()
return showUiVal
}
fun getConfiguration(): UnbluClientConfiguration {
createUnbluClientConfiguration()
unbluClientConfiguration =
UnbluClientConfiguration.Builder(unbluClientConfiguration)
.setUnbluBaseUrl(AppConfiguration.unbluServerUrl)
.setApiKey(AppConfiguration.unbluApiKey)
.setEntryPath(AppConfiguration.entryPath)
.build()
return unbluClientConfiguration
}
fun stop(onStopped: () -> Unit) {
agentClient?.let { agentClient ->
agentClient.deinitClient({
onStopped()
}, {
Log.e("UnbluController", "Error deInitializing: $it")
})
} ?: run(onStopped)
agentClient = null
}
fun setOAuthToken(token: String) {
unbluClientConfiguration = UnbluClientConfiguration.Builder(unbluClientConfiguration).setOAuthToken(token).build()
}
fun getPreferencesStorage(): UnbluPreferencesStorage {
return unbluClientConfiguration.preferencesStorage
}
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/api/UnbluController.kt
|
2101259314
|
package com.unblu.brandeableagentapp.nav
import android.annotation.SuppressLint
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.runtime.*
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavHostController
import com.google.accompanist.navigation.animation.AnimatedNavHost
import com.google.accompanist.navigation.animation.composable
import com.unblu.brandeableagentapp.data.AppConfiguration
import com.unblu.brandeableagentapp.model.AuthenticationType
import com.unblu.brandeableagentapp.model.LoginViewModel
import com.unblu.brandeableagentapp.model.SettingsViewModel
import com.unblu.brandeableagentapp.model.UnbluScreenViewModel
import com.unblu.brandeableagentapp.ui.*
@SuppressLint("ServiceCast")
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun NavGraph(navController: NavHostController, viewModelStore: ViewModelProvider) {
val loginViewModel = viewModelStore[LoginViewModel::class.java]
val successViewModel = viewModelStore[UnbluScreenViewModel::class.java]
navController.enableOnBackPressed(false)
AnimatedNavHost(navController, startDestination = NavRoute.Splash.route) {
composable(
NavRoute.Splash.route,
enterTransition = { fadeIn() },
exitTransition = { fadeOut() }) {
SplashScreen(navController)
}
//This screen is useful for development purposes, should be deleted when no longer needed
composable(
route = NavRoute.Settings.route,
enterTransition = { fadeIn() },
exitTransition = { fadeOut() }) {
val settingsViewModel = viewModelStore[SettingsViewModel::class.java]
loginViewModel.resetSSOLogin()
SettingsScreen(navController, settingsViewModel.settingsModel,
{
settingsViewModel.saveModel()
}) { updatedModel ->
settingsViewModel.updateSettingsModel(updatedModel)
}
}
composable(
route = NavRoute.Login.route,
enterTransition = { fadeIn() },
exitTransition = { fadeOut() }) {
//Edit this according to the AuthenticationType you will be using, if AuthenticationType.Direct just keep "LoginScreen(navController, loginViewModel)", if not keep LoginScreenSSO(navController, loginViewModel) and delete the other lines
if (AppConfiguration.authType !is AuthenticationType.Direct) {
LoginScreenSSO(navController, loginViewModel)
} else {
LoginScreen(navController, loginViewModel)
}
}
composable(
route = NavRoute.Unblu.route,
enterTransition = { fadeIn() },
exitTransition = { fadeOut() }) {
SuccessScreen(navController, successViewModel) {
loginViewModel.stopUnblu()
successViewModel.setShowDialog(false)
}
}
}
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/nav/NavGraph.kt
|
1026219738
|
package com.unblu.brandeableagentapp.nav
import com.unblu.brandeableagentapp.ui.SettingsScreen
sealed class NavRoute(var route: String) {
object Splash: NavRoute("splash")
object Login: NavRoute("login")
object Unblu: NavRoute("success")
/**
* No need for this Route if you delete [SettingsScreen]
*/
object Settings: NavRoute("settings")
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/nav/NavRoute.kt
|
3820585143
|
package com.unblu.brandeableagentapp.data
import com.google.gson.Gson
import com.unblu.brandeableagentapp.model.SettingsModel
import com.unblu.sdk.core.configuration.UnbluPreferencesStorage
object Storage {
const val UNBLU_USERNAME = "u_username"
const val UNBLU_SETTINGS ="u_settings"
fun getUnbluSettings(unbluPreferencesStorage: UnbluPreferencesStorage) : SettingsModel {
return try {
val storedSettingsJson = unbluPreferencesStorage.get(UNBLU_SETTINGS)
storedSettingsJson?.let { settingsJsons->
Gson().fromJson(settingsJsons, SettingsModel::class.java)
}?: SettingsModel()
}catch (e: Exception){
SettingsModel()
}
}
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/data/Storage.kt
|
3987858151
|
package com.unblu.brandeableagentapp.data
import com.unblu.brandeableagentapp.model.AuthenticationType
import com.unblu.brandeableagentapp.model.SettingsModel
object AppConfiguration {
var unbluServerUrl = "https://testing7.dev.unblu-test.com"
var unbluApiKey = "MZsy5sFESYqU7MawXZgR_w"
var entryPath = "/co-unblu"
var authType: AuthenticationType = AuthenticationType.Direct
//WebProxy
var webAuthProxyServerAddress = "https://agent-sso-trusted.cloud.unblu-env.com"
//OAuth
var oAuthClientId = "aae6ad6b-2230-414e-83f0-2b5933499b0b"
var oAuthRedirectUri = "msauth://com.unblu.brandeableagentapp/9fs7u0FrIlzqcFJ0wGxh9CRs6iQ%3D"
var oAuthEndpoint =
"https://login.microsoftonline.com/8005dd54-64b0-4f9d-bf46-e2582d0c2760/oauth2/v2.0/authorize"
var oAuthTokenEndpoint =
"https://login.microsoftonline.com/8005dd54-64b0-4f9d-bf46-e2582d0c2760/oauth2/v2.0/token"
fun updateFromSettingsModel(settingsModel: SettingsModel){
unbluServerUrl = settingsModel.unbluServerUrl
unbluApiKey = settingsModel.unbluApiKey
entryPath = settingsModel.entryPath
authType = settingsModel.authType
webAuthProxyServerAddress = settingsModel.webAuthProxyServerAddress
oAuthClientId = settingsModel.oAuthClientId
oAuthRedirectUri = settingsModel.oAuthRedirectUri
oAuthEndpoint = settingsModel.oAuthEndpoint
oAuthTokenEndpoint = settingsModel.oAuthTokenEndpoint
}
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/data/AppConfiguration.kt
|
3116908467
|
package com.unblu.brandeableagentapp.login.proxy
import android.util.Log
import android.webkit.*
import com.unblu.brandeableagentapp.data.AppConfiguration
import com.unblu.brandeableagentapp.model.AuthenticationType
import com.unblu.sdk.core.configuration.UnbluCookie
import java.net.HttpCookie
/**
* This class can be deleted in case the selected [AuthenticationType] is not [AuthenticationType.WebProxy].
* If so, make sure you also delete the folder in the project.
* @property onCookieReceived Function1<Set<UnbluCookie>?, Unit>
* @constructor
*/
class ProxyWebViewClient(private val onCookieReceived: (Set<UnbluCookie>?) -> Unit) : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
var doOverride = false
request?.apply {
Log.i("ProxyWebViewClient", "shouldOverrideUrlLoading : $url")
val urlString = url.toString()
if (urlString.contains(AppConfiguration.webAuthProxyServerAddress + AppConfiguration.entryPath + "/desk")) {
doOverride = true
view?.stopLoading()
// Get cookies and pass them to the webViewInterface's onComplete method
val cookieManager = CookieManager.getInstance()
val cookiesString = cookieManager.getCookie(AppConfiguration.webAuthProxyServerAddress)
Log.i("ProxyWebViewClient", "cookiesString : $cookiesString")
cleanupCookies(cookieManager){
Log.i("ProxyWebViewClient", "cleaning up cookies from proxy client")
val cookies = parseCookies(cookiesString)
onCookieReceived(UnbluCookie.from(cookies))
}
}
}
return doOverride // Allow the WebView to handle the navigation
}
private fun cleanupCookies(cookieManager: CookieManager, callback : ValueCallback<Boolean>) {
cookieManager.removeAllCookies {
callback.onReceiveValue(it)
}
}
private fun parseCookies(cookiesString: String): List<HttpCookie> {
val cookies = mutableListOf<HttpCookie>()
val keyValuePairs = cookiesString.split(";")
keyValuePairs.forEach { keyValue ->
val keyValueSplit = keyValue.split("=", limit = 2)
if (keyValueSplit.size == 2) {
val cookieName = keyValueSplit[0].trim()
val cookieValue = keyValueSplit[1].trim().trim { it == '"' }
Log.d("ProxyWebViewClient", "keyValueSplit : $cookieName=$cookieValue")
// Create a new Cookie object and add it to the list
val cookie = HttpCookie(cookieName, cookieValue)
cookies.add(cookie)
}
}
return cookies
}
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/login/proxy/ProxyWebViewClient.kt
|
3245525206
|
package com.unblu.brandeableagentapp.login.direct.util
fun validateUsername(user : String?) : Boolean{
return user?.isNotEmpty() ?: false
}
fun validatePassword(password : String?) : Boolean{
return password?.isNotEmpty() ?: false
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/login/direct/util/DataValidator.kt
|
658675519
|
/*
* Copyright (c) 2020. Unblu inc., Basel, Switzerland
* All rights reserved.
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package com.unblu.brandeableagentapp.login.direct
import android.net.Uri
import android.util.Log
import android.webkit.ValueCallback
import androidx.compose.ui.text.toLowerCase
import androidx.core.util.Pair
import com.unblu.brandeableagentapp.login.LoginFailedException
import com.unblu.sdk.core.configuration.UnbluClientConfiguration
import com.unblu.sdk.core.configuration.UnbluCookie
import com.unblu.sdk.core.internal.utils.CookieUtils
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.io.InputStream
import java.net.HttpCookie
import java.net.HttpURLConnection
import java.net.URL
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
object LoginHelper {
private const val UNBLU_REST_PATH: String = "/rest/v3"
private val TAG = LoginHelper::class.java.simpleName
fun login(
configuration: UnbluClientConfiguration,
loginUsername: String?,
loginPassword: String?,
success: ValueCallback<Set<UnbluCookie>?>,
failure: ValueCallback<String?>
) {
if (loginUsername == null || loginPassword == null) {
success.onReceiveValue(null)
return
}
val username: String = loginUsername
val password: String = loginPassword
val loginConnection = arrayOf<HttpURLConnection?>(null)
Single.fromCallable {
val loginUrl = URL(
Uri.parse(configuration.unbluBaseUrl + configuration.entryPath + UNBLU_REST_PATH + "/authenticator/login")
.toString()
)
loginConnection[0] = loginUrl.openConnection() as HttpURLConnection
loginConnection[0]!!.requestMethod = "POST"
loginConnection[0]!!.setRequestProperty("Content-Type", "application/json")
loginConnection[0]!!.doOutput = true
val obj: JSONObject = generateCredentials(username, password)
?: return@fromCallable Pair<Any?, LoginFailedException?>(
null,
LoginFailedException("Failed to encode authentication login credentials")
)
val cookies: Set<UnbluCookie> = CookieUtils.enhanceCookiesWithDeviceIdentifier(
configuration.preferencesStorage,
configuration.customCookies
)
if (cookies.isNotEmpty()) {
for (cookie in cookies) {
val cookieHeader: String = CookieUtils.createCookieString(
cookie,
CookieUtils.checkIfSecureUrl(loginUrl.toString())
)
loginConnection[0]!!.setRequestProperty("Cookie", cookieHeader)
}
}
val os = loginConnection[0]!!.outputStream
val input: ByteArray = obj.toString().toByteArray(StandardCharsets.UTF_8)
os.write(input, 0, input.size)
val responseCode = loginConnection[0]!!.responseCode
val responseBody = loginConnection[0]!!.inputStream.readToString()
handleLoginResponse(loginConnection[0], responseCode, responseBody)
}
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ result: Pair<out Any?, LoginFailedException?> ->
if (result.first == null) {
Log.e(
TAG,
"Failed to login with the given credentials!",
result.second
)
failure.onReceiveValue(result.second!!.message)
} else {
success.onReceiveValue(result.first as Set<UnbluCookie>?)
}
if (loginConnection[0] != null) {
loginConnection[0]!!.disconnect()
}
}
) { throwable: Throwable ->
throwable.message?.let { Log.e(TAG, it, throwable) }
failure.onReceiveValue("Could not Login: ${throwable.message}")
}
}
private fun generateCredentials(username: String, password: String): JSONObject? {
return try {
val obj = JSONObject()
obj.put("username", username)
obj.put("password", password)
obj
} catch (e: JSONException) {
Log.e(TAG, "Failed to encode authentication login credentials", e)
null
}
}
@Throws(IOException::class)
private fun handleLoginResponse(
loginConnection: HttpURLConnection?,
responseCode: Int,
responseBody: String
): Pair<Set<UnbluCookie>?, LoginFailedException?> {
return if (responseCode == 200) {
if (!responseBody.toBooleanStrict()) {
return Pair<Set<UnbluCookie>?, LoginFailedException?>(
null,
LoginFailedException("Invalid credentials for login")
)
}
val headers = loginConnection!!.headerFields
val authCookies: Set<UnbluCookie> =
getAuthenticationCookies(headers)
if (authCookies.isEmpty()) {
Pair<Set<UnbluCookie>?, LoginFailedException?>(
null,
LoginFailedException("Did not receive valid cookies after authentication. Headers: $headers")
)
} else Pair<Set<UnbluCookie>?, LoginFailedException?>(
authCookies,
null
)
} else {
Pair<Set<UnbluCookie>?, LoginFailedException?>(
null,
LoginFailedException("Failed to login. StatusCode: " + loginConnection!!.responseCode + "; StatusText: " + loginConnection.responseMessage + "; Details: " + responseBody)
)
}
}
private fun getAuthenticationCookies(headers: Map<String, List<String>>): Set<UnbluCookie> {
val authCookies: MutableMap<String, String> = HashMap()
for ((key, value) in headers) {
if (key?.lowercase() == "set-cookie") {
for (setCookieValue in value) {
val responseCookieList = HttpCookie.parse(setCookieValue)
for (responseCookie in responseCookieList) {
authCookies[responseCookie.name] = responseCookie.value
}
}
}
}
return HashSet<UnbluCookie>(UnbluCookie.from(authCookies))
}
fun InputStream.readToString(charset: Charset = Charsets.UTF_8): String {
return this.bufferedReader(charset).use { it.readText() }
}
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/login/direct/LoginHelper.kt
|
4246310146
|
package com.unblu.brandeableagentapp.login.direct
class DirectLoginController {
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/login/direct/DirectLoginController.kt
|
2907679166
|
package com.unblu.brandeableagentapp.login.sso
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.util.Log
import androidx.activity.result.ActivityResultLauncher
import com.unblu.brandeableagentapp.AgentApplication
import com.unblu.brandeableagentapp.R
import com.unblu.brandeableagentapp.data.AppConfiguration.oAuthClientId
import com.unblu.brandeableagentapp.data.AppConfiguration.oAuthEndpoint
import com.unblu.brandeableagentapp.data.AppConfiguration.oAuthRedirectUri
import com.unblu.brandeableagentapp.data.AppConfiguration.oAuthTokenEndpoint
import com.unblu.brandeableagentapp.model.AuthenticationType
import com.unblu.brandeableagentapp.model.TokenEvent
import io.reactivex.rxjava3.annotations.NonNull
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import net.openid.appauth.*
import net.openid.appauth.AuthorizationException.GeneralErrors
import net.openid.appauth.AuthorizationService.TokenResponseCallback
/**
* *This class can be deleted in case the selected [AuthenticationType] is not [AuthenticationType.OAuth].
*
* Controller for login/authentication through OAuth
*
* @property application Context
* @property storage UnbluPreferencesStorage
* @property authState AuthState?
* @property authService AuthorizationService
* @property _eventReceived MutableSharedFlow<TokenEvent>
* @property eventReceived SharedFlow<TokenEvent>
* @property tokenResponseCallback TokenResponseCallback
* @constructor
*/
class OpenIdAuthController(var application: AgentApplication) {
private var authState: AuthState? = null
private val authService: AuthorizationService
private val _eventReceived = MutableSharedFlow<TokenEvent>()
val eventReceived: SharedFlow<TokenEvent> = _eventReceived
init {
//retrieve auth state or create new instance if nothing on the storage
authState = getAuthState(application.getUnbluPrefs())
authService = AuthorizationService(application)
}
private val tokenResponseCallback: TokenResponseCallback =
TokenResponseCallback { response, ex ->
if (response != null) {
// Update the AuthState with the new token response
authState?.let { authState ->
authState.update(response, ex)
authState.accessToken?.let { accessToken ->
if (authState.isAuthorized) {
scheduleTokenRefresh(application, authState)
storeAuthState(authState, application.getUnbluPrefs())
// Handle successful token refresh here
CoroutineScope(Dispatchers.Default).launch {
Log.d(TAG, "accessToken: $accessToken")
_eventReceived.emit(TokenEvent.TokenReceived(accessToken))
}
Log.d(TAG, " token refreshed. Token: ${response.accessToken}")
} else {
Log.w(TAG, " token not refreshed: AuthState is not authorized")
}
}
}
} else {
// Handle failed token refresh here
Log.e(TAG, "Failed to refresh access token", ex)
CoroutineScope(Dispatchers.Default).launch {
_eventReceived.emit(
TokenEvent.ErrorReceived(
ex?.message ?: "Error retrieving oauth token "
)
)
}
}
}
fun startSignIn(
launcher: ActivityResultLauncher<Intent>
) {
if (shouldReAuth()) {
Log.d(TAG, "Authentication needed")
val authRequest = AuthorizationRequest.Builder(
oAuthConfiguration,
oAuthClientId,
ResponseTypeValues.CODE,
Uri.parse(oAuthRedirectUri)
)
.setScopes(listOf("openid", "email", "profile"))
.build();
val authIntent = authService.getAuthorizationRequestIntent(authRequest)
launcher.launch(authIntent)
} else {
Log.i(TAG, "Token still valid, will use it")
CoroutineScope(Dispatchers.Default).launch {
authState?.accessToken?.let {
_eventReceived.emit(TokenEvent.TokenReceived(it));
}
}
}
}
private fun shouldReAuth(): Boolean {
return authState?.accessTokenExpirationTime?.let { time -> time - System.currentTimeMillis() <= 0 }
?: true
}
fun handleActivityResult(resultCode: Int, @NonNull data: Intent?) {
if (resultCode == Activity.RESULT_OK) {
val authResponse = AuthorizationResponse.fromIntent(data!!)
val authException = AuthorizationException.fromIntent(data)
authState = AuthState(authResponse, authException)
if (authResponse != null) {
Log.d(TAG, "will request access token")
requestAccessToken(
authResponse,
authException
)
} else {
authException?.message?.let { message ->
Log.w(TAG, message)
}
CoroutineScope(Dispatchers.Default).launch {
_eventReceived.emit(TokenEvent.ErrorReceived(application.getString(R.string.login_aborted)))
}
}
} else {
Log.w(
TAG,
"Login process aborted. It is highly probable that the login page was terminated due to user interaction."
)
CoroutineScope(Dispatchers.Default).launch {
_eventReceived.emit(TokenEvent.ErrorReceived(application.getString(R.string.login_aborted)))
}
}
}
private fun requestAccessToken(
authResponse: AuthorizationResponse?,
authException: AuthorizationException?,
) {
if (authResponse != null) {
authService.performTokenRequest(
createTokenExchangeRequest(authResponse),
tokenResponseCallback
)
} else {
Log.e(TAG, "Authorization failed", authException)
tokenResponseCallback.onTokenRequestCompleted(null, authException)
}
}
private fun createTokenExchangeRequest(authResponse: AuthorizationResponse): TokenRequest {
return TokenRequest.Builder(
oAuthConfiguration,
oAuthClientId
).setGrantType(GrantTypeValues.AUTHORIZATION_CODE)
.setAuthorizationCode(authResponse.authorizationCode)
.setCodeVerifier(authResponse.request.codeVerifier)
.setNonce(authResponse.request.nonce)
.setRedirectUri(Uri.parse(oAuthRedirectUri))
.setScopes(listOf("openid", "email", "profile", "offline_access"))
.build()
}
fun refreshAccessToken(tokenRequest: TokenRequest) {
authState?.let { authState ->
if (authState.refreshToken == null) {
Log.e(TAG, "No refresh token available")
tokenResponseCallback.onTokenRequestCompleted(
null,
GeneralErrors.ID_TOKEN_VALIDATION_ERROR
)
return
}
authService.performTokenRequest(tokenRequest, tokenResponseCallback)
} ?: run {
Log.e(TAG, "No AuthState available, refresh failed")
}
}
companion object {
const val TAG = "OpenIdAuthController"
val oAuthConfiguration = AuthorizationServiceConfiguration(
Uri.parse(oAuthEndpoint),
Uri.parse(oAuthTokenEndpoint)
)
}
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/login/sso/OpenIdAuthController.kt
|
2372620267
|
package com.unblu.brandeableagentapp.login.sso
import com.unblu.brandeableagentapp.model.AuthenticationType
import com.unblu.sdk.core.configuration.UnbluPreferencesStorage
import net.openid.appauth.AuthState
import org.json.JSONException
const val AUTH_STATE = "auth_state"
/**
* This file can be deleted in case the selected [AuthenticationType] is not [AuthenticationType.OAuth].
* @param unbluPreferencesStorage UnbluPreferencesStorage
* @return AuthState
*/
fun getAuthState(unbluPreferencesStorage: UnbluPreferencesStorage) : AuthState {
return when(val stateData = unbluPreferencesStorage.get(AUTH_STATE)){
null -> AuthState()
"" -> AuthState()
else-> try {
AuthState.jsonDeserialize(stateData)
} catch (e: JSONException) {
AuthState()
}
}
}
fun storeAuthState(authState: AuthState, storage: UnbluPreferencesStorage){
storage.put(AUTH_STATE, authState.jsonSerializeString())
}
fun deleteAuthState(storage: UnbluPreferencesStorage){
storage.put(AUTH_STATE, "")
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/login/sso/AuthStateHelper.kt
|
2651619556
|
package com.unblu.brandeableagentapp.login.sso
import android.content.Context
import android.util.Log
import androidx.work.*
import com.unblu.brandeableagentapp.AgentApplication
import com.unblu.brandeableagentapp.data.AppConfiguration
import com.unblu.brandeableagentapp.login.sso.TokenRefreshWorker.Companion.TOKEN_REQUEST
import com.unblu.brandeableagentapp.model.AuthenticationType
import net.openid.appauth.AuthState
import net.openid.appauth.GrantTypeValues
import net.openid.appauth.TokenRequest
import java.util.concurrent.TimeUnit
/**
* This class can be deleted in case the selected [AuthenticationType] is not [AuthenticationType.OAuth].
*
* This worker is responsible for mantaining the refresh cycle for the authentication worker.
*
* @property workerParams WorkerParameters
* @constructor
*/
class TokenRefreshWorker(context: Context, workerParams: WorkerParameters) :
Worker(context, workerParams) {
companion object {
const val TAG = "TokenRefreshWorker"
const val TOKEN_REQUEST = "token_request"
}
private var workerParams: WorkerParameters
init {
this.workerParams = workerParams
}
override fun doWork(): Result {
val application = applicationContext as AgentApplication
// Retrieve the stored RefreshRequest
val tokenRequest: TokenRequest = workerParams.inputData.getString(TOKEN_REQUEST)
?.let { data -> TokenRequest.jsonDeserialize(data) }
?: kotlin.run { return Result.failure() }
// Refresh the access token
val appAuthController = OpenIdAuthController(application)
appAuthController.refreshAccessToken(tokenRequest)
return Result.success()
}
}
fun scheduleTokenRefresh(context: Context, authState: AuthState) {
if (authState.accessTokenExpirationTime != null) {
val expiresIn: Long = authState.accessTokenExpirationTime!! - System.currentTimeMillis()
printTimeInMinutes(expiresIn)
if (expiresIn > 0) {
val tokenRefreshWorkRequest = OneTimeWorkRequest.Builder(
TokenRefreshWorker::class.java
)
.setInitialDelay(expiresIn, TimeUnit.MILLISECONDS)
.setInputData(
Data.Builder()
.putString(TOKEN_REQUEST, createTokenRequest(authState))
.build()
)
.build()
WorkManager.getInstance(context)
.enqueueUniqueWork(
"tokenRefreshWork",
ExistingWorkPolicy.REPLACE,
tokenRefreshWorkRequest
)
}
}
}
fun createTokenRequest(authState: AuthState): String {
return TokenRequest.Builder(
OpenIdAuthController.oAuthConfiguration,
AppConfiguration.oAuthClientId
)
.setGrantType(GrantTypeValues.REFRESH_TOKEN)
.setRefreshToken(authState.refreshToken)
.setScopes(listOf("openid", "email", "profile", "offline_access"))
.build()
.jsonSerializeString()
}
fun printTimeInMinutes(timeInMillis: Long) {
val minutes = timeInMillis / 60000 // Convert milliseconds to minutes
Log.i(TokenRefreshWorker.TAG, "Will refresh in: $minutes")
}
|
android-brandable-agent-app/app/src/main/java/com/unblu/brandeableagentapp/login/sso/TokenRefreshWorker.kt
|
1973186514
|
package com.example.productivityapp
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.productivityapp", appContext.packageName)
}
}
|
ProductivityApp/app/src/androidTest/java/com/example/productivityapp/ExampleInstrumentedTest.kt
|
591621801
|
package com.example.productivityapp
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
ProductivityApp/app/src/test/java/com/example/productivityapp/ExampleUnitTest.kt
|
278412240
|
package com.example.productivityapp.ui.theme
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF4B35FF)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFE3DFFF)
val md_theme_light_onPrimaryContainer = Color(0xFF110068)
val md_theme_light_secondary = Color(0xFF764B9B)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFF1DAFF)
val md_theme_light_onSecondaryContainer = Color(0xFF2D004F)
val md_theme_light_tertiary = Color(0xFF86458B)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFFFD6FB)
val md_theme_light_onTertiaryContainer = Color(0xFF36003D)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFFFBFF)
val md_theme_light_onBackground = Color(0xFF1C1B1F)
val md_theme_light_surface = Color(0xFFFFFBFF)
val md_theme_light_onSurface = Color(0xFF1C1B1F)
val md_theme_light_surfaceVariant = Color(0xFFE4E1EC)
val md_theme_light_onSurfaceVariant = Color(0xFF47464F)
val md_theme_light_outline = Color(0xFF787680)
val md_theme_light_inverseOnSurface = Color(0xFFF3EFF4)
val md_theme_light_inverseSurface = Color(0xFF313034)
val md_theme_light_inversePrimary = Color(0xFFC4C0FF)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF4B35FF)
val md_theme_light_outlineVariant = Color(0xFFC8C5D0)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFFC4C0FF)
val md_theme_dark_onPrimary = Color(0xFF2000A4)
val md_theme_dark_primaryContainer = Color(0xFF3100E4)
val md_theme_dark_onPrimaryContainer = Color(0xFFE3DFFF)
val md_theme_dark_secondary = Color(0xFFDFB7FF)
val md_theme_dark_onSecondary = Color(0xFF451969)
val md_theme_dark_secondaryContainer = Color(0xFF5D3282)
val md_theme_dark_onSecondaryContainer = Color(0xFFF1DAFF)
val md_theme_dark_tertiary = Color(0xFFF9ACFA)
val md_theme_dark_onTertiary = Color(0xFF521459)
val md_theme_dark_tertiaryContainer = Color(0xFF6C2D71)
val md_theme_dark_onTertiaryContainer = Color(0xFFFFD6FB)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF1C1B1F)
val md_theme_dark_onBackground = Color(0xFFE5E1E6)
val md_theme_dark_surface = Color(0xFF1C1B1F)
val md_theme_dark_onSurface = Color(0xFFE5E1E6)
val md_theme_dark_surfaceVariant = Color(0xFF47464F)
val md_theme_dark_onSurfaceVariant = Color(0xFFC8C5D0)
val md_theme_dark_outline = Color(0xFF928F9A)
val md_theme_dark_inverseOnSurface = Color(0xFF1C1B1F)
val md_theme_dark_inverseSurface = Color(0xFFE5E1E6)
val md_theme_dark_inversePrimary = Color(0xFF4B35FF)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFFC4C0FF)
val md_theme_dark_outlineVariant = Color(0xFF47464F)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFF4B35FF)
|
ProductivityApp/app/src/main/java/com/example/productivityapp/ui/theme/Color.kt
|
2272773727
|
package com.example.productivityapp.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.runtime.Composable
private val LightColors = lightColorScheme(
primary = md_theme_light_primary,
onPrimary = md_theme_light_onPrimary,
primaryContainer = md_theme_light_primaryContainer,
onPrimaryContainer = md_theme_light_onPrimaryContainer,
secondary = md_theme_light_secondary,
onSecondary = md_theme_light_onSecondary,
secondaryContainer = md_theme_light_secondaryContainer,
onSecondaryContainer = md_theme_light_onSecondaryContainer,
tertiary = md_theme_light_tertiary,
onTertiary = md_theme_light_onTertiary,
tertiaryContainer = md_theme_light_tertiaryContainer,
onTertiaryContainer = md_theme_light_onTertiaryContainer,
error = md_theme_light_error,
errorContainer = md_theme_light_errorContainer,
onError = md_theme_light_onError,
onErrorContainer = md_theme_light_onErrorContainer,
background = md_theme_light_background,
onBackground = md_theme_light_onBackground,
surface = md_theme_light_surface,
onSurface = md_theme_light_onSurface,
surfaceVariant = md_theme_light_surfaceVariant,
onSurfaceVariant = md_theme_light_onSurfaceVariant,
outline = md_theme_light_outline,
inverseOnSurface = md_theme_light_inverseOnSurface,
inverseSurface = md_theme_light_inverseSurface,
inversePrimary = md_theme_light_inversePrimary,
surfaceTint = md_theme_light_surfaceTint,
outlineVariant = md_theme_light_outlineVariant,
scrim = md_theme_light_scrim,
)
private val DarkColors = darkColorScheme(
primary = md_theme_dark_primary,
onPrimary = md_theme_dark_onPrimary,
primaryContainer = md_theme_dark_primaryContainer,
onPrimaryContainer = md_theme_dark_onPrimaryContainer,
secondary = md_theme_dark_secondary,
onSecondary = md_theme_dark_onSecondary,
secondaryContainer = md_theme_dark_secondaryContainer,
onSecondaryContainer = md_theme_dark_onSecondaryContainer,
tertiary = md_theme_dark_tertiary,
onTertiary = md_theme_dark_onTertiary,
tertiaryContainer = md_theme_dark_tertiaryContainer,
onTertiaryContainer = md_theme_dark_onTertiaryContainer,
error = md_theme_dark_error,
errorContainer = md_theme_dark_errorContainer,
onError = md_theme_dark_onError,
onErrorContainer = md_theme_dark_onErrorContainer,
background = md_theme_dark_background,
onBackground = md_theme_dark_onBackground,
surface = md_theme_dark_surface,
onSurface = md_theme_dark_onSurface,
surfaceVariant = md_theme_dark_surfaceVariant,
onSurfaceVariant = md_theme_dark_onSurfaceVariant,
outline = md_theme_dark_outline,
inverseOnSurface = md_theme_dark_inverseOnSurface,
inverseSurface = md_theme_dark_inverseSurface,
inversePrimary = md_theme_dark_inversePrimary,
surfaceTint = md_theme_dark_surfaceTint,
outlineVariant = md_theme_dark_outlineVariant,
scrim = md_theme_dark_scrim,
)
@Composable
fun ProductivityAppTheme(
useDarkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable() () -> Unit
) {
val colors = if (!useDarkTheme) {
LightColors
} else {
DarkColors
}
MaterialTheme(
colorScheme = colors,
content = content
)
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/ui/theme/Theme.kt
|
2773030550
|
package com.example.productivityapp.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Set of Material typography styles to start with
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
/* Other default text styles to override
titleLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
labelSmall = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Medium,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
*/
)
|
ProductivityApp/app/src/main/java/com/example/productivityapp/ui/theme/Type.kt
|
195202625
|
package com.example.productivityapp.core
class Madara {
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/core/Madara.kt
|
292788090
|
package com.example.productivityapp.core.presentation
class hashirama {
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/core/presentation/hashirama.kt
|
451188197
|
package com.example.productivityapp.feature_todo.data.di
import android.content.Context
import androidx.room.Room
import com.example.productivityapp.feature_todo.data.local.TodoDao
import com.example.productivityapp.feature_todo.data.local.TodoDatabase
import com.example.productivityapp.feature_todo.data.remote.TodoApi
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object TodoModule {
@Provides
fun providesRetrofitApi(retrofit: Retrofit): TodoApi{
return retrofit.create(TodoApi::class.java)
}
@Singleton
@Provides
fun providesRetrofit(): Retrofit{
return Retrofit.Builder()
.addConverterFactory(
GsonConverterFactory.create()
).baseUrl("https://todo-7d5e2-default-rtdb.firebaseio.com/todo")
.build()
}
@Provides
fun providesRoomDao(database: TodoDatabase): TodoDao {
return database.dao
}
@Singleton
@Provides
fun providesRoomDb(
@ApplicationContext appContext: Context
): TodoDatabase{
return Room.databaseBuilder(
appContext.applicationContext,
TodoDatabase::class.java,
"todo_database"
).fallbackToDestructiveMigration().build()
}
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/data/di/TodoModule.kt
|
2659974404
|
package com.example.productivityapp.feature_todo.data.mapper
import com.example.productivityapp.feature_todo.data.local.dto.LocalTodoItem
import com.example.productivityapp.feature_todo.data.remote.dto.RemoteTodoItem
import com.example.productivityapp.feature_todo.domain.model.TodoItem
fun TodoItem.toLocalTodoItem(): LocalTodoItem{
return LocalTodoItem(
title = title,
description = description,
timestamp = timestamp,
completed = completed,
archived = archived,
id = id
)
}
fun TodoItem.toRemoteTodoItem(): RemoteTodoItem {
return RemoteTodoItem(
title = title,
description = description,
timestamp = timestamp,
completed = completed,
archived = archived,
id = id
)
}
fun LocalTodoItem.toTodoItem(): TodoItem{
return TodoItem(
title = title,
description = description,
timestamp = timestamp,
completed = completed,
archived = archived,
id = id
)
}
fun LocalTodoItem.toRemoteTodoItem(): RemoteTodoItem{
return RemoteTodoItem(
title = title,
description = description,
timestamp = timestamp,
completed = completed,
archived = archived,
id = id
)
}
fun RemoteTodoItem.toTodoItem(): TodoItem{
return TodoItem(
title = title,
description = description,
timestamp = timestamp,
completed = completed,
archived = archived,
id = id
)
}
fun RemoteTodoItem.toLocalTodoItem(): LocalTodoItem{
return LocalTodoItem(
title = title,
description = description,
timestamp = timestamp,
completed = completed,
archived = archived,
id = id
)
}
fun List<TodoItem>.toLocalTodoItemList(): List<LocalTodoItem>{
return this.map {todo->
LocalTodoItem(
title = todo.title,
description = todo.description,
timestamp = todo.timestamp,
completed = todo.completed,
archived = todo.archived,
id = todo.id
)
}
}
fun List<TodoItem>.toRemoteTodoItemList(): List<RemoteTodoItem>{
return this.map {todo->
RemoteTodoItem(
title = todo.title,
description = todo.description,
timestamp = todo.timestamp,
completed = todo.completed,
archived = todo.archived,
id = todo.id
)
}
}
fun List<LocalTodoItem>.toTodoItemListFromLocal(): List<TodoItem>{
return this.map {todo->
TodoItem(
title = todo.title,
description = todo.description,
timestamp = todo.timestamp,
completed = todo.completed,
archived = todo.archived,
id = todo.id
)
}
}
fun List<LocalTodoItem>.toRemoteTodoItemListFromLocal(): List<RemoteTodoItem>{
return this.map {todo->
RemoteTodoItem(
title = todo.title,
description = todo.description,
timestamp = todo.timestamp,
completed = todo.completed,
archived = todo.archived,
id = todo.id
)
}
}
fun List<RemoteTodoItem>.toTodoItemListFromRemote(): List<TodoItem>{
return this.map {todo->
TodoItem(
title = todo.title,
description = todo.description,
timestamp = todo.timestamp,
completed = todo.completed,
archived = todo.archived,
id = todo.id
)
}
}
fun List<RemoteTodoItem>.toLocalTodoItemListFromRemote(): List<LocalTodoItem>{
return this.map {todo->
LocalTodoItem(
title = todo.title,
description = todo.description,
timestamp = todo.timestamp,
completed = todo.completed,
archived = todo.archived,
id = todo.id
)
}
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/data/mapper/TodoMapper.kt
|
2438352333
|
package com.example.productivityapp.feature_todo.data.local.dto
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "todo")
data class LocalTodoItem(
val title: String,
val description: String,
val timestamp: Long,
val completed: Boolean,
val archived: Boolean,
@PrimaryKey(autoGenerate = true)
val id: Int?
)
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/data/local/dto/LocalTodoItem.kt
|
2003597347
|
package com.example.productivityapp.feature_todo.data.local
class Naruto {
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/data/local/Naruto.kt
|
49004211
|
package com.example.productivityapp.feature_todo.data.local
import androidx.room.Database
import androidx.room.RoomDatabase
import com.example.productivityapp.feature_todo.data.local.dto.LocalTodoItem
@Database(
entities = [LocalTodoItem::class],
version = 1,
exportSchema =false
)
abstract class TodoDatabase: RoomDatabase() {
abstract val dao: TodoDao
companion object{
const val DATABASE_NAME = "todo_db"
}
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/data/local/TodoDatabase.kt
|
1754626700
|
package com.example.productivityapp.feature_todo.data.local
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.productivityapp.feature_todo.data.local.dto.LocalTodoItem
@Dao
interface TodoDao {
@Query("SELECT * FROM todo")
fun getAllTodoItems(): List<LocalTodoItem>
@Query("SELECT * FROM todo WHERE id = :id")
suspend fun getSingleTodoItemById(id: Int): LocalTodoItem?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun addAllTodoItems(todos: List<LocalTodoItem>)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun addTodoItem(todo: LocalTodoItem): Long
@Delete
suspend fun deleteTodoItem(todo: LocalTodoItem)
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/data/local/TodoDao.kt
|
2003686509
|
package com.example.productivityapp.feature_todo.data.remote.dto
import com.google.gson.annotations.SerializedName
data class RemoteTodoItem(
@SerializedName("Title")
val title: String,
@SerializedName("Description")
val description: String,
@SerializedName("Timestamp")
val timestamp: Long,
@SerializedName("Completed")
val completed: Boolean,
@SerializedName("Archived")
val archived: Boolean,
@SerializedName("ID")
val id: Int?
)
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/data/remote/dto/RemoteTodoItem.kt
|
3089886933
|
package com.example.productivityapp.feature_todo.data.remote
class Saske {
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/data/remote/Saske.kt
|
1827341538
|
package com.example.productivityapp.feature_todo.data.remote
import com.example.productivityapp.feature_todo.data.remote.dto.RemoteTodoItem
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Path
import retrofit2.http.Query
import retrofit2.http.Url
interface TodoApi {
@GET("todo.json")
suspend fun getAllTodos(): List<RemoteTodoItem>
@GET("todo.json?orderBy=\"ID\"")
suspend fun getSingleTodoById(@Query("equalTo") id: Int?): Map<String, RemoteTodoItem>
//@POST("todo.json")
//suspend fun addTodo(@Body url: String, @Body updatedTodo: RemoteTodoItem): Response<Unit>
@PUT
suspend fun addTodo(@Url url: String,@Body updatedTodo: RemoteTodoItem): Response<Unit>
@DELETE("todo/{id}.json")
suspend fun deleteToDO(@Path("id") id: Int?): Response<Unit>
@PUT("todo/{id}.json")
suspend fun updateTodoItem(@Path("id") id: Int?, @Body todoItem: RemoteTodoItem): Response<Unit>
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/data/remote/TodoApi.kt
|
248791220
|
package com.example.productivityapp.feature_todo.domain.util
class InvalidTodoItemException(message: String) : Exception(message)
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/domain/util/InvalidTodoItemException.kt
|
210756482
|
package com.example.productivityapp.feature_todo.domain
class Sakura {
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/domain/Sakura.kt
|
1415307749
|
package com.example.productivityapp.feature_todo.domain.model
data class TodoItem(
val title: String,
val description: String,
val timestamp: Long,
val completed: Boolean,
val archived: Boolean,
val id: Int?
)
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/domain/model/TodoItem.kt
|
2903650501
|
package com.example.productivityapp.feature_todo.presentation
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.example.productivityapp.ui.theme.ProductivityAppTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ProductivityAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
}
}
}
}
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/presentation/MainActivity.kt
|
1339380577
|
package com.example.productivityapp.feature_todo.presentation.todo_list
class Itachi {
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/presentation/todo_list/Itachi.kt
|
3603885088
|
package com.example.productivityapp.feature_todo.presentation.todo_new_update
class Shisui {
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/presentation/todo_new_update/Shisui.kt
|
77041650
|
package com.example.productivityapp.feature_todo.presentation
class Kakashi {
}
|
ProductivityApp/app/src/main/java/com/example/productivityapp/feature_todo/presentation/Kakashi.kt
|
853708528
|
package com.example.homework16
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.homework16", appContext.packageName)
}
}
|
SuperHeroesList/app/src/androidTest/java/com/example/homework16/ExampleInstrumentedTest.kt
|
4257897866
|
package com.example.homework16
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
SuperHeroesList/app/src/test/java/com/example/homework16/ExampleUnitTest.kt
|
3409177821
|
package com.example.homework16
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.WindowManager
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
val recyclerView: RecyclerView = findViewById(R.id.recyclerView)
val apiClient = ApiClient.client.create(ApiInterface::class.java)
apiClient.getSuperheroes()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
if (it.isNotEmpty()) {
val items = it
val myAdapter = RecyclerViewAdapter(items as MutableList<Hero>) {
Toast.makeText(this, "${it} clicked", Toast.LENGTH_SHORT).show()
}
recyclerView.adapter = myAdapter
}
}, {
Toast.makeText(this, "Fetch error ${it.message}", Toast.LENGTH_LONG).show()
})
recyclerView.layoutManager = LinearLayoutManager(this)
}
}
|
SuperHeroesList/app/src/main/java/com/example/homework16/MainActivity.kt
|
2353646021
|
package com.example.homework16
import io.reactivex.Single
import retrofit2.http.GET
interface ApiInterface {
@GET("/superhero-api/api/all.json")
fun getSuperheroes():Single<List<Hero>>
}
|
SuperHeroesList/app/src/main/java/com/example/homework16/ApiInterface.kt
|
4143801644
|
package com.example.homework16
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import com.bumptech.glide.Glide
class RecyclerViewAdapter(val items: MutableList<Hero>, val onClick: (String) -> Unit) :
Adapter<RecycleViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecycleViewHolder {
val listItemView = LayoutInflater.from(parent.context)
.inflate(R.layout.list_item_layout, parent, false)
return RecycleViewHolder(listItemView)
}
override fun getItemCount(): Int = items.count()
override fun onBindViewHolder(holder: RecycleViewHolder, position: Int) {
holder.name.text = items[position].name
Glide.with(holder.itemView.context)
.load(items[position].images.lg)
.into(holder.image)
"Name: ${items[position].biography.fullName}".also { holder.fullName.text = it }
"Birth place: ${items[position].biography.placeOfBirth}".also {
holder.placeOfBirth.text = it
}
"Aliases: ${items[position].biography.aliases}".also { holder.aliases.text = it }
"Publisher: ${items[position].biography.publisher}".also { holder.publisher.text = it }
"Gender: ${items[position].appearance.gender}".also { holder.gender.text = it }
"Race: ${items[position].appearance.race}".also { holder.race.text = it }
"Height: ${items[position].appearance.height[1]}".also { holder.height.text = it }
"Weight: ${items[position].appearance.weight[1]}".also { holder.weight.text = it }
"Intelligence: ${items[position].powerstats.intelligence}".also {
holder.intelligence.text = it
}
"Strength: ${items[position].powerstats.strength}".also { holder.strength.text = it }
"Speed: ${items[position].powerstats.speed}".also { holder.speed.text = it }
"Durability: ${items[position].powerstats.durability}".also { holder.durability.text = it }
"Power: ${items[position].powerstats.power}".also { holder.power.text = it }
"Combat: ${items[position].powerstats.combat}".also { holder.combat.text = it }
holder.itemView.setOnClickListener {
onClick(items[position].name)
}
}
}
class RecycleViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val name: TextView = itemView.findViewById(R.id.heroName)
val image: ImageView = itemView.findViewById(R.id.photo)
val fullName: TextView = itemView.findViewById(R.id.fullName)
val placeOfBirth: TextView = itemView.findViewById(R.id.placeOfBirth)
val aliases: TextView = itemView.findViewById(R.id.aliases)
val publisher: TextView = itemView.findViewById(R.id.publisher)
val gender: TextView = itemView.findViewById(R.id.gender)
val race: TextView = itemView.findViewById(R.id.race)
val height: TextView = itemView.findViewById(R.id.height)
val weight: TextView = itemView.findViewById(R.id.weight)
val intelligence: TextView = itemView.findViewById(R.id.intelligence)
val strength: TextView = itemView.findViewById(R.id.strength)
val speed: TextView = itemView.findViewById(R.id.speed)
val durability: TextView = itemView.findViewById(R.id.durability)
val power: TextView = itemView.findViewById(R.id.power)
val combat: TextView = itemView.findViewById(R.id.combat)
}
|
SuperHeroesList/app/src/main/java/com/example/homework16/RecyclerViewAdapter.kt
|
2337091932
|
package com.example.homework16
import com.google.gson.annotations.SerializedName
data class ApiResponse(val heroes: List<Hero>)
data class Hero(
@SerializedName("id") var id: Int,
@SerializedName("name") var name: String,
@SerializedName("slug") var slug: String,
@SerializedName("powerstats") var powerstats: Powerstats,
@SerializedName("appearance") var appearance: Appearance,
@SerializedName("biography") var biography: Biography,
@SerializedName("work") var work: Work,
@SerializedName("connections") var connections: Connections,
@SerializedName("images") var images: Images
)
data class Powerstats(
@SerializedName("intelligence") var intelligence: String,
@SerializedName("strength") var strength: String,
@SerializedName("speed") var speed: String,
@SerializedName("durability") var durability: String,
@SerializedName("power") var power: String,
@SerializedName("combat") var combat: String
)
data class Appearance(
@SerializedName("gender") var gender: String,
@SerializedName("race") var race: String,
@SerializedName("height") var height: ArrayList<String>,
@SerializedName("weight") var weight: ArrayList<String>,
@SerializedName("eyeColor") var eyeColor: String,
@SerializedName("hairColor") var hairColor: String
)
data class Biography(
@SerializedName("fullName") var fullName: String,
@SerializedName("alterEgos") var alterEgos: String,
@SerializedName("aliases") var aliases: ArrayList<String>,
@SerializedName("placeOfBirth") var placeOfBirth: String,
@SerializedName("firstAppearance") var firstAppearance: String,
@SerializedName("publisher") var publisher: String,
@SerializedName("alignment") var alignment: String
)
data class Work(
@SerializedName("occupation") var occupation: String,
@SerializedName("base") var base: String
)
data class Connections(
@SerializedName("groupAffiliation") var groupAffiliation: String,
@SerializedName("relatives") var relatives: String
)
data class Images(
@SerializedName("xs") var xs: String,
@SerializedName("sm") var sm: String,
@SerializedName("md") var md: String,
@SerializedName("lg") var lg: String
)
|
SuperHeroesList/app/src/main/java/com/example/homework16/ApiResponse.kt
|
3945471854
|
package com.example.homework16
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
class ApiClient {
companion object{
val client = Retrofit.Builder()
.baseUrl("https://akabab.github.io")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(OkHttpClient.Builder().build())
.build()
}
}
|
SuperHeroesList/app/src/main/java/com/example/homework16/ApiClient.kt
|
1902497853
|
package com.example.komik
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.komik", appContext.packageName)
}
}
|
Komik/app/src/androidTest/java/com/example/komik/ExampleInstrumentedTest.kt
|
253582516
|
package com.example.komik
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
Komik/app/src/test/java/com/example/komik/ExampleUnitTest.kt
|
1000689097
|
package com.example.komik
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.TextView
class DetailActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_detail)
// Ini Terima data dari intent
val selectedHero = intent.getParcelableExtra<Hero>("selectedHero")
// Ini Tampilkan data di UI
val tvName: TextView = findViewById(R.id.nama_komik)
val tvDescription: TextView = findViewById(R.id.desc_komik)
val imgPhoto: ImageView = findViewById(R.id.foto)
tvName.text = selectedHero?.name
tvDescription.text = selectedHero?.description
imgPhoto.setImageResource(selectedHero?.photo ?: 0)
supportActionBar?.title = selectedHero?.name ?: getString(R.string.detail_title)
}
}
|
Komik/app/src/main/java/com/example/komik/DetailActivity.kt
|
3695470860
|
package com.example.komik
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
private lateinit var dasar: RecyclerView
private val list = ArrayList<Hero>()
private fun showSelectedHero(hero: Hero) {
Toast.makeText(this, "Kamu memilih " + hero.name, Toast.LENGTH_SHORT).show()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
dasar = findViewById(R.id.dasar)
dasar.setHasFixedSize(true)
list.addAll(getListHeroes())
showRecyclerList()
}
private fun getListHeroes(): ArrayList<Hero> {
val dataName = resources.getStringArray(R.array.data_name)
val dataDescription = resources.getStringArray(R.array.data_description)
val dataPhoto = resources.obtainTypedArray(R.array.data_photo)
val listHero = ArrayList<Hero>()
for (i in dataName.indices) {
val hero = Hero(dataName[i], dataDescription[i], dataPhoto.getResourceId(i, -1))
listHero.add(hero)
}
return listHero
}
private fun showRecyclerList() {
dasar.layoutManager = LinearLayoutManager(this)
val listHeroAdapter = ListKomikAdapter(list)
dasar.adapter = listHeroAdapter
listHeroAdapter.setOnItemClickCallback(object : ListKomikAdapter.OnItemClickCallback {
override fun onItemClicked(data: Hero) {
val intent = Intent(this@MainActivity, DetailActivity::class.java)
intent.putExtra("selectedHero", data)
startActivity(intent)
}
})
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_list -> {
dasar.layoutManager = LinearLayoutManager(this)
}
R.id.action_grid -> {
dasar.layoutManager = GridLayoutManager(this, 2)
}
R.id.action_about -> {
startActivity(Intent(this@MainActivity, AboutActivity::class.java))
}
}
return super.onOptionsItemSelected(item)
}
}
|
Komik/app/src/main/java/com/example/komik/MainActivity.kt
|
1207525984
|
package com.example.komik
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class AboutActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about)
supportActionBar?.title = getString(R.string.detail_about)
}
}
|
Komik/app/src/main/java/com/example/komik/AboutActivity.kt
|
4106639354
|
package com.example.komik
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
data class Hero(
val name: String,
val description: String,
val photo: Int
) : Parcelable
|
Komik/app/src/main/java/com/example/komik/Komik.kt
|
896036559
|
package com.example.komik
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class ListKomikAdapter (private val listHero: ArrayList<Hero>) : RecyclerView.Adapter<ListKomikAdapter.ListViewHolder>() {
private lateinit var onItemClickCallback: OnItemClickCallback
fun setOnItemClickCallback(onItemClickCallback: OnItemClickCallback) {
this.onItemClickCallback = onItemClickCallback
}
class ListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imgPhoto: ImageView = itemView.findViewById(R.id.img_item_photo)
val tvName: TextView = itemView.findViewById(R.id.tv_item_name)
val tvDescription: TextView = itemView.findViewById(R.id.tv_item_description)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ListViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(R.layout.item_row_dasar, parent, false)
return ListViewHolder(view)
}
override fun getItemCount()= listHero.size
override fun onBindViewHolder(holder: ListViewHolder, position: Int) {
val (name, description, photo) = listHero[position]
holder.imgPhoto.setImageResource(photo)
holder.tvName.text = name
holder.tvDescription.text = description
holder.itemView.setOnClickListener { onItemClickCallback.onItemClicked(listHero[holder.adapterPosition]) }
}
interface OnItemClickCallback {
fun onItemClicked(data: Hero)
}
}
|
Komik/app/src/main/java/com/example/komik/ListKomikAdapter.kt
|
2498069018
|
package com.example.komik
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.View
import androidx.appcompat.app.AppCompatActivity
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
val rootView = findViewById<View>(android.R.id.content)
rootView.postDelayed({
val intent = Intent(this@SplashActivity, MainActivity::class.java)
startActivity(intent)
finish()
}, 3000)
}
}
|
Komik/app/src/main/java/com/example/komik/SplashActivity.kt
|
3349852226
|
package com.app.mythirdapp
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.app.mythirdapp", appContext.packageName)
}
}
|
MyThirdApp/app/src/androidTest/java/com/app/mythirdapp/ExampleInstrumentedTest.kt
|
3667795969
|
package com.app.mythirdapp
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
MyThirdApp/app/src/test/java/com/app/mythirdapp/ExampleUnitTest.kt
|
2139671623
|
package com.app.mythirdapp
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
|
MyThirdApp/app/src/main/java/com/app/mythirdapp/MainActivity.kt
|
3454891878
|
package com.kotlin.lamelapharmacy
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.kotlin.lamelapharmacy", appContext.packageName)
}
}
|
Lamela_pharmacy/app/src/androidTest/java/com/kotlin/lamelapharmacy/ExampleInstrumentedTest.kt
|
4148724665
|
package com.kotlin.lamelapharmacy
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
Lamela_pharmacy/app/src/test/java/com/kotlin/lamelapharmacy/ExampleUnitTest.kt
|
164079397
|
package com.kotlin.lamelapharmacy
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class Make_an_order: Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_make_an_order, container, false)
val medicineNameEditText: EditText = view.findViewById(R.id.medicineNameEditText)
val quantityEditText: EditText = view.findViewById(R.id.quantityEditText)
val prescriptionEditText: EditText = view.findViewById(R.id.prescriptionEditText)
val submitOrderButton: Button = view.findViewById(R.id.submitOrderButton)
submitOrderButton.setOnClickListener {
// Retrieve user input
val medicineName = medicineNameEditText.text.toString()
val quantity = quantityEditText.text.toString()
val prescription = prescriptionEditText.text.toString()
// Validate and submit the order
if (medicineName.isNotEmpty() && quantity.isNotEmpty()) {
// TODO: Implement order submission logic here
// You can send the order details to a server or perform other actions
// For now, display a simple confirmation message
val message = "Order received!\nMedicine: $medicineName\nQuantity: $quantity\nPrescription: $prescription"
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(requireContext(), "Please fill in all required fields", Toast.LENGTH_SHORT).show()
}
}
return view
}
}
|
Lamela_pharmacy/app/src/main/java/com/kotlin/lamelapharmacy/Make_an_order.kt
|
45990473
|
package com.kotlin.lamelapharmacy
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.Fragment
class More_about_drugs: Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_more_about_drugs, container, false)
}
@SuppressLint("SetJavaScriptEnabled")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val web_drugs:WebView = view.findViewById(R.id.web_drugs)
web_drugs.webViewClient = object : WebViewClient(){
@Deprecated("Deprecated in Java")
override fun shouldOverrideUrlLoading(
view: WebView?,
url:String
): Boolean {
view?.loadUrl(url)
return true
}
}
web_drugs.loadUrl("https://www.drugs.com/drug_information.html")
web_drugs.settings.javaScriptEnabled = true
web_drugs.settings.allowContentAccess = true
web_drugs.settings.useWideViewPort = true
web_drugs.settings.domStorageEnabled
}
}
|
Lamela_pharmacy/app/src/main/java/com/kotlin/lamelapharmacy/More_about_drugs.kt
|
2670590039
|
package com.kotlin.lamelapharmacy
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.drawerlayout.widget.DrawerLayout
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.navigation.NavigationView
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.kotlin.lamelapharmacy.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var auth:FirebaseAuth
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding:ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
auth = Firebase.auth
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.appBarMain.toolbar)
val drawerLayout: DrawerLayout = binding.drawerLayout
val navView: NavigationView = binding.navView
val navController = findNavController(R.id.nav_host_fragment_content_main)
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
appBarConfiguration = AppBarConfiguration(
setOf(
R.id.home,R.id.contact,R.id.about_Us,R.id.info,R.id.order,R.id.meet,R.id.drug
), drawerLayout
)
setupActionBarWithNavController(navController, appBarConfiguration)
navView.setupWithNavController(navController)
NavigationUI.setupWithNavController(binding.appBarMain.bottomNav,navController)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.settings){
Firebase.auth.signOut()
startActivity(Intent(this,Login::class.java))
}
return super.onOptionsItemSelected(item)
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment_content_main)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
}
|
Lamela_pharmacy/app/src/main/java/com/kotlin/lamelapharmacy/MainActivity.kt
|
2965387859
|
package com.kotlin.lamelapharmacy
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.google.firebase.auth.FirebaseAuth
class MainActivity2 : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
// ...
// Initialize Firebase Auth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTheme(R.style.Theme_LamelaPharmacy)
setContentView(R.layout.activity_main2)
}
fun Click(view: View) {
val intent = Intent(this,Login::class.java)
startActivity(intent)
finish()
}
}
|
Lamela_pharmacy/app/src/main/java/com/kotlin/lamelapharmacy/MainActivity2.kt
|
2106943944
|
package com.kotlin.lamelapharmacy
import android.os.Bundle
import android.text.method.TextKeyListener.clear
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Spinner
import android.widget.Toast
class Disease_Information : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_disease__information, container, false)
val firstNameEditText:EditText = view.findViewById(R.id.txtFname)
val secondNameEditText:EditText = view.findViewById(R.id.txtSname)
val dobEditText:EditText = view.findViewById(R.id.txtDob)
val ageEditText:EditText = view.findViewById(R.id.txtage)
val feelingEditText:EditText = view.findViewById(R.id.txtFeel)
val historyEditText:EditText = view.findViewById(R.id.txthistory)
val genderSpinner:Spinner = view.findViewById(R.id.gender)
val submitButton:Button = view.findViewById(R.id.submitButton)
submitButton.setOnClickListener {
// Retrieve user input
val firstName = firstNameEditText.text.toString()
val secondName = secondNameEditText.text.toString()
val gender = genderSpinner.selectedItem.toString()
val dob = dobEditText.text.toString()
val age = ageEditText.text.toString()
val feeling = feelingEditText.text.toString()
val history = historyEditText.text.toString()
// Perform any further processing or validation as needed
// Display a message
val sent =
"Sent successfully\nFirst Name: $firstName\nSecond Name: $secondName\nGender: $gender\nDob :$dob\nAge :$age\nFeeling :$feeling\nHistory :$history"
Toast.makeText(requireContext(), sent, Toast.LENGTH_SHORT).show()
}
return view
}
}
|
Lamela_pharmacy/app/src/main/java/com/kotlin/lamelapharmacy/Disease_Information.kt
|
2384652514
|
package com.kotlin.lamelapharmacy
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
class Splash : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
Handler().postDelayed({
val intent = Intent(this,Signup::class.java)
startActivity(intent)
finish()
},5000)
}
}
|
Lamela_pharmacy/app/src/main/java/com/kotlin/lamelapharmacy/Splash.kt
|
1217877773
|
package com.kotlin.lamelapharmacy
import android.app.Dialog
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.google.android.material.textfield.TextInputLayout
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class Login : AppCompatActivity() {
private lateinit var auth:FirebaseAuth
private lateinit var emailInput: EditText
private lateinit var emailcontainer: TextInputLayout
private lateinit var passwordInput: EditText
private lateinit var passwordcontainer: TextInputLayout
private lateinit var LoginButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
auth = Firebase.auth
emailInput = findViewById(R.id.loginemail)
emailcontainer = findViewById(R.id.loginemailcontainer)
passwordInput = findViewById(R.id.loginpassword)
passwordcontainer = findViewById(R.id.loginpasswordcontainer)
LoginButton = findViewById(R.id.loginbtn)
emailInput.addTextChangedListener(validateLogin)
passwordInput.addTextChangedListener(validateLogin)
LoginButton.setOnClickListener {
LoginButton.isEnabled = false
emailInput.isEnabled = false
passwordInput.isEnabled = false
val dialog = Dialog(this)
dialog.setContentView(R.layout.dialog_loading)
if (dialog.window != null){
dialog!!.window!!.setBackgroundDrawable(ColorDrawable(0))
}
dialog.show()
val email = emailInput.text.toString().trim()
val password = passwordInput.text.toString().trim()
auth.signInWithEmailAndPassword(email, password).addOnCompleteListener {
if (it.isSuccessful){
startActivity(Intent(this, MainActivity::class.java))
finish()
}else{
Toast.makeText(this, it.exception.toString(),Toast.LENGTH_LONG).show()
}
}
}
}
private val validateLogin = object : TextWatcher{
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
val emi = emailInput.text.toString().trim().lowercase()
val pass = passwordInput.text.toString().trim().lowercase()
fun validateEmail(): Boolean{
if (emi.isBlank()){
emailcontainer.isErrorEnabled = true
emailcontainer.error = "This field is required"
LoginButton.isEnabled = false
return false
}else{
emailcontainer.isErrorEnabled = false
LoginButton.isEnabled = true
return true
}
}
fun validatePassword(): Boolean{
if (pass.isBlank()){
passwordcontainer.isErrorEnabled = true
passwordcontainer.error = "incorrect password"
LoginButton.isEnabled = false
return false
}else{
passwordcontainer.isErrorEnabled = false
LoginButton.isEnabled = true
return true
}
}
LoginButton.isEnabled = validateEmail() && validatePassword()
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun afterTextChanged(p0: Editable?) {
}
}
fun Register(view: View) {
val intent = Intent(this,Signup::class.java)
startActivity(intent)
finish()
}
override fun onStart() {
super.onStart()
auth = Firebase.auth
val currentUser = auth.currentUser
if (currentUser != null){
startActivity(Intent(this,MainActivity::class.java))
finish()
}
}
}
|
Lamela_pharmacy/app/src/main/java/com/kotlin/lamelapharmacy/Login.kt
|
1925062305
|
package com.kotlin.lamelapharmacy
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
class About_Us : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_about__us, container, false)
val aboutTextView: TextView = view.findViewById(R.id.about)
aboutTextView.text = getString(R.string.about_pharmacy_description)
return view
}
}
|
Lamela_pharmacy/app/src/main/java/com/kotlin/lamelapharmacy/About_Us.kt
|
3264922724
|
package com.kotlin.lamelapharmacy
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.fragment.app.Fragment
class Home : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false)
}
@SuppressLint("SetJavaScriptEnabled")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val web_home:WebView = view.findViewById(R.id.web_home)
web_home.webViewClient = object : WebViewClient(){
@Deprecated("Deprecated in Java")
override fun shouldOverrideUrlLoading(
view: WebView?,
url:String
): Boolean {
view?.loadUrl(url)
return true
}
}
web_home.loadUrl("https://www.drugs.com")
web_home.settings.javaScriptEnabled = true
web_home.settings.allowContentAccess = true
web_home.settings.useWideViewPort = true
web_home.settings.domStorageEnabled
}
}
|
Lamela_pharmacy/app/src/main/java/com/kotlin/lamelapharmacy/Home.kt
|
593007589
|
package com.kotlin.lamelapharmacy
import android.app.Dialog
import android.content.Intent
import android.graphics.drawable.ColorDrawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import com.google.android.material.textfield.TextInputLayout
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
class Signup : AppCompatActivity() {
private lateinit var auth: FirebaseAuth
private lateinit var emailInput: EditText
private lateinit var emailcontainer: TextInputLayout
private lateinit var passwordInput: EditText
private lateinit var passwordcontainer: TextInputLayout
private lateinit var confirmpasswordInput: EditText
private lateinit var confirmcontainer: TextInputLayout
private lateinit var SignUpButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_signup )
auth = Firebase.auth
emailInput = findViewById(R.id.sign_upemail)
emailcontainer = findViewById(R.id.emailcontainer)
passwordInput = findViewById(R.id.sign_uppassword)
passwordcontainer = findViewById(R.id.passwordcontainer)
confirmpasswordInput = findViewById(R.id.sign_upconfirm)
confirmcontainer = findViewById(R.id.confirmcontainer)
SignUpButton = findViewById(R.id.signupbtn)
emailInput.addTextChangedListener(validateSignUp)
passwordInput.addTextChangedListener(validateSignUp)
confirmpasswordInput.addTextChangedListener(validateSignUp)
SignUpButton.setOnClickListener {
SignUpButton.isEnabled = false
emailInput.isEnabled = false
passwordInput.isEnabled = false
confirmpasswordInput.isEnabled = false
val dialog = Dialog(this,)
dialog.setContentView(R.layout.dialog_wait)
if (dialog.window != null){
dialog.window!!.setBackgroundDrawable(ColorDrawable(0))
}
dialog.show()
val email = emailInput.text.toString().trim()
val password = passwordInput.text.toString().trim()
auth.createUserWithEmailAndPassword(email, password).addOnCompleteListener {
if (it.isSuccessful){
startActivity(Intent(this,Login::class.java))
finish()
Toast.makeText(this,"Account created successful",Toast.LENGTH_LONG).show()
}else{
Toast.makeText(this, it.exception.toString(),Toast.LENGTH_LONG).show()
}
}
}
}
private val validateSignUp = object : TextWatcher{
override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
}
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
val emi1 = emailInput.text.toString().trim().lowercase()
val pass = passwordInput.text.toString().trim().lowercase()
val con = confirmpasswordInput.text.toString().trim().lowercase()
fun validateEmail(): Boolean{
if (emi1.isBlank()){
emailcontainer.isErrorEnabled = true
emailcontainer.error = "This field is required"
SignUpButton.isEnabled = false
return false
}else{
emailcontainer.isErrorEnabled = false
SignUpButton.isEnabled = true
return true
}
}
fun validatePassword(): Boolean{
if (pass.isBlank()){
passwordcontainer.isErrorEnabled = true
passwordcontainer.error = "This field is required"
SignUpButton.isEnabled = false
return false
}else if (pass.length < 8){
passwordcontainer.isErrorEnabled = true
passwordcontainer.error = "password is too weak(8-16)"
SignUpButton.isEnabled = false
return false
}else{
passwordcontainer.isErrorEnabled = false
SignUpButton.isEnabled = true
return true
}
}
fun validateConfirmpassword(): Boolean{
if (con.isBlank()){
confirmcontainer.isErrorEnabled = true
confirmcontainer.error = "This field is required"
SignUpButton.isEnabled = false
return false
}else if (con != pass){
passwordcontainer.isErrorEnabled = true
passwordcontainer.error = "passwords don't match"
confirmcontainer.isErrorEnabled = true
confirmcontainer.error = "passwords don't match"
SignUpButton.isEnabled = false
return false
}else{
confirmcontainer.isErrorEnabled = false
SignUpButton.isEnabled = true
return true
}
}
SignUpButton.isEnabled = validateEmail() && validatePassword() && validateConfirmpassword()
}
override fun afterTextChanged(p0: Editable?) {
}
}
fun Login(view: View) {
val intent = Intent(this, Login::class.java)
startActivity(intent)
finish()
}
}
|
Lamela_pharmacy/app/src/main/java/com/kotlin/lamelapharmacy/Signup.kt
|
4263911494
|
package com.kotlin.lamelapharmacy
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
class Contact_Us: Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_contact__us, container, false)
val contactAddressTextView: TextView = view.findViewById(R.id.address)
val contactPhoneTextView: TextView = view.findViewById(R.id.phone)
val contactEmailTextView: TextView = view.findViewById(R.id.email)
contactAddressTextView.text = getString(R.string.contact_address)
contactPhoneTextView.text = getString(R.string.contact_phone)
contactEmailTextView.text = getString(R.string.contact_email)
return view
}
}
|
Lamela_pharmacy/app/src/main/java/com/kotlin/lamelapharmacy/Contact_Us.kt
|
3621106152
|
package com.kotlin.lamelapharmacy
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
class Meet_the_doctor : Fragment() {
override fun onCreate(savedInstanceState:Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater:LayoutInflater, container:ViewGroup?,
savedInstanceState:Bundle?
):View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meet_the_doctor, container, false)
}
}
|
Lamela_pharmacy/app/src/main/java/com/kotlin/lamelapharmacy/Meet_the_doctor.kt
|
3258796332
|
package com.example.roomdemo
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.example.roomdemo", appContext.packageName)
}
}
|
Student-Register/app/src/androidTest/java/com/example/roomdemo/ExampleInstrumentedTest.kt
|
4269551291
|
package com.example.roomdemo
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
Student-Register/app/src/test/java/com/example/roomdemo/ExampleUnitTest.kt
|
1862405162
|
package com.example.roomdemo
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.roomdemo.databinding.ActivityMainBinding
import com.example.roomdemo.db.Subscriber
import com.example.roomdemo.db.SubscriberDatabase
import com.example.roomdemo.db.SubscriberRepository
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var subscriberViewModel: SubscriberViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this,R.layout.activity_main)
val dao = SubscriberDatabase.getInstance(application).SubscriberDAO
val repository = SubscriberRepository(dao)
val factory = SubscriberViewModelFactory(repository)
subscriberViewModel = ViewModelProvider(this,factory)[SubscriberViewModel::class.java]
binding.myViewModel = subscriberViewModel
binding.lifecycleOwner = this
initRecyclerView()
subscriberViewModel.message.observe(this, Observer {
it.getContentIfNotHandled()?.let {
Toast.makeText(this, it, Toast.LENGTH_LONG).show()
}
})
}
private fun initRecyclerView(){
binding.subscriberRecyclerView.layoutManager = LinearLayoutManager(this)
displaySubscribersList()
}
private fun displaySubscribersList(){
subscriberViewModel.subscribers.observe(this, Observer {
Log.i("MY-TAG",it.toString())
binding.subscriberRecyclerView.adapter = MyRecyclerViewAdapter(it) { selectedItem: Subscriber ->
listItemClicked(
selectedItem
)
}
})
}
private fun listItemClicked(subscriber: Subscriber){
// Toast.makeText(this, "Selected name is: ${subscriber.name}",Toast.LENGTH_LONG).show()
subscriberViewModel.initUpdateAndDelete(subscriber)
}
}
|
Student-Register/app/src/main/java/com/example/roomdemo/MainActivity.kt
|
67514332
|
package com.example.roomdemo
import android.util.Patterns
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.roomdemo.db.Subscriber
import com.example.roomdemo.db.SubscriberRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class SubscriberViewModel(private val repository: SubscriberRepository) : ViewModel(){
val subscribers = repository.subscribers
private var isUpdateOrDelete = false
private lateinit var subscriberToUpdateOrDelete : Subscriber
val inputName = MutableLiveData<String>()
val inputEmail = MutableLiveData<String>()
val saveOrUpdateButtonText = MutableLiveData<String>()
val clearAllOrDeleteButtonText = MutableLiveData<String>()
private val statusMessage = MutableLiveData<Event<String>>()
val message : LiveData<Event<String>>
get() = statusMessage
init {
saveOrUpdateButtonText.value = "Save"
clearAllOrDeleteButtonText.value = "Clear All"
}
fun saveOrUpdate(){
if (inputName.value == null) {
statusMessage.value = Event("Please enter subscriber's name")
} else if (inputEmail.value == null) {
statusMessage.value = Event("Please enter subscriber's email")
} else if (!Patterns.EMAIL_ADDRESS.matcher(inputEmail.value!!).matches()) {
statusMessage.value = Event("Please enter a correct email address")
} else {
if(isUpdateOrDelete){
subscriberToUpdateOrDelete.name = inputName.value!!
subscriberToUpdateOrDelete.email = inputEmail.value!!
update(subscriberToUpdateOrDelete)
}else {
val name = inputName.value!!
val email = inputEmail.value!!
insert(Subscriber(0, name, email))
inputName.value = ""
inputEmail.value = ""
}
}
}
fun clearAllOrDelete(){
if(isUpdateOrDelete){
delete(subscriberToUpdateOrDelete)
}else {
clearAll()
}
}
private fun insert(subscriber: Subscriber) = viewModelScope.launch(Dispatchers.IO) {
val newRowId = repository.insert(subscriber)
withContext(Dispatchers.Main){
if(newRowId > -1) {
statusMessage.value = Event("Subscriber Inserted Successfully! $newRowId")
}else{
statusMessage.value = Event("Error Occurred!")
}
}
}
private fun update(subscriber: Subscriber) = viewModelScope.launch(Dispatchers.IO) {
val numberOfRows = repository.update(subscriber)
withContext(Dispatchers.Main){
if(numberOfRows > 0) {
inputName.value = ""
inputEmail.value = ""
isUpdateOrDelete = false
saveOrUpdateButtonText.value = "Save"
clearAllOrDeleteButtonText.value = "Clear All"
statusMessage.value = Event("$numberOfRows Rows Updated Successfully!")
}else{
statusMessage.value = Event("Error Occurred!")
}
}
}
private fun delete(subscriber: Subscriber) = viewModelScope.launch(Dispatchers.IO) {
val numberOfRowsDeleted = repository.delete(subscriber)
withContext(Dispatchers.Main){
if(numberOfRowsDeleted > 0) {
inputName.value = ""
inputEmail.value = ""
isUpdateOrDelete = false
saveOrUpdateButtonText.value = "Save"
clearAllOrDeleteButtonText.value = "Clear All"
statusMessage.value = Event("$numberOfRowsDeleted Rows Deleted Successfully!")
} else {
statusMessage.value = Event("Error Occurred!")
}
}
}
private fun clearAll() = viewModelScope.launch(Dispatchers.IO) {
val numberOfRowsDeleted = repository.deleteAll()
withContext(Dispatchers.Main){
if(numberOfRowsDeleted > 0) {
statusMessage.value = Event("$numberOfRowsDeleted Rows Deleted Successfully!")
}else{
statusMessage.value = Event("Error Occurred!")
}
}
}
fun initUpdateAndDelete(subscriber: Subscriber){
inputName.value = subscriber.name
inputEmail.value = subscriber.email
isUpdateOrDelete = true
subscriberToUpdateOrDelete = subscriber
saveOrUpdateButtonText.value = "Update"
clearAllOrDeleteButtonText.value = "Delete"
}
}
|
Student-Register/app/src/main/java/com/example/roomdemo/SubscriberViewModel.kt
|
3901517834
|
package com.example.roomdemo
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.roomdemo.databinding.ListItemBinding
import com.example.roomdemo.db.Subscriber
import com.example.roomdemo.generated.callback.OnClickListener
class MyRecyclerViewAdapter(
private val subscribersList: List<Subscriber>,
private val clickListener:(Subscriber)->Unit) : RecyclerView.Adapter<MyViewHolder>()
{
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val layoutInflater = LayoutInflater.from(parent.context)
val binding : ListItemBinding =
DataBindingUtil.inflate(layoutInflater,R.layout.list_item,parent,false)
return MyViewHolder(binding)
}
override fun getItemCount(): Int {
return subscribersList.size
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
holder.bind(subscribersList[position],clickListener)
}
}
class MyViewHolder(val binding: ListItemBinding): RecyclerView.ViewHolder(binding.root){
fun bind(subscriber: Subscriber, clickListener:(Subscriber)->Unit){
binding.nameTextView.text = subscriber.name
binding.emailTextView.text = subscriber.email
binding.listItemLayout.setOnClickListener {
clickListener(subscriber)
}
}
}
|
Student-Register/app/src/main/java/com/example/roomdemo/MyRecyclerViewAdapter.kt
|
992398304
|
package com.example.roomdemo
/**
* Used as a wrapper for data that is exposed via a LiveData that represents an event.
*/
open class Event<out T>(private val content: T) {
var hasBeenHandled = false
private set // Allow external read but not write
/**
* Returns the content and prevents its use again.
*/
fun getContentIfNotHandled(): T? {
return if (hasBeenHandled) {
null
} else {
hasBeenHandled = true
content
}
}
/**
* Returns the content, even if it's already been handled.
*/
fun peekContent(): T = content
}
|
Student-Register/app/src/main/java/com/example/roomdemo/Event.kt
|
102650482
|
package com.example.roomdemo.db
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
@Dao
interface SubscriberDAO {
@Insert
suspend fun insertSubscriber(subscriber: Subscriber): Long
@Update
suspend fun updateSubscriber(subscriber: Subscriber):Int
@Delete
suspend fun deleteSubscriber(subscriber: Subscriber):Int
@Query("DELETE FROM subscriber_data_table")
suspend fun deleteAll():Int
@Query("SELECT * FROM subscriber_data_table")
fun getAllSubscribers():LiveData<List<Subscriber>>
}
|
Student-Register/app/src/main/java/com/example/roomdemo/db/SubscriberDAO.kt
|
3213283850
|
package com.example.roomdemo.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [Subscriber::class], version = 1)
abstract class SubscriberDatabase : RoomDatabase() {
abstract val SubscriberDAO : SubscriberDAO
companion object {
@Volatile
private var INSTANCE : SubscriberDatabase? = null
fun getInstance(context: Context):SubscriberDatabase{
synchronized(this){
var instance = INSTANCE
if(instance==null){
instance = Room.databaseBuilder(
context.applicationContext,
SubscriberDatabase::class.java,
"subscriber_data_database"
).build()
INSTANCE = instance
}
return instance
}
}
}
}
|
Student-Register/app/src/main/java/com/example/roomdemo/db/SubscriberDatabase.kt
|
3562717910
|
package com.example.roomdemo.db
class SubscriberRepository(private val dao: SubscriberDAO) {
val subscribers = dao.getAllSubscribers()
suspend fun insert(subscriber: Subscriber):Long{
return dao.insertSubscriber(subscriber)
}
suspend fun update(subscriber: Subscriber):Int{
return dao.updateSubscriber(subscriber)
}
suspend fun delete(subscriber: Subscriber):Int{
return dao.deleteSubscriber(subscriber)
}
suspend fun deleteAll():Int{
return dao.deleteAll()
}
}
|
Student-Register/app/src/main/java/com/example/roomdemo/db/SubscriberRepository.kt
|
773477816
|
package com.example.roomdemo.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "subscriber_data_table")
data class Subscriber(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "subscriber_id")
val id : Int,
@ColumnInfo(name = "subscriber_name")
var name : String,
@ColumnInfo(name = "subscriber_email")
var email : String
)
|
Student-Register/app/src/main/java/com/example/roomdemo/db/Subscriber.kt
|
3646519759
|
package com.example.roomdemo
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.roomdemo.db.SubscriberRepository
import java.lang.IllegalArgumentException
class SubscriberViewModelFactory(private val repository: SubscriberRepository):ViewModelProvider.Factory{
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if(modelClass.isAssignableFrom(SubscriberViewModel::class.java)) {
return SubscriberViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel Class")
}
}
|
Student-Register/app/src/main/java/com/example/roomdemo/SubscriberViewModelFactory.kt
|
3956756769
|
package com.objectivedynamics.nutribase
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.objectivedynamics.nutribase", appContext.packageName)
}
}
|
nutribase-spike/app/src/androidTest/java/com/objectivedynamics/nutribase/ExampleInstrumentedTest.kt
|
3741634079
|
package com.objectivedynamics.nutribase
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
nutribase-spike/app/src/test/java/com/objectivedynamics/nutribase/ExampleUnitTest.kt
|
1228446899
|
package com.objectivedynamics.nutribase
import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.objectivedynamics.nutribase.api.FileResult
import com.objectivedynamics.nutribase.api.createGitHubApiFileService
import com.objectivedynamics.nutribase.taglist.TagAdapter
import com.objectivedynamics.nutribase.models.NutritionData
import com.objectivedynamics.nutribase.tagDetails.TagDetailsActivity
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.Base64
class MainActivity : AppCompatActivity() {
private lateinit var adapter: TagAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.name)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
adapter = TagAdapter { tag ->
TagDetailsActivity.startActivity(this, tag)
}
val list: RecyclerView = findViewById(R.id.list)
list.layoutManager = LinearLayoutManager(this)
list.adapter = adapter
val fileService = createGitHubApiFileService()
fileService.getFile("objectivedynamics42","nutribase-data", "nutribase-v1.0.json").enqueue(object : Callback<FileResult>{
override fun onFailure(p0: Call<FileResult>, p1: Throwable) {
//TODO handle failure
}
override fun onResponse(call: Call<FileResult>, response: Response<FileResult>) {
val content = response.body()?.content
val nutritionData = getTagData(content)
adapter.submitList(nutritionData?.tags)
}
})
}
private fun getTagData(content: String?): NutritionData? {
val jsonString: String = getTagDataJson(content)
val gson = Gson()
return gson.fromJson(jsonString, NutritionData::class.java)
}
private fun getTagDataJson(content: String?): String {
val contentNoLineBreaks = content?.replace("\n", "")
val decoder = Base64.getDecoder()
val decodedBytes: ByteArray = decoder.decode(contentNoLineBreaks)
return decodedBytes.toString(Charsets.UTF_8)
}
}
|
nutribase-spike/app/src/main/java/com/objectivedynamics/nutribase/MainActivity.kt
|
1271434436
|
package com.objectivedynamics.nutribase.models
import com.google.gson.annotations.SerializedName
data class NutritionData(
@SerializedName("Tags") val tags: List<Tag>,
)
data class Tag(
@SerializedName("Name") val name: String,
)
|
nutribase-spike/app/src/main/java/com/objectivedynamics/nutribase/models/NutritionData.kt
|
3469666531
|
package com.objectivedynamics.nutribase.taglist
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
//TODO import com.objectivedynamics.nutribase.models.FoodGroup
import com.objectivedynamics.nutribase.R
import com.objectivedynamics.nutribase.models.Tag
class NutritionDataViewHolder(view: View) : RecyclerView.ViewHolder(view){
private val name: TextView = view.findViewById(R.id.name)
fun bind(tag: Tag){
name.text = tag.name
}
}
val diffCallback = object:DiffUtil.ItemCallback<Tag>(){
override fun areItemsTheSame(oldItem: Tag, newItem: Tag): Boolean {
return oldItem === newItem
}
override fun areContentsTheSame(oldItem: Tag, newItem: Tag): Boolean {
return oldItem == newItem
}
}
class TagAdapter(private val tagClickHAndler:(Tag) -> Unit) : ListAdapter<Tag,NutritionDataViewHolder>(diffCallback) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NutritionDataViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_tag, parent, false)
return NutritionDataViewHolder(view)
}
override fun onBindViewHolder(holder: NutritionDataViewHolder, position: Int) {
holder.bind(getItem(position))
holder.itemView.setOnClickListener{
tagClickHAndler(getItem(position))
}
}
}
|
nutribase-spike/app/src/main/java/com/objectivedynamics/nutribase/taglist/TagAdapter.kt
|
1646698971
|
package com.objectivedynamics.nutribase.api
data class FileResult(
val content:String
)
|
nutribase-spike/app/src/main/java/com/objectivedynamics/nutribase/api/FileResult.kt
|
3735540969
|
package com.objectivedynamics.nutribase.api
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
fun createGitHubApiFileService() : GitHubFileApiService{
val retrofit = Retrofit.Builder()
.baseUrl("https://api.github.com")
.addConverterFactory(MoshiConverterFactory.create())
.build()
return retrofit.create(GitHubFileApiService::class.java)
}
interface GitHubFileApiService {
@GET("/repos/{owner}/{repo}/contents/{path}")
fun getFile(
@Path("owner") owner:String,
@Path("repo") repo:String,
@Path("path") path:String
) : Call<FileResult>
}
|
nutribase-spike/app/src/main/java/com/objectivedynamics/nutribase/api/GitHubFileApiService.kt
|
3806466819
|
package com.objectivedynamics.nutribase.tagDetails
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.objectivedynamics.nutribase.R
import com.objectivedynamics.nutribase.models.Tag
class TagDetailsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_tag_details)
val name = intent.getStringExtra(KEY_NAME)
val nameText: TextView = findViewById(R.id.tagName)
nameText.text = name
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
}
companion object{
const val KEY_NAME = "key_name"
fun startActivity(context: Context, tag: Tag){
val intent = Intent(context, TagDetailsActivity::class.java)
intent.putExtra(KEY_NAME, tag.name)
context.startActivity(intent)
}
}
}
|
nutribase-spike/app/src/main/java/com/objectivedynamics/nutribase/tagDetails/TagDetailsActivity.kt
|
1125346200
|
package site.overwrite.encryptedfilesapp
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("site.overwrite.encryptedfilesapp", appContext.packageName)
}
}
|
Excelsior-App/app/src/androidTest/java/site/overwrite/encryptedfilesapp/ExampleInstrumentedTest.kt
|
3978005210
|
package site.overwrite.encryptedfilesapp
import org.junit.Test
import org.junit.Assert.*
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
@Test
fun addition_isCorrect() {
assertEquals(4, 2 + 2)
}
}
|
Excelsior-App/app/src/test/java/site/overwrite/encryptedfilesapp/ExampleUnitTest.kt
|
2984680832
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.ui.home
import android.app.Activity
import android.app.Application
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.Log
import android.widget.Toast
import androidx.compose.material3.SnackbarDuration
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.core.content.FileProvider
import androidx.lifecycle.AndroidViewModel
import io.ktor.util.cio.writeChannel
import io.ktor.utils.io.CancellationException
import io.ktor.utils.io.copyAndClose
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.runBlocking
import site.overwrite.encryptedfilesapp.DEFAULT_TIMEOUT_MILLIS
import site.overwrite.encryptedfilesapp.Server
import site.overwrite.encryptedfilesapp.TIMEOUT_MILLIS_PER_KILOBYTE_TRANSFER
import site.overwrite.encryptedfilesapp.cryptography.Cryptography
import site.overwrite.encryptedfilesapp.cryptography.EncryptionParameters
import site.overwrite.encryptedfilesapp.data.ItemType
import site.overwrite.encryptedfilesapp.data.RemoteDirectory
import site.overwrite.encryptedfilesapp.data.RemoteFile
import site.overwrite.encryptedfilesapp.data.RemoteItem
import site.overwrite.encryptedfilesapp.data.SyncStatus
import site.overwrite.encryptedfilesapp.file.CRUDOperations
import site.overwrite.encryptedfilesapp.file.Pathing
import site.overwrite.encryptedfilesapp.ui.SnackbarData
import site.overwrite.encryptedfilesapp.ui.ToastData
data class HomeViewUIState(
// Main fields
val server: Server = Server(""),
val username: String = "",
val password: String = "",
val encryptionParameters: EncryptionParameters = EncryptionParameters(),
val rootDirectory: RemoteDirectory = RemoteDirectory(
"",
"",
0,
emptyArray(),
emptyArray(),
null
),
val activeDirectory: RemoteDirectory = RemoteDirectory(
"",
"",
0,
emptyArray(),
emptyArray(),
null
),
// Displayables' fields
val toastData: ToastData = ToastData(),
val snackbarData: SnackbarData = SnackbarData()
) {
val parentDirectory: RemoteDirectory?
get() = activeDirectory.parentDir
val atRootDirectory: Boolean
get() = parentDirectory == null
}
data class ProcessingDialogData(
val show: Boolean = false,
val title: String = "",
val subtitle: String = "",
val onCancel: (() -> Unit)? = null
)
class HomeViewModel(application: Application) : AndroidViewModel(application) {
private val _uiState = MutableStateFlow(HomeViewUIState())
val uiState: StateFlow<HomeViewUIState> = _uiState.asStateFlow()
init {
_uiState.value = HomeViewUIState()
}
// Mutable values
var loggedIn by mutableStateOf(false)
private set
var showLogoutDialog by mutableStateOf(false)
var showCreateFolderDialog by mutableStateOf(false)
var processingDialogData by mutableStateOf(ProcessingDialogData())
private set
var processingDialogProgress: Float? by mutableStateOf(null)
private set
// Auth methods
@OptIn(ExperimentalStdlibApi::class)
fun login(
server: Server,
username: String,
password: String
) {
Log.d("HOME", "Start login process")
// Update the UI state's version of the parameters
_uiState.update {
it.copy(
server = server,
username = username,
password = password
)
}
// Then set the local copy of the required variables
var encryptionIV: String
var encryptionSalt: String
var encryptionKey: ByteArray
// Now actually perform the login operation
_uiState.value.server.handleLogin(username, password) { _ ->
_uiState.value.server.getEncryptionParameters(
{ json ->
// Set the IV and salt
encryptionIV = json.getString("iv")
encryptionSalt = json.getString("salt")
// Convert the given password into the AES
val userAESKey = Cryptography.genAESKey(password, encryptionSalt)
encryptionKey = Cryptography.decryptAES(
json.getString("encrypted_key"),
userAESKey,
encryptionIV
)
// Update the UI state's version of the parameters
_uiState.update {
it.copy(
encryptionParameters = EncryptionParameters(
iv = encryptionIV,
salt = encryptionSalt,
key = encryptionKey
)
)
}
// Get the root folder's items
getRootFolderItems()
// Mark that we are logged in
loggedIn = true
Log.d(
"HOME",
"Logged in as '$username' into ${_uiState.value.server.serverURL}"
)
Log.d(
"HOME",
"Got initialization vector '$encryptionIV'," +
" salt '$encryptionSalt', and encryption key (as hex string)" +
" '${encryptionKey.toHexString()}'"
)
},
{ _, json ->
val message = json.getString("message")
Log.d(
"HOME",
"Failed to get encryption parameters: $message"
)
showSnackbar(
message = "Failed to get encryption parameters: $message",
actionLabel = "Retry",
onAction = {
Log.d("HOME", "Retry login to '${server.serverURL}'")
login(server, username, password)
},
onDismiss = {}
)
},
{ error ->
Log.d("HOME", "Error when getting encryption parameters: $error")
showSnackbar(
message = "Error when getting encryption parameters: ${error.message}",
actionLabel = "Retry",
onAction = {
Log.d("HOME", "Retry login to '${server.serverURL}'")
login(server, username, password)
},
onDismiss = {}
)
}
)
}
}
fun logout(context: Context) {
if (!loggedIn) return
Log.d("HOME", "Start logout process")
_uiState.value.server.handleLogout {
loggedIn = false
Log.d("HOME", "Logged out; deleting synced local files")
initProcessingDialog("Deleting local files")
val filesToDelete = _uiState.value.rootDirectory.syncedConstituentFiles
val numFilesToDelete = filesToDelete.size
var file: RemoteFile
for (fileNum in 1..numFilesToDelete) {
file = filesToDelete[fileNum - 1]
CRUDOperations.deleteItem(file.path)
processingDialogProgress = fileNum.toFloat() / numFilesToDelete
}
processingDialogProgress = 1f
Log.d("HOME", "Removing directories")
if (Pathing.doesItemExist("")) {
CRUDOperations.deleteItem("")
}
Log.d("HOME", "Cleanup complete")
(context as Activity).finish()
}
}
// Directory item methods
private fun changeActiveDirectory(newActiveDirectory: RemoteDirectory) {
_uiState.update {
it.copy(
activeDirectory = newActiveDirectory
)
}
}
fun goToPreviousDirectory() {
if (!_uiState.value.atRootDirectory) {
changeActiveDirectory(_uiState.value.parentDirectory!!)
} else {
Log.d("HOME", "Cannot go back to previous directory")
showSnackbar("Cannot go back to previous directory")
}
}
fun directoryItemOnClick(item: RemoteItem) {
if (item.type == ItemType.DIRECTORY) {
changeActiveDirectory(item as RemoteDirectory)
return
}
val file = CRUDOperations.getFile(item.path)
if (file == null) {
Log.d("HOME", "File '${item.name}' not synced, so cannot open")
showSnackbar("File not synced")
return
}
// Get URI and MIME type of file
val context = getApplication<Application>().applicationContext
val uri = FileProvider.getUriForFile(
context,
"${context.packageName}.provider",
file
)
val mime = context.contentResolver.getType(uri)
// Open file with user selected app
val intent = Intent()
intent.setAction(Intent.ACTION_VIEW)
intent.setDataAndType(uri, mime)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
context.startActivity(intent)
} catch (error: ActivityNotFoundException) {
Log.d(
"HOME",
"Error when opening file: $error"
)
showSnackbar("Error when opening file: ${error.message}")
}
}
// CRUD methods
private fun getRootFolderItems() {
_uiState.value.server.listDir(
"",
{ json ->
val rootDirectory = RemoteDirectory.fromJSON(json)
_uiState.update {
it.copy(
rootDirectory = rootDirectory
)
}
changeActiveDirectory(rootDirectory)
},
{ _, json ->
val message = json.getString("message")
Log.d(
"HOME",
"Failed to get root folder items: $message"
)
showSnackbar(
message = "Failed to get root folder items: $message",
actionLabel = "Retry",
onAction = {
Log.d("HOME", "Retrying getting root folder items")
getRootFolderItems()
},
onDismiss = {}
)
},
{ error ->
Log.d("HOME", "Error when getting root folder items: $error")
showSnackbar(
message = "Error when getting root folder items: ${error.message}",
actionLabel = "Retry",
onAction = {
Log.d("HOME", "Retrying getting root folder items")
getRootFolderItems()
},
onDismiss = {}
)
}
)
}
private fun syncFile(
file: RemoteFile,
fileNum: Int? = null,
totalNumFiles: Int? = null,
onComplete: () -> Unit
) {
var interrupted = false
if (file.syncStatus != SyncStatus.NOT_SYNCED) {
onComplete()
return
}
val processingDialogSubtitle = if (fileNum == null) "" else "$fileNum of $totalNumFiles"
initProcessingDialog(
"Downloading '${file.name}'",
processingDialogSubtitle,
newOnCancel = { interrupted = true }
)
_uiState.value.server.getFile(
file.path,
file.size * TIMEOUT_MILLIS_PER_KILOBYTE_TRANSFER + DEFAULT_TIMEOUT_MILLIS,
{ interrupted },
{ channel ->
// Create a temporary file to store the encrypted content
val encryptedFile = CRUDOperations.createFile("${file.path}.encrypted")
if (encryptedFile == null) {
Log.d(
"HOME",
"Error when making file: failed to create temporary file"
)
showSnackbar(
message = "Failed to create temporary file",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retrying file sync")
syncFile(
file,
fileNum,
totalNumFiles,
onComplete
)
},
onDismiss = {}
)
hideProcessingDialog()
return@getFile
}
// Copy the channel into the encrypted file
runBlocking {
channel.copyAndClose(encryptedFile.writeChannel())
}
// Decrypt the file
initProcessingDialog(
"Decrypting '${file.name}'",
processingDialogSubtitle,
newOnCancel = { interrupted = true }
)
val decryptedFile = CRUDOperations.createFile(file.path)
if (decryptedFile == null) {
Log.d(
"HOME",
"Error when making file: failed to create output file"
)
showSnackbar(
message = "Failed to create output file",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retrying file sync")
syncFile(
file,
fileNum,
totalNumFiles,
onComplete
)
},
onDismiss = {}
)
hideProcessingDialog()
return@getFile
}
if (!Cryptography.decryptAES(
encryptedFile.inputStream(),
decryptedFile.outputStream(),
_uiState.value.encryptionParameters.key!!,
_uiState.value.encryptionParameters.iv,
interruptChecker = { interrupted }
) { numBytesDecrypted ->
processingDialogProgress =
numBytesDecrypted.toFloat() / encryptedFile.length()
}
) {
CRUDOperations.deleteItem(encryptedFile)
CRUDOperations.deleteItem(decryptedFile) // Don't want to leave traces
hideProcessingDialog()
Log.d("HOME", "File decryption cancelled")
showSnackbar("File decryption cancelled")
return@getFile
}
CRUDOperations.deleteItem(encryptedFile)
hideProcessingDialog()
onComplete()
},
{ error ->
hideProcessingDialog()
if (error is CancellationException) {
Log.d("HOME", "File request cancelled")
showSnackbar("File request cancelled")
return@getFile
}
Log.d("HOME", "File request had error: $error")
showSnackbar(
message = "File request had error: ${error.message}",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retry sync '${file.path}'")
syncFile(
file,
fileNum,
totalNumFiles,
onComplete
)
}
)
}
) { bytesSentTotal: Long, contentLength: Long ->
processingDialogProgress = bytesSentTotal.toFloat() / contentLength
}
}
fun syncItem(item: RemoteItem) {
// TODO: Allow this do be performed in the background
if (item.markedForLocalDeletion) {
showToast("Cannot sync when attempting to delete")
return
}
if (item.type == ItemType.FILE) {
val theFile = item as RemoteFile
Log.d("HOME", "Syncing file '${theFile.path}'")
syncFile(theFile) {
Log.d("HOME", "Synced file '${theFile.path}'")
showSnackbar("File synced")
}
return
}
val theDirectory = item as RemoteDirectory
Log.d("HOME", "Syncing directory '${theDirectory.path}'")
val filesToSync = theDirectory.constituentFiles
val numFilesToSync = filesToSync.size
var numSyncedFiles = 0
// This is kind of an ugly workaround... but it works
fun helper() {
if (numSyncedFiles == numFilesToSync) {
Log.d("HOME", "Synced directory '${theDirectory.path}'")
showSnackbar("Directory synced")
return
}
syncFile(
filesToSync[numSyncedFiles],
numSyncedFiles + 1,
numFilesToSync
) {
numSyncedFiles += 1
helper()
}
}
helper()
}
fun uploadFileToServer(uri: Uri) {
val context = getApplication<Application>().applicationContext
val name = Pathing.getFileName(uri, context.contentResolver)
Log.d("HOME", "Attempting to upload file '$name' to server")
val parentDir = _uiState.value.activeDirectory.path
val path: String = if (parentDir.isEmpty()) {
name
} else {
"$parentDir/$name"
}
_uiState.value.server.doesItemExist(
path,
{ exists ->
if (exists) {
Log.d("HOME", "File already exists on server; not creating")
showSnackbar("File already exists on server")
return@doesItemExist
}
// Get the file size
val fileDescriptor = context.contentResolver.openAssetFileDescriptor(uri, "r")
val fileSize: Long
if (fileDescriptor != null) {
fileSize = fileDescriptor.length
fileDescriptor.close()
} else {
fileSize = -1
}
// Get the input stream of the file
val inputStream = context.contentResolver.openInputStream(uri)
val mimeType =
context.contentResolver.getType(uri) ?: "application/octet-stream"
if (inputStream == null) {
Log.d("HOME", "Failed to read file '$path'")
showSnackbar(
message = "Failed to read file '$name'",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retrying file creation")
uploadFileToServer(uri)
},
onDismiss = {}
)
return@doesItemExist
}
var interrupted = false
initProcessingDialog(
"Encrypting '$name'",
newOnCancel = { interrupted = true }
)
// Create a temporary file to store the encrypted content
val encryptedFile = CRUDOperations.createFile("$path.encrypted")
if (encryptedFile == null) {
Log.d(
"HOME",
"Error when making file: failed to create temporary file"
)
showSnackbar(
message = "Failed to create temporary file for uploading",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retrying file creation")
uploadFileToServer(uri)
},
onDismiss = {}
)
hideProcessingDialog()
return@doesItemExist
}
// Now encrypt the original file, storing the result in the temporary file
if (!Cryptography.encryptAES(
inputStream,
encryptedFile.outputStream(),
_uiState.value.encryptionParameters.key!!,
_uiState.value.encryptionParameters.iv,
interruptChecker = { interrupted }
) { numBytesEncrypted ->
processingDialogProgress = if (fileSize != -1L) {
numBytesEncrypted.toFloat() / fileSize
} else {
null
}
}
) {
Log.d("HOME", "File encryption cancelled")
showSnackbar("File encryption cancelled")
CRUDOperations.deleteItem(encryptedFile)
hideProcessingDialog()
return@doesItemExist
}
Log.d("HOME", "Encrypted file; attempting upload")
// Once encrypted, send file to server
initProcessingDialog(
"Uploading '$name'",
newOnCancel = { interrupted = true }
)
_uiState.value.server.uploadFile(
path,
encryptedFile,
mimeType,
fileSize * TIMEOUT_MILLIS_PER_KILOBYTE_TRANSFER + DEFAULT_TIMEOUT_MILLIS,
{ interrupted },
{
Log.d("HOME", "New file uploaded to server: $path")
/*
* Note that the `fileSize` here is *not* exactly the uploaded file's size,
* but since we are using AES encryption, the difference in the uploaded
* file size and the file size of the unencrypted file should be small
* enough to not matter when displaying.
*/
_uiState.value.activeDirectory.addFile(name, path, fileSize)
showSnackbar("Uploaded '$name'")
CRUDOperations.deleteItem(encryptedFile)
},
{ _, json ->
val message = json.getString("message")
Log.d(
"HOME",
"Failed to create file: $message"
)
CRUDOperations.deleteItem(encryptedFile)
hideProcessingDialog()
showSnackbar(
message = "Failed to upload file: $message",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retrying file creation")
uploadFileToServer(uri)
},
onDismiss = {}
)
},
{ error ->
CRUDOperations.deleteItem(encryptedFile)
hideProcessingDialog()
if (error is CancellationException) {
Log.d("HOME", "File upload cancelled")
showSnackbar("File upload cancelled")
return@uploadFile
}
Log.d("HOME", "Error when uploading file: $error")
showSnackbar(
message = "Error when making file: ${error.message}",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retrying file creation")
uploadFileToServer(uri)
},
onDismiss = {}
)
}
) { bytesSentTotal, contentLength ->
processingDialogProgress = bytesSentTotal.toFloat() / contentLength
if (bytesSentTotal == contentLength) {
hideProcessingDialog()
}
}
inputStream.close()
},
{ error ->
Log.d("HOME", "Error when checking path existence: $error")
showSnackbar(
message = "Error when checking path existence: ${error.message}",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retrying file upload")
uploadFileToServer(uri)
},
onDismiss = {}
)
}
)
}
fun createFolderOnServer(name: String) {
Log.d("HOME", "Attempting to create new folder '$name' on server")
val parentDir = _uiState.value.activeDirectory.path
val path: String = if (parentDir.isEmpty()) {
name
} else {
"$parentDir/$name"
}
_uiState.value.server.doesItemExist(
path,
{ exists ->
if (exists) {
Log.d("HOME", "Folder already exists on server; not creating")
showSnackbar("Folder already exists on server")
return@doesItemExist
}
_uiState.value.server.createFolder(
path,
{
Log.d("HOME", "New folder created on server: $path")
_uiState.value.activeDirectory.addFolder(name, path)
showSnackbar("Folder created")
},
{ _, json ->
val message = json.getString("message")
Log.d("HOME", "Failed to create folder: $message")
showSnackbar(
message = "Failed to create folder: $message",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retrying creation of folder")
createFolderOnServer(name)
},
onDismiss = {}
)
},
{ error ->
Log.d("HOME", "Error when making folder: $error")
showSnackbar(
message = "Error when making folder: ${error.message}",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retrying creation of folder")
createFolderOnServer(name)
},
onDismiss = {}
)
}
)
},
{ error ->
Log.d("HOME", "Error when checking path existence: $error")
}
)
}
fun deleteItemLocally(item: RemoteItem) {
item.markForLocalDeletion()
Log.d("HOME", "Marked '${item.path}' for local deletion")
showSnackbar(
"Deleted '${item.name}' locally",
"Undo",
duration = SnackbarDuration.Short,
onAction = {
item.unmarkForLocalDeletion()
Log.d("HOME", "Unmarked '${item.path}' for local deletion")
showSnackbar(
message = "Restored '${item.name}'",
duration = SnackbarDuration.Short
)
},
onDismiss = {
if (!item.markedForLocalDeletion) return@showSnackbar
if (CRUDOperations.deleteItem(item.path)) {
item.unmarkForLocalDeletion()
return@showSnackbar
}
Log.d("HOME", "Failed to delete '${item.path}' locally")
showSnackbar(
message = "Failed to delete '${item.name}' locally",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retrying local deletion of item")
deleteItemLocally(item)
},
onDismiss = {}
)
}
)
}
fun deleteItemFromServer(item: RemoteItem) {
item.markForServerDeletion()
Log.d("HOME", "Marked '${item.path}' for server deletion")
showSnackbar(
"Deleted '${item.name}' on server",
"Undo",
duration = SnackbarDuration.Short,
onAction = {
item.unmarkForServerDeletion()
Log.d("HOME", "Unmarked '${item.path}' for server deletion")
showSnackbar("Restored '${item.name}' on server", duration = SnackbarDuration.Short)
},
onDismiss = {
if (!item.markedForServerDeletion) return@showSnackbar
_uiState.value.server.deleteItem(
item.path,
{
if (item.type == ItemType.FILE) {
_uiState.value.activeDirectory.removeFile(item as RemoteFile)
} else {
_uiState.value.activeDirectory.removeFolder(item as RemoteDirectory)
}
Log.d("HOME", "Deleted '${item.path}' on server")
},
{ _, json ->
val message = json.getString("message")
Log.d("HOME", "Failed to delete '${item.path}' on server: $message")
showSnackbar(
message = "Failed to delete '${item.name}' on server: $message",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retrying deletion of item on server")
deleteItemFromServer(item)
},
onDismiss = {}
)
},
{ error ->
Log.d("HOME", "Error when deleting '${item.path}' on server: $error")
showSnackbar(
message = "Error when deleting '${item.name}' on server: $error",
actionLabel = "Retry",
duration = SnackbarDuration.Long,
onAction = {
Log.d("HOME", "Retrying deletion of item on server")
deleteItemFromServer(item)
},
onDismiss = {}
)
}
)
}
)
}
// Displayables methods
/**
* Shows a toast message to the screen.
* @param message Message of the toast.
* @param duration How long the toast should show on the screen.
*/
private fun showToast(
message: String,
duration: Int = Toast.LENGTH_LONG
) {
_uiState.update {
it.copy(
toastData = ToastData(message, duration)
)
}
}
/**
* Clears the toast data.
*/
fun clearToast() {
showToast("")
}
/**
* Shows a snackbar.
*
* @param message Message of the snackbar.
* @param actionLabel Action label to shown as a button in the snackbar.
* @param withDismissAction Whether to show a dismiss action in the snackbar.
* @param duration How long the snackbar will be shown.
* @param onAction Action to take when the action button is pressed.
* @param onDismiss Action to take when the snackbar is dismissed.
*/
private fun showSnackbar(
message: String,
actionLabel: String? = null,
withDismissAction: Boolean = false,
duration: SnackbarDuration = if (actionLabel == null) SnackbarDuration.Short else
SnackbarDuration.Indefinite,
onAction: (() -> Unit)? = null,
onDismiss: (() -> Unit)? = null,
snackbarFree: Boolean = false
) {
// If snackbar is not free yet (and not going to be free), run the current dismiss action
if (!_uiState.value.snackbarData.snackbarFree && !snackbarFree) {
if (_uiState.value.snackbarData.onDismiss != null) {
_uiState.value.snackbarData.onDismiss!!()
}
}
// Then we can safely update the snackbar
_uiState.update {
it.copy(
snackbarData = SnackbarData(
message = message,
actionLabel = actionLabel,
withDismissAction = withDismissAction,
duration = duration,
onAction = onAction,
onDismiss = onDismiss,
snackbarFree = snackbarFree
)
)
}
}
/**
* Clears the snackbar data.
*/
fun clearSnackbar() {
showSnackbar(
message = "",
snackbarFree = true
)
}
// Other methods
/**
* Initializes the processing dialog.
*
* @param newTitle New title for the processing dialog.
* @param newSubtitle New subtitle for the processing dialog.
* @param newProgress New progress value for the processing dialog. Put `null` if the dialog is
* meant to be indefinite.
*/
private fun initProcessingDialog(
newTitle: String,
newSubtitle: String = "",
newProgress: Float? = 0f,
newOnCancel: (() -> Unit)? = null
) {
if (processingDialogData.show) {
hideProcessingDialog()
}
processingDialogData = ProcessingDialogData(
true,
newTitle,
newSubtitle,
newOnCancel
)
processingDialogProgress = newProgress
}
/**
* Hides the processing dialog.
*/
private fun hideProcessingDialog() {
processingDialogData = ProcessingDialogData(
false,
"",
"",
null
)
processingDialogProgress = null
runBlocking {
delay(100)
// FIXME: This is quite hacky to fix the issue of the non-updating of the title.
// Is there a better way?
}
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/home/HomeViewModel.kt
|
2167042913
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.ui.home
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.runBlocking
import site.overwrite.encryptedfilesapp.Server
import site.overwrite.encryptedfilesapp.data.Credentials
import site.overwrite.encryptedfilesapp.data.DataStoreManager
import site.overwrite.encryptedfilesapp.serializable
import site.overwrite.encryptedfilesapp.ui.home.services.AppIsActiveService
import site.overwrite.encryptedfilesapp.ui.theme.EncryptedFilesAppTheme
class HomeActivity : ComponentActivity() {
// Properties
private lateinit var dataStoreManager: DataStoreManager
private lateinit var homeViewModel: HomeViewModel
@SuppressLint("SourceLockedOrientationActivity")
override fun onCreate(savedInstanceState: Bundle?) {
Log.d("HOME", "onCreate called")
super.onCreate(savedInstanceState)
// Prevent screen rotate
this.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
// Get the data passed in from the login view
val credentials: Credentials = intent.serializable("credentials")!!
val server = Server(credentials.serverURL)
val username = credentials.username
val password = credentials.password
// Update server URL and username
dataStoreManager = DataStoreManager(applicationContext)
runBlocking {
dataStoreManager.setServerURL(credentials.serverURL)
dataStoreManager.setUsername(credentials.username)
}
// Start services
// TODO: Allow return to app on press on notification
val appIsActiveIntent = Intent(this, AppIsActiveService::class.java)
appIsActiveIntent.putExtra("credentials", credentials)
startForegroundService(appIsActiveIntent)
// Then set the content
setContent {
EncryptedFilesAppTheme {
homeViewModel = viewModel()
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
HomeScreen(
server = server,
username = username,
password = password,
homeViewModel = homeViewModel
)
}
}
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
if (intent.getBooleanExtra("close_app", false)) {
finish()
}
}
override fun onDestroy() {
Log.d("HOME", "onDestroy called")
stopService(Intent(this, AppIsActiveService::class.java))
homeViewModel.logout(this)
super.onDestroy()
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/home/HomeActivity.kt
|
3380347597
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.ui.home
import android.content.res.Configuration
import android.net.Uri
import android.widget.Toast
import androidx.activity.compose.BackHandler
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
import androidx.compose.material.icons.automirrored.filled.Logout
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.CloudDone
import androidx.compose.material.icons.filled.CreateNewFolder
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Folder
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Sync
import androidx.compose.material.icons.filled.UploadFile
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material.icons.outlined.Cloud
import androidx.compose.material.icons.outlined.CloudOff
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FabPosition
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.SnackbarResult
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults.topAppBarColors
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import site.overwrite.encryptedfilesapp.Server
import site.overwrite.encryptedfilesapp.data.ItemType
import site.overwrite.encryptedfilesapp.data.RemoteDirectory
import site.overwrite.encryptedfilesapp.data.RemoteFile
import site.overwrite.encryptedfilesapp.data.RemoteItem
import site.overwrite.encryptedfilesapp.data.SyncStatus
import site.overwrite.encryptedfilesapp.file.Pathing
import site.overwrite.encryptedfilesapp.ui.Dialogs
import site.overwrite.encryptedfilesapp.ui.theme.EncryptedFilesAppTheme
// Main composable
@Composable
fun HomeScreen(
server: Server?,
username: String,
password: String,
homeViewModel: HomeViewModel
) {
val context = LocalContext.current
val homeViewUIState by homeViewModel.uiState.collectAsState()
val snackbarHostState = remember { SnackbarHostState() }
var topBarName = homeViewUIState.activeDirectory.name
if (topBarName == "") {
topBarName = "Home"
}
Scaffold(
topBar = {
HomeTopBar(
name = topBarName,
hasPreviousDirectory = !homeViewUIState.atRootDirectory,
previousDirectoryOnClick = { homeViewModel.goToPreviousDirectory() },
setShowConfirmLogoutDialog = { homeViewModel.showLogoutDialog = it },
onClickSyncCurrentDirectory = { homeViewModel.syncItem(homeViewUIState.activeDirectory) }
)
},
snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
floatingActionButton = {
AddItemActionButton(
onClickUploadFile = { homeViewModel.uploadFileToServer(it) },
onClickCreateFolder = { homeViewModel.showCreateFolderDialog = true }
)
},
floatingActionButtonPosition = FabPosition.End
) { innerPadding ->
if (!homeViewModel.loggedIn) {
Column(
modifier = Modifier
.padding(innerPadding)
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
CircularProgressIndicator(
modifier = Modifier.width(48.dp),
color = MaterialTheme.colorScheme.secondary,
trackColor = MaterialTheme.colorScheme.surfaceVariant,
)
}
return@Scaffold
}
val itemsToShow: ArrayList<RemoteItem> = arrayListOf()
for (item in homeViewUIState.activeDirectory.items) {
if (!item.markedForServerDeletion) {
itemsToShow.add(item)
}
}
if (itemsToShow.size == 0) {
Column(
modifier = Modifier
.padding(innerPadding)
.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Icon(Icons.Default.Folder, "Folder", modifier = Modifier.size(100.dp))
Text("This folder is empty", fontWeight = FontWeight.Bold)
}
return@Scaffold
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(innerPadding)
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
for (item in itemsToShow) {
DirectoryItem(
item = item,
onClick = { homeViewModel.directoryItemOnClick(item) },
onSyncRequest = { homeViewModel.syncItem(item) },
onLocalDeleteRequest = { homeViewModel.deleteItemLocally(item) },
onServerDeleteRequest = { homeViewModel.deleteItemFromServer(item) }
)
}
Spacer(modifier = Modifier.height(100.dp)) // Stop action button hiding last item
}
}
// Dialogs
if (homeViewModel.showCreateFolderDialog) {
CreateFolderDialog(
textFieldValidator = { Pathing.isValidFolderName(it) },
onDismiss = { homeViewModel.showCreateFolderDialog = false },
onConfirmFolderName = {
homeViewModel.showCreateFolderDialog = false
homeViewModel.createFolderOnServer(it)
}
)
}
if (homeViewModel.processingDialogData.show) {
ProcessingDialog(
homeViewModel.processingDialogData,
homeViewModel.processingDialogProgress
)
}
if (homeViewModel.showLogoutDialog) {
LogoutDialog(
hideDialog = { homeViewModel.showLogoutDialog = false }
) {
homeViewModel.logout(context)
}
}
// Set up back button handling
BackHandler {
if (homeViewUIState.atRootDirectory) {
homeViewModel.showLogoutDialog = true
} else {
homeViewModel.goToPreviousDirectory()
}
}
// On first showing, login
LaunchedEffect(Unit) {
if (server != null) {
homeViewModel.login(
server = server,
username = username,
password = password
)
}
}
// Show any displayables
LaunchedEffect(homeViewUIState.toastData) {
if (homeViewUIState.toastData.isEmpty) return@LaunchedEffect
Toast.makeText(
context,
homeViewUIState.toastData.message,
homeViewUIState.toastData.duration
).show()
homeViewModel.clearToast()
}
LaunchedEffect(homeViewUIState.snackbarData) {
if (homeViewUIState.snackbarData.isEmpty) return@LaunchedEffect
val result = snackbarHostState.showSnackbar(
homeViewUIState.snackbarData.message,
homeViewUIState.snackbarData.actionLabel,
homeViewUIState.snackbarData.withDismissAction,
homeViewUIState.snackbarData.duration
)
when (result) {
SnackbarResult.Dismissed -> {
if (homeViewUIState.snackbarData.onDismiss != null) {
homeViewUIState.snackbarData.onDismiss!!()
}
}
SnackbarResult.ActionPerformed -> {
if (homeViewUIState.snackbarData.onAction != null) {
homeViewUIState.snackbarData.onAction!!()
}
}
}
homeViewModel.clearSnackbar()
}
}
// Scaffold composables
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun HomeTopBar(
name: String,
hasPreviousDirectory: Boolean,
previousDirectoryOnClick: () -> Unit,
setShowConfirmLogoutDialog: (Boolean) -> Unit,
onClickSyncCurrentDirectory: () -> Unit
) {
var showExtrasMenu by remember { mutableStateOf(false) }
TopAppBar(
colors = topAppBarColors(
containerColor = MaterialTheme.colorScheme.primaryContainer,
titleContentColor = MaterialTheme.colorScheme.primary,
),
navigationIcon = {
if (!hasPreviousDirectory) return@TopAppBar
IconButton(
onClick = previousDirectoryOnClick
) {
Icon(
imageVector = Icons.AutoMirrored.Default.ArrowBack,
contentDescription = "Back"
)
}
},
title = {
Text(
name,
overflow = TextOverflow.Visible,
maxLines = 1
)
},
actions = {
IconButton(onClick = { showExtrasMenu = true }) {
Icon(
imageVector = Icons.Default.MoreVert,
contentDescription = "More"
)
}
DropdownMenu(
expanded = showExtrasMenu,
onDismissRequest = { showExtrasMenu = false }
) {
DropdownMenuItem(
leadingIcon = { Icon(Icons.Default.Sync, "Sync") },
text = { Text("Sync Directory") },
onClick = {
onClickSyncCurrentDirectory()
showExtrasMenu = false
}
)
DropdownMenuItem(
leadingIcon = { Icon(Icons.Default.Info, "About") },
text = { Text("About") },
onClick = {
/* TODO: Show about page */
showExtrasMenu = false
}
)
DropdownMenuItem(
leadingIcon = { Icon(Icons.AutoMirrored.Default.Logout, "Logout") },
text = { Text("Logout") },
onClick = {
setShowConfirmLogoutDialog(true)
showExtrasMenu = false
}
)
}
}
)
}
@Composable
fun AddItemActionButton(
onClickUploadFile: (Uri) -> Unit,
onClickCreateFolder: () -> Unit
) {
var dropdownExpanded by remember { mutableStateOf(false) }
val pickFileLauncher = rememberLauncherForActivityResult(
ActivityResultContracts.GetContent()
) { uri -> if (uri != null) onClickUploadFile(uri) }
FloatingActionButton(
modifier = Modifier.padding(all = 16.dp),
onClick = { dropdownExpanded = !dropdownExpanded },
) {
Icon(Icons.Default.Add, "Add")
DropdownMenu(
expanded = dropdownExpanded,
onDismissRequest = { dropdownExpanded = false }
) {
DropdownMenuItem(
leadingIcon = { Icon(Icons.Default.UploadFile, "Upload File") },
text = { Text("Upload File") },
onClick = {
// TODO: Allow to upload multiple files at once
pickFileLauncher.launch("*/*")
dropdownExpanded = false
}
)
DropdownMenuItem(
leadingIcon = { Icon(Icons.Default.CreateNewFolder, "Create Folder") },
text = { Text("Create Folder") },
onClick = {
onClickCreateFolder()
dropdownExpanded = false
}
)
}
}
}
// Dialogs
@Composable
fun CreateFolderDialog(
textFieldValidator: (String) -> Boolean,
onDismiss: () -> Unit,
onConfirmFolderName: (String) -> Unit,
) {
Dialogs.TextInputDialog(
dialogTitle = "Enter Folder Name",
textFieldLabel = "Name",
textFieldPlaceholder = "Name of the folder",
textFieldErrorText = "Invalid folder name",
onConfirmation = { onConfirmFolderName(it) },
onDismissal = { onDismiss() },
textFieldValidator = { textFieldValidator(it) }
)
}
@Composable
fun ProcessingDialog(
processingDialogData: ProcessingDialogData,
progress: Float?
) {
Dialogs.ProgressIndicatorDialog(
dialogTitle = processingDialogData.title,
dialogSubtitle = processingDialogData.subtitle,
progress = progress,
onCancel = processingDialogData.onCancel
)
}
@Composable
fun LogoutDialog(
hideDialog: () -> Unit,
handleLogout: () -> Unit
) {
Dialogs.YesNoDialog(
icon = Icons.AutoMirrored.Default.Logout,
iconDesc = "Logout",
dialogTitle = "Confirm Logout",
dialogContent = {
Text("Are you sure that you want to log out?")
},
onYes = {
hideDialog()
handleLogout()
},
onNo = { hideDialog() }
)
}
// Main composables
/**
* Composable that represents an item that is in the active directory.
*
* @param item Remote item that this composable is representing.
* @param onClick Function to run when the item is clicked.
* @param onSyncRequest Function to run when the sync button is clicked.
* @param onLocalDeleteRequest Function to run when the delete from device button is clicked.
* @param onServerDeleteRequest Function to run when the delete from server button is clicked.
*/
@Composable
fun DirectoryItem(
item: RemoteItem,
onClick: (RemoteItem) -> Unit,
onSyncRequest: () -> Unit,
onLocalDeleteRequest: () -> Unit,
onServerDeleteRequest: () -> Unit
) {
var isDropdownExpanded by remember { mutableStateOf(false) }
var showConfirmDeleteDialog by remember { mutableStateOf(false) }
TextButton(
shape = RoundedCornerShape(0),
modifier = Modifier.height(50.dp),
onClick = { onClick(item) }
) {
// Get the correct icon and description to display
val icon: ImageVector
val description: String
when (item.type) {
ItemType.FILE -> {
icon = Icons.AutoMirrored.Default.InsertDriveFile
description = "File"
}
ItemType.DIRECTORY -> {
icon = Icons.Default.Folder
description = "Folder"
}
}
Row(
verticalAlignment = Alignment.CenterVertically
) {
// Decide on what sync status to show
val syncStatusIcon: ImageVector
val syncStatusDesc: String
when (item.syncStatus) {
SyncStatus.SYNCED -> {
syncStatusIcon = Icons.Filled.CloudDone
syncStatusDesc = "Synced"
}
SyncStatus.NOT_SYNCED -> {
syncStatusIcon = Icons.Outlined.Cloud
syncStatusDesc = "Not synced"
}
SyncStatus.UNSYNCABLE -> {
syncStatusIcon = Icons.Outlined.CloudOff
syncStatusDesc = "Unsyncable"
}
}
Icon(syncStatusIcon, syncStatusDesc, modifier = Modifier.size(24.dp))
Spacer(Modifier.size(10.dp))
// Show the appropriate item icon
Icon(icon, description)
Spacer(Modifier.size(4.dp))
// Then show the name of the item...
Text(
item.name,
modifier = Modifier.width(200.dp),
overflow = TextOverflow.Ellipsis,
maxLines = 1
)
Spacer(Modifier.weight(1f))
// ...and its size
Text(item.formattedSize())
Spacer(Modifier.size(4.dp))
// Finally define the "more actions" button
Box {
IconButton(
modifier = Modifier.size(24.dp),
onClick = { isDropdownExpanded = !isDropdownExpanded }
) {
Icon(Icons.Default.MoreVert, "More")
}
DropdownMenu(
expanded = isDropdownExpanded,
onDismissRequest = { isDropdownExpanded = false }
) {
DropdownMenuItem(
leadingIcon = { Icon(Icons.Default.Sync, "Sync") },
text = { Text("Sync") },
enabled = item.syncStatus == SyncStatus.NOT_SYNCED,
onClick = {
onSyncRequest()
isDropdownExpanded = false
}
)
DropdownMenuItem(
leadingIcon = {
Icon(
Icons.Default.Delete,
"Delete From Device"
)
},
text = { Text("Delete From Device") },
enabled = item.syncStatus == SyncStatus.SYNCED,
onClick = {
onLocalDeleteRequest()
isDropdownExpanded = false
}
)
DropdownMenuItem(
leadingIcon = {
Icon(
Icons.Default.Clear,
"Delete From Server"
)
},
text = { Text("Delete From Server") },
onClick = {
showConfirmDeleteDialog = true
isDropdownExpanded = false
}
)
// TODO: Add renaming of items
// TODO: Add moving of items
}
}
}
if (showConfirmDeleteDialog) {
Dialogs.YesNoDialog(
icon = Icons.Default.Warning,
iconDesc = "Warning",
dialogTitle = "Confirm Deletion",
dialogContent = {
Column(
verticalArrangement = Arrangement.spacedBy(5.dp)
) {
Text(
"Are you sure that you want to delete the " +
"${item.type.toString().lowercase()} '${item.name}' from the " +
"server?"
)
if (item.type == ItemType.DIRECTORY) {
Text("This action also deletes all files within the directory.")
}
Text("This action is irreversible!", fontWeight = FontWeight.Bold)
}
},
onYes = {
onServerDeleteRequest()
showConfirmDeleteDialog = false
},
onNo = { showConfirmDeleteDialog = false }
)
}
}
}
// Previews
@Preview
@Composable
fun HomeTopBarPreview() {
EncryptedFilesAppTheme {
HomeTopBar("Testing Name", true, {}, {}, {})
}
}
@Preview
@Composable
fun AddItemButtonPreview() {
EncryptedFilesAppTheme {
AddItemActionButton({}, {})
}
}
@Preview
@Composable
fun CreateFolderDialogPreview() {
EncryptedFilesAppTheme {
CreateFolderDialog({ false }, {}, {})
}
}
@Preview
@Composable
fun LogoutDialogPreview() {
EncryptedFilesAppTheme {
LogoutDialog({}, {})
}
}
@Preview(uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true)
@Composable
fun DirectoryFilePreview() {
EncryptedFilesAppTheme {
DirectoryItem(
RemoteFile(
"Test File.txt",
"", // Need to be blank for testing
1234,
null
),
{},
{},
{},
{}
)
}
}
@Preview(uiMode = Configuration.UI_MODE_NIGHT_NO, showBackground = true)
@Composable
fun DirectoryFolderPreview() {
EncryptedFilesAppTheme {
DirectoryItem(
RemoteDirectory(
"Test Folder",
"dir1/dir2/subdir3",
7891011,
emptyArray(),
emptyArray(),
null
),
{},
{},
{},
{}
)
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/home/HomeComponents.kt
|
831565655
|
/*
* Copyright (c) 2024 PhotonicGluon.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package site.overwrite.encryptedfilesapp.ui.home.services
import android.app.NotificationManager
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.core.app.ServiceCompat
import site.overwrite.encryptedfilesapp.data.Credentials
import site.overwrite.encryptedfilesapp.serializable
import site.overwrite.encryptedfilesapp.ui.NotificationActionButtonData
import site.overwrite.encryptedfilesapp.ui.NotificationChannelData
import site.overwrite.encryptedfilesapp.ui.NotificationCreator
import site.overwrite.encryptedfilesapp.ui.NotificationData
import site.overwrite.encryptedfilesapp.ui.home.HomeActivity
class CloseAppReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent?) {
Log.d("CLOSE-APP-RECEIVER", "Received request to close app")
val shutdownIntent = Intent(context, HomeActivity::class.java)
shutdownIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
shutdownIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
shutdownIntent.putExtra("close_app",true)
context.startActivity(shutdownIntent)
}
}
class AppIsActiveService : Service() {
private lateinit var persistentNotificationCreator: NotificationCreator
override fun onCreate() {
super.onCreate()
Log.d("APP-IS-ACTIVE-SERVICE", "onCreate called")
persistentNotificationCreator = NotificationCreator(
this,
NotificationChannelData(
id = "Excelsior-AppIsActive",
name = "App is Active",
desc = "Notification channel for showing that Excelsior is active",
importance = NotificationManager.IMPORTANCE_LOW
),
)
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
Log.d("APP-IS-ACTIVE-SERVICE", "onStartCommand called")
val credentials: Credentials = intent.serializable("credentials")!!
val notificationData = NotificationData(
id = 1,
title = "Excelsior is running",
text = "Connected to ${credentials.serverURL} as ${credentials.username}",
isPersistent = true
)
persistentNotificationCreator.buildNotification(notificationData)
persistentNotificationCreator.addActionButton(
NotificationActionButtonData(
this,
"ACTION_LOGOUT", // TODO: Is this correct?,
"Logout",
CloseAppReceiver::class.java,
)
)
ServiceCompat.startForeground(
this,
notificationData.id,
persistentNotificationCreator.notification!!,
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE
} else {
0
},
)
return super.onStartCommand(intent, flags, startId)
}
override fun onDestroy() {
Log.d("APP-IS-ACTIVE-SERVICE", "onDestroy called")
persistentNotificationCreator.cancelNotification()
persistentNotificationCreator.deleteChannel()
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? {
return null // We are not providing anything
}
}
|
Excelsior-App/app/src/main/java/site/overwrite/encryptedfilesapp/ui/home/services/AppIsActiveService.kt
|
2174973395
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.