Skip to content

Commit

Permalink
Mobileapps 1083 (#95)
Browse files Browse the repository at this point in the history
* fixed trash and count issue

* fixed sync issue

* fixed percentage issue and spacing

* codacy correction

* removed unused code
  • Loading branch information
aman-alfresco authored Mar 14, 2022
1 parent dbe36f6 commit 2d96755
Show file tree
Hide file tree
Showing 26 changed files with 141 additions and 99 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import com.alfresco.content.PermissionFragment
import com.alfresco.content.data.Entry
import com.alfresco.content.data.OfflineRepository
import kotlin.coroutines.cancellation.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

data class ActionCaptureMedia(
override var entry: Entry,
Expand All @@ -24,15 +26,20 @@ data class ActionCaptureMedia(
)
) {
PermissionFragment.requestOptionalPermissions(context, CaptureHelperFragment.optionalPermissions())
val item = CaptureHelperFragment.capturePhoto(context)
if (item != null) {
repository.scheduleForUpload(
item.uri.toString(),
entry.id,
item.filename,
item.description,
item.mimeType
)
val result = CaptureHelperFragment.capturePhoto(context)
if (!result.isNullOrEmpty()) {
withContext(Dispatchers.IO) {
result.map { item ->
repository.scheduleForUpload(
item.uri.toString(),
entry.id,
item.filename,
item.description,
item.mimeType
)
}
repository.setTotalTransferSize(result.size)
}
} else {
throw CancellationException("User Cancellation")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,8 @@ interface ActionPermission {
if (checkReadPermission(context))
executeIntentData(context)
} catch (ex: CancellationException) {
println("ExtensionActivity.CancellationException")
(context as AppCompatActivity).finish()
} catch (ex: Exception) {
println("ExtensionActivity.Exception")
bus.send(Error(ex.message ?: ""))
delay(1000)
(context as AppCompatActivity).finish()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ data class ActionUploadExtensionFiles(
repository.scheduleContentForUpload(context, it, entry.id, true)
}
}
repository.setTotalTransferSize(entry.parentId)
repository.setTotalTransferSize(list.size)
} else {
throw CancellationException("User Cancellation")
}
Expand All @@ -39,7 +39,6 @@ data class ActionUploadExtensionFiles(
override fun copy(_entry: Entry): ActionExtension = copy(entry = _entry)

override fun showToast(view: View, anchorView: View?) {
println("Upload Extension Files List Size === " + repository.buildTransferList().size)
MaterialAlertDialogBuilder(view.context)
.setTitle(view.resources.getString(R.string.action_upload_queue_title))
.setCancelable(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ data class ActionUploadFiles(
result.map {
repository.scheduleContentForUpload(context, it, entry.id)
}
repository.setTotalTransferSize(entry.parentId)
repository.setTotalTransferSize(result.size)
}
} else {
throw CancellationException("User Cancellation")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ data class ActionUploadMedia(
result.map {
repository.scheduleContentForUpload(context, it, entry.id)
}
repository.setTotalTransferSize(entry.parentId)
repository.setTotalTransferSize(result.size)
}
} else {
throw CancellationException("User Cancellation")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import com.alfresco.content.actions.ActionCaptureMedia
import com.alfresco.content.actions.ActionRemoveOffline
import com.alfresco.content.actions.ActionSyncNow
import com.alfresco.content.actions.ActionUploadMedia
import com.alfresco.content.browse.transfer.TransferSyncNow
import com.alfresco.content.data.AuthenticationRepository
import com.alfresco.content.data.OfflineRepository
import com.alfresco.content.data.PeopleRepository
Expand Down Expand Up @@ -86,6 +87,7 @@ class MainActivityViewModel(
coroutineScope.on<ActionCaptureMedia> { service.upload() }
coroutineScope.on<ActionUploadMedia> { service.upload() }
coroutineScope.on<ActionSyncNow> { service.syncNow(it.overrideNetwork) }
coroutineScope.on<TransferSyncNow> { service.upload() }
}

val requiresLogin: Boolean
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ class BrowseFragment : ListFragment<BrowseViewModel, BrowseViewState>() {
withState(viewModel) { state ->
if (state.path == getString(R.string.nav_path_recents)) {
updateBanner(state.totalTransfersSize, state.uploadTransferList.size)
if (state.uploadTransferList.isEmpty())
viewModel.resetTransferData()
}

if (viewModel.canAddItems(state)) {
Expand All @@ -97,33 +99,27 @@ class BrowseFragment : ListFragment<BrowseViewModel, BrowseViewState>() {

private fun updateBanner(totalSize: Int, pendingFilesCount: Int) {

println("BrowseFragment.updateBanner $totalSize $pendingFilesCount")

if (pendingFilesCount == 0) {
hideBanner(0)
return
}
bannerTransferData?.visibility = View.VISIBLE
if (totalSize != 0 && pendingFilesCount != 0)
bannerTransferData?.visibility = View.VISIBLE

val uploadFileCount = totalSize - pendingFilesCount
val percentage = (uploadFileCount.toFloat().div(totalSize.toFloat())).times(100)

if (totalSize > 1) {
if (pendingFilesCount != 0)
tvUploadingFiles?.text = String.format(getString(com.alfresco.content.listview.R.string.upload_file_text_multiple), pendingFilesCount)
else tvUploadingFiles?.text = String.format(getString(com.alfresco.content.listview.R.string.upload_complete_text_multiple), totalSize)
if (pendingFilesCount != 0) {
tvUploadingFiles?.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_upload, 0, 0, 0)
tvUploadingFiles?.text = String.format(getString(com.alfresco.content.listview.R.string.upload_file_text_multiple), pendingFilesCount)
} else {
if (pendingFilesCount != 0)
tvUploadingFiles?.text = String.format(getString(com.alfresco.content.listview.R.string.upload_file_text_single), pendingFilesCount)
else tvUploadingFiles?.text = String.format(getString(com.alfresco.content.listview.R.string.upload_complete_text_single), totalSize)
tvUploadingFiles?.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_upload_done, 0, 0, 0)
tvUploadingFiles?.text = String.format(getString(com.alfresco.content.listview.R.string.upload_complete_text_multiple), totalSize)
}

tvPercentage?.text = String.format(getString(com.alfresco.content.listview.R.string.upload_percentage_text), percentage.toInt())
tvPercentage?.text = String.format(getString(com.alfresco.content.listview.R.string.upload_percentage_text), percentage)

percentageFiles?.progress = percentage.toInt()

if (pendingFilesCount == 0)
hideBanner(1000)
if (totalSize != 0 && pendingFilesCount == 0) {
hideBanner(3000)
}
}

private fun hideBanner(millis: Long) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ class BrowseViewModel(
}
}
if (state.path == context.getString(R.string.nav_path_recents)) {
offlineRepository.updateTransferSize(offlineRepository.buildTransferList().size)
val list = offlineRepository.buildTransferList()
if (list.isEmpty())
offlineRepository.updateTransferSize(0)
setState { copy(totalTransfersSize = offlineRepository.getTotalTransfersSize()) }
}

Expand Down Expand Up @@ -226,6 +228,14 @@ class BrowseViewModel(
}
}

/**
* reset local files after uploading to server
*/
fun resetTransferData() {
offlineRepository.removeCompletedUploads()
offlineRepository.updateTransferSize(0)
}

override fun emptyMessageArgs(state: ListViewState) =
when ((state as BrowseViewState).path) {
context.getString(R.string.nav_path_recents) ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import androidx.lifecycle.lifecycleScope
import com.airbnb.epoxy.AsyncEpoxyController
import com.airbnb.mvrx.MavericksView
import com.airbnb.mvrx.withState
import com.alfresco.content.actions.ActionSyncNow
import com.alfresco.content.browse.R
import com.alfresco.content.data.Entry
import com.alfresco.content.fragmentViewModelWithArgs
Expand Down Expand Up @@ -157,5 +156,10 @@ class TransferFilesFragment : Fragment(), MavericksView {
}

private fun startSync(overrideNetwork: Boolean) =
lifecycleScope.emit(ActionSyncNow(overrideNetwork))
lifecycleScope.emit(TransferSyncNow(overrideNetwork))
}

/**
* Not a typical action - used as an event.
*/
data class TransferSyncNow(val overrideNetwork: Boolean)
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ import com.alfresco.content.browse.R
import com.alfresco.content.data.Entry
import com.alfresco.content.data.OfflineRepository
import com.alfresco.content.data.Settings
import com.alfresco.content.data.SyncService
import com.alfresco.content.network.ConnectivityTracker
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch

/**
* Mark as UploadFilesViewState
Expand Down Expand Up @@ -42,9 +46,20 @@ class TransferFilesViewModel(
private var observeExtensionUploadsJob: Job? = null

init {
viewModelScope.launch {
SyncService
.observeTransfer(context)
.map { it == SyncService.SyncState.Running }
.combine(ConnectivityTracker.networkAvailable) { running, connected ->
!running && connected
}
.execute {
copy(syncNowEnabled = it() ?: false)
}
}

observeExtensionUploads()
val list = OfflineRepository().buildTransferList()
println("transfer files list size ${list.size}")
setState { copy(entries = list) }
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import kotlinx.coroutines.suspendCancellableCoroutine

class CaptureHelperFragment : Fragment() {
private lateinit var requestLauncher: ActivityResultLauncher<Unit>
private var onResult: CancellableContinuation<CaptureItem?>? = null
private var onResult: CancellableContinuation<List<CaptureItem>?>? = null

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Expand All @@ -21,7 +21,7 @@ class CaptureHelperFragment : Fragment() {
}
}

private suspend fun capturePhoto(): CaptureItem? =
private suspend fun capturePhoto(): List<CaptureItem>? =
suspendCancellableCoroutine { continuation ->
onResult = continuation
requestLauncher.launch(Unit)
Expand All @@ -32,7 +32,7 @@ class CaptureHelperFragment : Fragment() {

suspend fun capturePhoto(
context: Context
): CaptureItem? =
): List<CaptureItem>? =
withFragment(
context,
TAG,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ import androidx.annotation.CallSuper
/**
* An [ActivityResultContract] to [take a picture] and returns a-[CaptureItem].
*/
class CapturePhotoResultContract : ActivityResultContract<Unit, CaptureItem?>() {
class CapturePhotoResultContract : ActivityResultContract<Unit, List<CaptureItem>?>() {
@CallSuper
override fun createIntent(context: Context, input: Unit): Intent {
return Intent(context, CaptureActivity::class.java)
}

override fun parseResult(resultCode: Int, intent: Intent?): CaptureItem? {
override fun parseResult(resultCode: Int, intent: Intent?): List<CaptureItem>? {
return if (intent == null || resultCode != Activity.RESULT_OK) null
else intent.extras?.getParcelable(OUTPUT_KEY)
else intent.extras?.getParcelableArrayList(OUTPUT_KEY)
}

internal companion object {
Expand Down
35 changes: 17 additions & 18 deletions data/src/main/kotlin/com/alfresco/content/data/OfflineRepository.kt
Original file line number Diff line number Diff line change
Expand Up @@ -137,18 +137,6 @@ class OfflineRepository(val session: Session = SessionManager.requireSession) {
.build()
.find()

private fun fetchAllTransferEntries(parentId: String?) =
box.query()
.apply {
if (parentId != null) {
equal(Entry_.parentId, parentId)
notEqual(Entry_.offlineStatus, OfflineStatus.UNDEFINED.value())
equal(Entry_.isUpload, true)
}
}
.build()
.find()

internal fun fetchOfflineEntry(target: Entry) = entry(target.id)

/**
Expand All @@ -160,13 +148,13 @@ class OfflineRepository(val session: Session = SessionManager.requireSession) {
/**
* update transfer size count using the parent ID
*/
fun setTotalTransferSize(parentId: String?) {
removeCompletedUploads()
fun setTotalTransferSize(size: Int) {
val count = getTotalTransfersSize()
val list = fetchAllTransferEntries()
val listById = fetchAllTransferEntries(parentId)

if (list.isEmpty())
updateTransferSize(listById.size)
else updateTransferSize(list.size + listById.size)
updateTransferSize(size)
else updateTransferSize(count + size)
}

fun scheduleContentForUpload(
Expand Down Expand Up @@ -195,9 +183,11 @@ class OfflineRepository(val session: Session = SessionManager.requireSession) {
type = Entry.Type.FILE,
mimeType = mimeType,
isUpload = true,
isExtension = isExtension,
offlineStatus = OfflineStatus.PENDING
)

clearData()

update(entry)

val dest = File(session.uploadDir, entry.boxId.toString())
Expand All @@ -211,6 +201,12 @@ class OfflineRepository(val session: Session = SessionManager.requireSession) {
}
}

private fun clearData() {
removeCompletedUploads()
if (buildTransferList().isEmpty())
updateTransferSize(0)
}

fun scheduleForUpload(
path: String,
parentId: String,
Expand All @@ -228,6 +224,9 @@ class OfflineRepository(val session: Session = SessionManager.requireSession) {
isUpload = true,
offlineStatus = OfflineStatus.PENDING
)

clearData()

update(entry)
val srcPath = path.removePrefix("file://")
File(srcPath).renameTo(File(session.uploadDir, entry.boxId.toString()))
Expand Down
17 changes: 17 additions & 0 deletions data/src/main/kotlin/com/alfresco/content/data/SyncService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,23 @@ class SyncService(
it?.let { SyncState.from(it.state) }
}

/**
* observer for uploading the files
*/
fun observeTransfer(context: Context): Flow<SyncState?> =
WorkManager
.getInstance(context)
.getWorkInfosForUniqueWorkLiveData(UNIQUE_UPLOAD_WORK_NAME)
.asFlow()
.map { list ->
list?.find { it.state == WorkInfo.State.RUNNING }
?: list?.find { !it.state.isFinished }
?: list?.firstOrNull()
}
.map {
it?.let { SyncState.from(it.state) }
}

// TODO: race condition work is cancelled but sync service may still trigger it
fun cancel(context: Context) {
WorkManager
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.alfresco.Logger
import com.alfresco.coroutines.asyncMap
import java.lang.Exception

class UploadWorker(
appContext: Context,
Expand Down Expand Up @@ -38,7 +37,6 @@ class UploadWorker(
)
true
} catch (ex: Exception) {
repository.update(entry.copy(offlineStatus = OfflineStatus.ERROR))
Logger.e(ex)
false
}
Expand Down
Loading

0 comments on commit 2d96755

Please sign in to comment.