Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add: Option to unenrol from courses #336

Open
wants to merge 1 commit into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 18 additions & 5 deletions app/src/main/java/crux/bphc/cms/fragments/CourseContentFragment.kt
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import androidx.core.text.HtmlCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
Expand All @@ -22,6 +23,7 @@ import crux.bphc.cms.app.Urls
import crux.bphc.cms.core.FileManager
import crux.bphc.cms.fragments.MoreOptionsFragment.OptionsViewModel
import crux.bphc.cms.helper.CourseDataHandler
import crux.bphc.cms.helper.CourseManager
import crux.bphc.cms.helper.CourseRequestHandler
import crux.bphc.cms.interfaces.ClickListener
import crux.bphc.cms.interfaces.CourseContent
Expand All @@ -43,8 +45,10 @@ import kotlin.collections.ArrayList
*/
class CourseContentFragment : Fragment() {
private lateinit var fileManager: FileManager
private lateinit var courseDataHandler: CourseDataHandler
private lateinit var realm: Realm
private lateinit var courseDataHandler: CourseDataHandler
private lateinit var courseRequestHandler: CourseRequestHandler
private lateinit var courseManager: CourseManager

var courseId: Int = 0
private lateinit var courseName: String
Expand Down Expand Up @@ -86,9 +90,13 @@ class CourseContentFragment : Fragment() {
courseName = courseDataHandler.getCourseName(courseId)
courseSections = courseDataHandler.getCourseData(courseId)

courseRequestHandler = CourseRequestHandler()

fileManager = FileManager(requireActivity(), courseName) { setCourseContentsOnAdapter() }
fileManager.registerDownloadReceiver()

courseManager = CourseManager(courseId, courseRequestHandler)

setHasOptionsMenu(true)
}

Expand Down Expand Up @@ -325,7 +333,6 @@ class CourseContentFragment : Fragment() {

private fun refreshContent(contextUrl: String = "") {
CoroutineScope(Dispatchers.IO).launch {
val courseRequestHandler = CourseRequestHandler()
var sections = mutableListOf<CourseSection>()
try {
sections = courseRequestHandler.getCourseDataSync(courseId)
Expand Down Expand Up @@ -391,16 +398,22 @@ class CourseContentFragment : Fragment() {
setCourseContentsOnAdapter()
Toast.makeText(activity, "Marked all as read", Toast.LENGTH_SHORT).show()
return true
}
if (item.itemId == R.id.action_open_in_browser) {
} else if (item.itemId == R.id.action_open_in_browser) {
Utils.openURLInBrowser(requireActivity(), Urls.getCourseUrl(courseId).toString())
return true;
} else {
viewLifecycleOwner.lifecycleScope.launch {
courseManager.unenrolCourse(requireContext())
}
}


return super.onOptionsItemSelected(item)
}

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.course_details_menu, menu)
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.course_details_menu, menu)
}

override fun onDestroy() {
Expand Down
52 changes: 52 additions & 0 deletions app/src/main/java/crux/bphc/cms/helper/CourseManager.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package crux.bphc.cms.helper

import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.annotation.UiThread
import crux.bphc.cms.models.course.Course
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class CourseManager(val courseId: Int, val courseRequestHandler: CourseRequestHandler) {

var startedUnenrol: Boolean = false

@UiThread
suspend fun unenrolCourse(context: Context): Boolean {
/* Guard against multiple presses */
if (startedUnenrol) return false
startedUnenrol = true

if (!UserSessionManager.hasValidSession()) {
if (!UserSessionManager.createUserSession()) {
Toast.makeText(
context,
"Failed to create session. Try logging out and back in!",
Toast.LENGTH_LONG
).show()
startedUnenrol = false
return false
}
}

val ret = withContext(Dispatchers.IO) {
val idsess = courseRequestHandler.getEnrolIdSessKey(courseId) ?:
return@withContext false
val enrolId = idsess.first ?: return@withContext false
val sessKey = idsess.second ?: return@withContext false

courseRequestHandler.unenrolSelf(enrolId, sessKey)
}

if (ret) {
Toast.makeText(context, "Sucessfully unenroled from course!", Toast.LENGTH_LONG).show()
} else {
Toast.makeText(context, "Failed to unenrol from course!", Toast.LENGTH_LONG ).show()
}

startedUnenrol = false
return ret
}

}
38 changes: 37 additions & 1 deletion app/src/main/java/crux/bphc/cms/helper/CourseRequestHandler.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import android.content.Context;
import android.util.Log;
import android.util.Pair;
import android.widget.Toast;

import androidx.annotation.NonNull;
Expand Down Expand Up @@ -29,6 +30,7 @@
import crux.bphc.cms.models.forum.ForumData;
import crux.bphc.cms.network.APIClient;
import crux.bphc.cms.network.MoodleServices;
import kotlin.text.Regex;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
Expand Down Expand Up @@ -246,7 +248,6 @@ public List<Discussion> getForumDiscussions(int moduleId) {
return null;
}


@NotNull
public List<Discussion> getForumDicussionsSync(int moduleId) throws IOException {
Call<ForumData> call = moodleServices.getForumDiscussions(userAccount.getToken(), moduleId, 0, 0);
Expand Down Expand Up @@ -276,6 +277,41 @@ public void onFailure(@NotNull Call<ForumData> call, @NotNull Throwable t) {
});
}

@Nullable
public Pair<String,String> getEnrolIdSessKey(int courseId) {
String sessionCookie = UserSessionManager.INSTANCE.getFormattedSessionCookie();
Call<ResponseBody> call = moodleServices.viewCoursePage(sessionCookie, courseId);
try {
Response<ResponseBody> response = call.execute();
String rawHtml = response.body().string();
if (rawHtml == null) {
return null;
}

String enrolId = new Regex("enrolid=([0-9]+)").find(rawHtml, 0)
.getGroupValues().get(1);
String sessKey = new Regex("sesskey=(\\w+)").find(rawHtml, 0)
.getGroupValues().get(1);
return new Pair(enrolId, sessKey);
} catch (IOException | IndexOutOfBoundsException | NullPointerException e) {
Log.e(TAG, "Failed in getEnrolIdSessKey", e);
return null;
}
}

public boolean unenrolSelf(String enrolId, String sessKey) {
String sessionCookie = UserSessionManager.INSTANCE.getFormattedSessionCookie();
Call<ResponseBody> call = moodleServices.selfUnenrolCourse(sessionCookie, enrolId, sessKey);
try{
Response<ResponseBody> response = call.execute();
/* We have no way of verifying unenrolment success */
return true;
} catch (IOException e) {
Log.e(TAG, "Failed in unenrolSelf", e);
return false;
}
}

//This method resolves the names of files with same names
private List<CourseSection> resolve(List<CourseSection> courseSections) {
List<Content> contents = new ArrayList<>();
Expand Down
93 changes: 93 additions & 0 deletions app/src/main/java/crux/bphc/cms/helper/UserSessionManager.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package crux.bphc.cms.helper

import android.util.Log
import crux.bphc.cms.models.UserAccount
import crux.bphc.cms.network.APIClient
import crux.bphc.cms.network.MoodleServices
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException

object UserSessionManager {
/**
* Create an HTTP session using a private token.
*/
suspend fun createUserSession(): Boolean {
val token = UserAccount.token
val privateToken = UserAccount.privateToken
if (privateToken.isEmpty()) {
return false;
}

val retrofit = APIClient.getRetrofitInstance(false)
val moodleServices = retrofit.create(MoodleServices::class.java)

/*
* We first use the private token to get an autologin key. This key
* then can be used to generate a session cookie.
*/
val detail = withContext(Dispatchers.IO) {
val call = moodleServices.autoLoginGetKey(token, privateToken) ?: return@withContext null
try {
val response = call.execute()
if (!response.isSuccessful()) {
return@withContext null
}

return@withContext response.body()
} catch (e: IOException) {
Log.e("UserAccount", "IOException when fetching autologin key", e)
return@withContext null
}
} ?: return false

return withContext(Dispatchers.IO) {
val call = moodleServices.autoLoginWithKey(detail.autoLoginUrl, UserAccount.userID,
detail.key) ?: return@withContext false

try {
val response = call.execute()
if (!response.raw().isRedirect) {
return@withContext false
}

/*
* The server responds with 'Set-Cookie' headers for each
* cookie it wants to set. Attributes are separated by ;.
* The first attribute is the 'cookie-name=value' pair
* we require.
*/
val cookies = response.raw().headers("Set-Cookie") ?: return@withContext false
for (cookie in cookies) {
val kv = cookie.trim().split(";")[0].split("=")
if (kv[0] != "MoodleSession") {
continue
}

UserAccount.sessionCookie = kv[1]
UserAccount.sessionCookieGenEpoch = System.currentTimeMillis() / 1000;
return@withContext true
}
return@withContext false
} catch(e: IOException) {
Log.e("UserAccount", "IOException when attempting to autologin", e)
return@withContext false
}
}
}

fun getFormattedSessionCookie(): String {
return "MoodleSession=${UserAccount.sessionCookie}"
}

fun hasValidSession(): Boolean {
/*
* We have no real way of determining if the session is still valid.
* Futher more, Moodle rate limits autologin to 6 minutes. We simply
* assume a session generated more than 6 minutes ago is invalid.
* A less naive implementation could perform an actual HTTP request
* and determine if the session is valid or not.
*/
return UserAccount.sessionCookieGenEpoch + (6 * 60) > System.currentTimeMillis() / 1000;
}
}
40 changes: 37 additions & 3 deletions app/src/main/java/crux/bphc/cms/models/UserAccount.kt
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
package crux.bphc.cms.models

import android.content.Context
import android.os.Build
import android.util.Log
import crux.bphc.cms.app.MyApplication
import crux.bphc.cms.models.core.UserDetail
import crux.bphc.cms.network.APIClient
import crux.bphc.cms.network.MoodleServices
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import java.time.Instant

/**
* @author Harshit Agarwal (16-Dec-2016)
Expand All @@ -20,6 +28,34 @@ object UserAccount {
val token: String
get() = prefs.getString("token", "") ?: ""

val privateToken: String
get() = prefs.getString("privateToken", "") ?: ""

/**
* A session cookie that is associated with the current user.
* The session may have expired and the cookie may be invalid.
*/
var sessionCookie: String
get() = prefs.getString("sessionCookie", "") ?: ""
set(value) {
prefs.edit()
.putString("sessionCookie", value)
.apply()
}

/**
* The approx. UNIX epoch at which this session cookie was
* generated. Can be used to roughly estimate the validity
* of the session cookie.
*/
var sessionCookieGenEpoch: Long
get() = prefs.getLong("sessionCookieGenEpoch", -1)
set(value) {
prefs.edit()
.putLong("sessionCookieGenEpoch", value)
.apply()
}

val username: String
get() = prefs.getString("username", "") ?: ""

Expand Down Expand Up @@ -48,9 +84,7 @@ object UserAccount {
.putString("token", userDetail.token)
// the private token can be used to create an http sesion
// check /admin/tool/mobile/autologin.php
.putString("privateToken", userDetail.privateToken) // the private token can be used to
// create an http session from
// che
.putString("privateToken", userDetail.privateToken)
.putString("firstname", userDetail.firstName)
.putString("lastname", userDetail.lastName)
.putString("userpictureurl", userDetail.userPictureUrl)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package crux.bphc.cms.models.core

import com.google.gson.annotations.SerializedName

data class AutoLoginDetail(
@SerializedName("key") val key: String = "",
@SerializedName("autologinurl") val autoLoginUrl: String = "",
)
Loading