Skip to content

Commit

Permalink
Centralize all of the network managers to one network manager (mNetwo…
Browse files Browse the repository at this point in the history
…rkManager) in MainActivity. This way, we do not create a new instance each time we need to call getAccessToken()
  • Loading branch information
meiron03 committed Dec 5, 2023
1 parent ef90fc1 commit 86f1ffa
Show file tree
Hide file tree
Showing 15 changed files with 67 additions and 97 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class AboutFragment : Fragment() {
mActivity.closeKeyboard()
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentAboutBinding.inflate(inflater, container, false)
val view = binding.root

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,13 @@ import android.graphics.PorterDuff
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.preference.PreferenceManager
import com.pennapps.labs.pennmobile.api.OAuth2NetworkManager
import com.pennapps.labs.pennmobile.api.StudentLife
import com.pennapps.labs.pennmobile.classes.GSRBookingResult
import com.pennapps.labs.pennmobile.databinding.GsrDetailsBookBinding
Expand All @@ -26,6 +24,8 @@ class BookGsrFragment : Fragment() {
private var _binding: GsrDetailsBookBinding? = null
private val binding get() = _binding!!

private lateinit var mActivity: MainActivity

// fields for booking
internal lateinit var firstNameEt: EditText
internal lateinit var lastNameEt: EditText
Expand Down Expand Up @@ -57,8 +57,8 @@ class BookGsrFragment : Fragment() {
roomName = arguments.getString("roomName") ?: ""
}
mStudentLife = MainActivity.studentLifeInstance
val mActivity : MainActivity? = activity as MainActivity
mActivity?.setTitle(R.string.gsr)
mActivity = activity as MainActivity
mActivity.setTitle(R.string.gsr)
}

override fun onResume() {
Expand All @@ -68,7 +68,7 @@ class BookGsrFragment : Fragment() {
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
savedInstanceState: Bundle?): View {
_binding = GsrDetailsBookBinding.inflate(inflater, container, false)
val view = binding.root

Expand All @@ -92,7 +92,7 @@ class BookGsrFragment : Fragment() {
|| emailEt.text.toString().matches("".toRegex())) {
Toast.makeText(activity, "Please fill in all fields before booking",
Toast.LENGTH_LONG).show()
} else if (!emailEt.text.toString().matches("""[\w]+@(seas\.|sas\.|wharton\.|nursing\.)?upenn\.edu""".toRegex())) {
} else if (!emailEt.text.toString().matches("""\w+@(seas\.|sas\.|wharton\.|nursing\.)?upenn\.edu""".toRegex())) {
Toast.makeText(activity, "Please enter a valid Penn email", Toast.LENGTH_LONG).show()
} else {
submit.isClickable = false
Expand All @@ -102,7 +102,6 @@ class BookGsrFragment : Fragment() {
}
}

val mActivity : MainActivity = activity as MainActivity
mActivity.hideBottomBar()

return view
Expand All @@ -115,14 +114,10 @@ class BookGsrFragment : Fragment() {

private fun bookGSR(gsrId: Int, gsrLocationCode: String, startTime: String?, endTime: String?, gid: Int, roomId: Int, roomName: String) {

OAuth2NetworkManager(activity as MainActivity).getAccessToken {
var sessionID = ""
mActivity.mNetworkManager.getAccessToken {
var bearerToken = ""
val sp = PreferenceManager.getDefaultSharedPreferences(activity)
Log.i("Bearer Token", sp.getString(getString(R.string.access_token), "").toString());
activity?.let { activity ->
val sp = PreferenceManager.getDefaultSharedPreferences(activity)
sessionID = sp.getString(getString(R.string.huntsmanGSR_SessionID), "") ?: ""
bearerToken = "Bearer " + sp.getString(getString(R.string.access_token), "").toString()
Log.i("BookGSRFragment", bearerToken)
}
Expand All @@ -133,49 +128,49 @@ class BookGsrFragment : Fragment() {
Log.i("BookGSRFragment", "ID $roomId")
Log.i("BookGSRFragment", "Room Name $roomName")


mStudentLife.bookGSR(
//Passing the values
bearerToken,
startTime,
endTime,
gid,
roomId,
roomName,

//Creating an anonymous callback
object : Callback<GSRBookingResult> {
override fun success(result: GSRBookingResult, response: Response) {
//Displaying the output as a toast and go back to GSR fragment
if (result.getDetail().equals("success")) {
Toast.makeText(activity, "GSR successfully booked", Toast.LENGTH_LONG).show()

// Save user info in shared preferences
val sp = PreferenceManager.getDefaultSharedPreferences(activity)
val editor = sp.edit()
editor.putString(getString(R.string.first_name), firstNameEt.text.toString())
editor.putString(getString(R.string.last_name), lastNameEt.text.toString())
editor.putString(getString(R.string.email_address), emailEt.text.toString())
editor.apply()
mStudentLife.bookGSR(
//Passing the values
bearerToken,
startTime,
endTime,
gid,
roomId,
roomName,

//Creating an anonymous callback
object : Callback<GSRBookingResult> {
override fun success(result: GSRBookingResult, response: Response) {
//Displaying the output as a toast and go back to GSR fragment
if (result.getDetail().equals("success")) {
Toast.makeText(activity, "GSR successfully booked", Toast.LENGTH_LONG).show()

// Save user info in shared preferences
val sp = PreferenceManager.getDefaultSharedPreferences(activity)
val editor = sp.edit()
editor.putString(getString(R.string.first_name), firstNameEt.text.toString())
editor.putString(getString(R.string.last_name), lastNameEt.text.toString())
editor.putString(getString(R.string.email_address), emailEt.text.toString())
editor.apply()
}
else {
Toast.makeText(activity, "GSR booking failed", Toast.LENGTH_LONG).show()
Log.e("BookGsrFragment", "GSR booking failed with " + result.getError())
}
// go back to GSR fragment
binding.loading.loadingPanel.visibility = View.GONE
activity?.onBackPressed()
}
else {
Toast.makeText(activity, "GSR booking failed", Toast.LENGTH_LONG).show()
Log.e("BookGsrFragment", "GSR booking failed with " + result.getError())
}
// go back to GSR fragment
binding.loading.loadingPanel.visibility = View.GONE
activity?.onBackPressed()
}

override fun failure(error: RetrofitError) {
//If any error occurred displaying the error as toast
Log.e("BookGSRFragment", "Error booking gsr", error)
Toast.makeText(activity, "An error has occurred. Please try again.", Toast.LENGTH_LONG).show()
binding.loading.loadingPanel.visibility = View.GONE
activity?.onBackPressed()
override fun failure(error: RetrofitError) {
//If any error occurred displaying the error as toast
Log.e("BookGSRFragment", "Error booking gsr", error)
Toast.makeText(activity, "An error has occurred. Please try again.", Toast.LENGTH_LONG).show()
binding.loading.loadingPanel.visibility = View.GONE
activity?.onBackPressed()
}
}
}
)}
)
}
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class DiningFragment : Fragment() {
setHasOptionsMenu(true)
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentDiningBinding.inflate(inflater, container, false)
val v = binding.root
binding.diningSwiperefresh.setColorSchemeResources(R.color.color_accent, R.color.color_primary)
Expand All @@ -77,8 +77,7 @@ class DiningFragment : Fragment() {
inflater.inflate(R.menu.dining_sort, menu)
val sp = PreferenceManager.getDefaultSharedPreferences(activity)
// sort the dining halls in the user-specified order
val order = sp.getString("dining_sortBy", "RESIDENTIAL")
when (order) {
when (sp.getString("dining_sortBy", "RESIDENTIAL")) {
"RESIDENTIAL" -> {
menu.findItem(R.id.action_sort_residential).isChecked = true
}
Expand Down Expand Up @@ -198,7 +197,7 @@ class DiningFragment : Fragment() {

companion object {
// Gets the dining hall menus
fun getMenus(venues: MutableList<DiningHall>) : Unit {
fun getMenus(venues: MutableList<DiningHall>) {
val idVenueMap = mutableMapOf<Int, DiningHall>()
venues.forEach { idVenueMap[it.id] = it }
val current = LocalDateTime.now()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class DiningHolderFragment : Fragment() {
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
savedInstanceState: Bundle?): View {
_binding = FragmentDiningHolderBinding.inflate(inflater, container, false)
val view = binding.root
view.dining_swiperefresh?.setOnRefreshListener { getConnected() }
Expand Down Expand Up @@ -68,7 +68,7 @@ class DiningHolderFragment : Fragment() {
binding.internetConnectionDiningHolder.visibility = View.VISIBLE
//loadingPanel?.visibility = View.GONE
} else {
binding.internetConnectionDiningHolder?.visibility = View.GONE
binding.internetConnectionDiningHolder.visibility = View.GONE
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ class DiningSettingsFragment : Fragment() {
favoriteDiningHalls.add(hall.id)
}
}
OAuth2NetworkManager(activity as MainActivity).getAccessToken {
mActivity.mNetworkManager.getAccessToken {
val bearerToken =
"Bearer " + sp.getString(getString(R.string.access_token), "").toString()
mStudentLife.sendDiningPref(bearerToken, DiningRequest(favoriteDiningHalls),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ class GsrFragment : Fragment() {
}

private fun updateStatus() {
OAuth2NetworkManager(mActivity).getAccessToken {
mActivity.mNetworkManager.getAccessToken {
val sp = PreferenceManager.getDefaultSharedPreferences(activity)
bearerToken = sp.getString(getString(R.string.access_token), "").toString();

Expand Down Expand Up @@ -243,7 +243,7 @@ class GsrFragment : Fragment() {
var gsrLocation = gsrLocationDropDown.selectedItem.toString()
val location = mapGSR(gsrLocation)
val gid = mapGID(gsrLocation)
OAuth2NetworkManager(mActivity).getAccessToken {
mActivity.mNetworkManager.getAccessToken {
val sp = PreferenceManager.getDefaultSharedPreferences(activity)
bearerToken = sp.getString(getString(R.string.access_token), "").toString();

Expand Down Expand Up @@ -285,7 +285,7 @@ class GsrFragment : Fragment() {
sortingSwitch.isClickable = false


OAuth2NetworkManager(mActivity).getAccessToken {
mActivity.mNetworkManager.getAccessToken {
val sp = PreferenceManager.getDefaultSharedPreferences(activity)
bearerToken = sp.getString(getString(R.string.access_token), "").toString();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ class GsrReservationsFragment : Fragment() {

val labs = MainActivity.studentLifeInstance

OAuth2NetworkManager(mActivity).getAccessToken {
mActivity.mNetworkManager.getAccessToken {
val sp = PreferenceManager.getDefaultSharedPreferences(mActivity)
val sessionID = sp.getString(getString(R.string.huntsmanGSR_SessionID), "")
val email = sp.getString(getString(R.string.email_address), "")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ class HomeFragment : Fragment() {
var loaded = 0

val studentLife = MainActivity.studentLifeInstance
OAuth2NetworkManager(mActivity).getAccessToken {
mActivity.mNetworkManager.getAccessToken {
val sp = sharedPreferences
val deviceID = OAuth2NetworkManager(mActivity).getDeviceId()
val bearerToken = "Bearer " + sp.getString(getString(R.string.access_token), "").toString()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ class HuntsmanGSRLogin : Fragment() {

// performs POST request and redirects user to GSR booking fragment
private fun bookHuntsmanGSR(bearerToken : String, sessionID : String) {
OAuth2NetworkManager(activity as MainActivity).getAccessToken {
(activity as MainActivity).mNetworkManager.getAccessToken {

mStudentLife.bookGSR(
//Passing the values
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,13 @@ import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.analytics.FirebaseAnalytics
import com.pennapps.labs.pennmobile.adapters.LaundryRoomAdapter
import com.pennapps.labs.pennmobile.api.StudentLife
import com.pennapps.labs.pennmobile.classes.LaundryRoom
import com.pennapps.labs.pennmobile.classes.LaundryUsage
import com.pennapps.labs.pennmobile.components.collapsingtoolbar.ToolbarBehavior
import com.pennapps.labs.pennmobile.databinding.FragmentLaundryBinding
import com.pennapps.labs.pennmobile.utils.Utils
import kotlinx.android.synthetic.main.include_main.*
import kotlinx.android.synthetic.main.loading_panel.*
import kotlinx.android.synthetic.main.loading_panel.view.*
import kotlinx.android.synthetic.main.no_results.*
Expand Down Expand Up @@ -56,15 +54,9 @@ class LaundryFragment : Fragment() {
mActivity = activity as MainActivity
mContext = mActivity
setHasOptionsMenu(true)

val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "3")
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Laundry")
bundle.putString(FirebaseAnalytics.Param.ITEM_CATEGORY, "App Feature")
FirebaseAnalytics.getInstance(mContext).logEvent(FirebaseAnalytics.Event.VIEW_ITEM, bundle)
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentLaundryBinding.inflate(inflater, container, false)
val view = binding.root

Expand Down Expand Up @@ -150,16 +142,11 @@ class LaundryFragment : Fragment() {
}
return super.onOptionsItemSelected(item)
}

override fun onResume() {
super.onResume()
}

private fun updateRooms() {

//displays banner if not connected
if (!isOnline(context)) {
binding.internetConnectionLaundry?.setBackgroundColor(resources.getColor(R.color.darkRedBackground))
binding.internetConnectionLaundry.setBackgroundColor(resources.getColor(R.color.darkRedBackground))
binding.internetConnectionMessageLaundry.text = getString(R.string.internet_error)
binding.internetConnectionLaundry.visibility = View.VISIBLE
} else {
Expand Down Expand Up @@ -218,12 +205,6 @@ class LaundryFragment : Fragment() {
// sort laundry rooms by name
laundryRoomsResult.sortWith(Comparator { room1, room2 -> room2.id - room1.id })

var loading = false
// make sure results are finished loading
while (roomsDataResult.size != count) {
loading = true
}

// update UI
mActivity.runOnUiThread {
roomsData = roomsDataResult
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class MainActivity : AppCompatActivity() {
private lateinit var mSharedPrefs: SharedPreferences

val tokenMutex = Mutex()

val mNetworkManager by lazy { OAuth2NetworkManager(this) }
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme)
if (Build.VERSION.SDK_INT > 28) {
Expand Down Expand Up @@ -98,11 +98,6 @@ class MainActivity : AppCompatActivity() {
}
}

// override fun onResume() {
// super.onResume()
// showBottomBar()
// }

private fun onExpandableBottomNavigationItemSelected() {
expandable_bottom_bar.setOnNavigationItemSelectedListener { item ->
val position = when (item.itemId) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ class PottruckFragment : Fragment() {


mActivity.runOnUiThread {
OAuth2NetworkManager(mActivity).getAccessToken {
mActivity.mNetworkManager.getAccessToken {
val sp = PreferenceManager.getDefaultSharedPreferences(mActivity)
val context = mActivity.applicationContext
val bearerToken =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class GsrReservationsAdapter(private var reservations: ArrayList<GSRReservation>
builder.setPositiveButton("Confirm") { _, _ ->
val bookingID = reservation.booking_id

OAuth2NetworkManager(mContext as MainActivity).getAccessToken {
(mContext as MainActivity).mNetworkManager.getAccessToken {

val sp = PreferenceManager.getDefaultSharedPreferences(mContext)
val sessionID = if (reservation.info == null) sp.getString(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,7 @@ class HomeAdapter(private var cells: ArrayList<HomeCell>) :
} }
val deviceID = OAuth2NetworkManager(mActivity).getDeviceId()
val idHash = Utils.getSha256Hash(deviceID)
OAuth2NetworkManager(mActivity).getAccessToken {
mActivity.mNetworkManager.getAccessToken {
val sp = PreferenceManager.getDefaultSharedPreferences(mContext)
val bearerToken = "Bearer " + sp.getString(mContext.getString(R.string.access_token), " ")

Expand Down
Loading

0 comments on commit 86f1ffa

Please sign in to comment.