Skip to content

Instantly share code, notes, and snippets.

@thegarlynch
Created September 29, 2021 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thegarlynch/f3817520afe727c8b5fe247e1c4df419 to your computer and use it in GitHub Desktop.
Save thegarlynch/f3817520afe727c8b5fe247e1c4df419 to your computer and use it in GitHub Desktop.
SlackWebHook untuk Mengirim Remote File ke Slack
import androidx.appcompat.app.AppCompatActivity
import com.cpssoft.mobile.titan.BuildConfig
import com.cpssoft.mobile.titan.common.extentions.formatDate
import com.cpssoft.mobile.titan.common.global.App
import com.cpssoft.mobile.titan.common.view.dialog.ApproveDialog
import com.cpssoft.mobile.titan.server.RemoteModule
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.*
import org.threeten.bp.ZonedDateTime
import timber.log.Timber
object SlackWebHook {
private const val FILES_UPLOAD_URL = "https://slack.com/api/files.upload"
private const val FRAGMENT_TAG = "Slack Dialog Approval"
private fun slackRequest(): Request {
val dbName = RemoteModule.getLocalDbName()
val file = App.context.getDatabasePath(dbName)
val newDbName = file.name + "_" + ZonedDateTime.now()
.formatDate("ddMMyyyyA")
val multipart = MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("token", BuildConfig.SLACK_TOKEN)
.addFormDataPart("channels", BuildConfig.SLACK_CHANNEL_MAINTENANCE)
.addFormDataPart(
"file", newDbName,
RequestBody.create(
MediaType.parse("application/x-sqlite3"),
file
)
)
.addFormDataPart("filename", newDbName)
.addFormDataPart("filetype", ".sqlite3")
.build()
return Request.Builder()
.addHeader("Content-Type", "multipart/form-data")
.url(FILES_UPLOAD_URL)
.post(multipart)
.build()
}
/**
* This will send DB to POS Slack Channel
* Only if it is debugging
*/
private fun sendDebugDBFile() {
if (!BuildConfig.DEBUG) {
return
}
try {
val client = OkHttpClient.Builder().build()
val resp = client.newCall(slackRequest()).execute()
if (resp.isSuccessful) {
val respBody = resp.body()!!.string()
Timber.d("SlackWebHookResponse : $respBody")
} else {
Timber.d("Slack Server Error ${resp.code()}")
}
} catch (ex: Exception) {
Timber.d(ex, "Slack Exception")
}
}
fun sendUploadDatabaseDialog(
activity: AppCompatActivity,
continueTask: () -> Unit
) {
if (!BuildConfig.DEBUG) {
continueTask.invoke()
}
val dialog = ApproveDialog.newInstance(
"Upload Database",
"Database Local QA akan dikirim untuk debugging"
)
dialog.onYes = {
// dismiss dialog early
continueTask.invoke()
dialog.dismiss()
val scope = CoroutineScope(Dispatchers.IO)
scope.launch(Dispatchers.IO) {
sendDebugDBFile()
}
}
dialog.onNo = {
continueTask.invoke()
dialog.dismiss()
}
dialog.show(activity.supportFragmentManager, FRAGMENT_TAG)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment