diff --git a/app/build.gradle.kts b/app/build.gradle.kts index e2bf998..12d9347 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -14,8 +14,8 @@ android { applicationId = "relax.offline.mp3.music" minSdk = 24 targetSdk = 34 - versionCode = 1 - versionName = "1.0.1" + versionCode = 3 + versionName = "1.0.3" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" @@ -30,13 +30,13 @@ android { "proguard-rules.pro" ) } -// debug { -// isMinifyEnabled = true -// proguardFiles( -// getDefaultProguardFile("proguard-android-optimize.txt"), -// "proguard-rules.pro" -// ) -// } + debug { + isMinifyEnabled = true + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } } compileOptions { sourceCompatibility = JavaVersion.VERSION_1_8 @@ -60,27 +60,21 @@ dependencies { implementation("androidx.constraintlayout:constraintlayout:2.1.4") implementation("androidx.media3:media3-session:1.3.1") implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.8.0") -// implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.8.0") implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3") testImplementation("junit:junit:4.13.2") androidTestImplementation("androidx.test.ext:junit:1.1.5") androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1") - implementation("com.github.bumptech.glide:glide:4.16.0") + implementation("androidx.room:room-ktx:2.6.1") implementation("androidx.room:room-runtime:2.6.1") //noinspection KaptUsageInsteadOfKsp kapt("androidx.room:room-compiler:2.6.1") - implementation("com.geyifeng.immersionbar:immersionbar:3.2.2") - implementation("com.geyifeng.immersionbar:immersionbar-ktx:3.2.2") - implementation("com.github.lihangleo2:ShadowLayout:3.4.0") implementation("androidx.media3:media3-exoplayer:1.3.1") implementation("androidx.media3:media3-exoplayer-dash:1.3.1") implementation("androidx.media3:media3-ui:1.3.1") implementation("androidx.media3:media3-common:1.3.1") -// implementation("com.android.tools.compose:compose-preview-renderer:0.0.1-alpha01") -// implementation("org.chromium.net:cronet-api:119.6045.31") implementation("androidx.media3:media3-datasource-cronet:1.3.1") implementation("io.coil-kt:coil-compose:2.6.0") @@ -92,7 +86,15 @@ dependencies { implementation("io.ktor:ktor-serialization-kotlinx-json:2.3.8") implementation("org.brotli:dec:0.1.2") + implementation("com.github.bumptech.glide:glide:4.16.0") + implementation("com.geyifeng.immersionbar:immersionbar:3.2.2") + implementation("com.geyifeng.immersionbar:immersionbar-ktx:3.2.2") + implementation("com.github.lihangleo2:ShadowLayout:3.4.0") implementation("com.google.android.flexbox:flexbox:3.0.0") implementation("io.github.scwang90:refresh-layout-kernel:2.1.0") implementation("io.github.scwang90:refresh-footer-ball:2.1.0") + implementation ("com.google.code.gson:gson:2.10.1") + + //google +// implementation("com.google.android.gms:play-services-ads-identifier:18.0.1") } \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro index 35463f0..b074b2c 100644 --- a/app/proguard-rules.pro +++ b/app/proguard-rules.pro @@ -20,4 +20,28 @@ # hide the original source file name. #-renamesourcefileattribute SourceFile --dontwarn org.slf4j.impl.StaticLoggerBinder \ No newline at end of file +-dontwarn org.slf4j.impl.StaticLoggerBinder +-dontwarn java.lang.management.ManagementFactory +-dontwarn java.lang.management.RuntimeMXBean +-dontwarn org.slf4j.impl.StaticMDCBinder +-dontwarn org.slf4j.impl.StaticMarkerBinder +# Gson 的混淆规则 +# 保持 Gson 所使用的类及其字段名称 +-keep class com.google.gson.** { *; } +-keep class com.google.gson.stream.** { *; } + +# 保持使用 @Expose 注解的字段 +-keepattributes *Annotation* + +# 保持被序列化/反序列化的类(确保您的模型类不会被混淆) +-keep class your.package.name.** { *; } + +# 保持使用 @SerializedName 注解的字段 +-keep class ** { + @com.google.gson.annotations.SerializedName ; +} + +# 保持 Gson TypeAdapter 类 +-keep class * extends com.google.gson.TypeAdapter { + *; +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 08cf6d3..4dc58cb 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -7,13 +7,16 @@ - + - + + + + + + ${bean}") - relax.offline.music.App.appOfflineDBManager.insertOfflineBean(bean) + App.appOfflineDBManager.insertOfflineBean(bean) } suspend fun insertFavoriteData(mediaItem: MediaItem) { @@ -254,4 +250,46 @@ abstract class MoBaseActivity : AppCompatActivity(), CoroutineScope by MainScope LogTag.LogD(Innertube.TAG, "insertFavoriteBean bean->${bean}") App.appFavoriteDBManager.insertFavoriteBean(bean) } + + fun withPermission(): Boolean { + // 不允许的国家代码 + val restrictedCountries = setOf("CN", "HK", "TW", "JP", "KR", "GB", "CH", "BE", "MO", "SG") + // 检查是否包含当前的国家代码 + if (appStore.ipCountryCode in restrictedCountries) { + return false + } + // 如果不在受限国家代码中,则继续其他检查 + return withIso() + } + + private fun withIso(): Boolean { + //460 || 461 China (People's Republic of) + //454 "Hong Kong, China" + //466 "Taiwan, China" + //440 || 441 Japan + //450 Korea (Republic of) + //234 || 235 United Kingdom of Great Britain and Northern Ireland + //228 Switzerland (Confederation of) + //206 Belgium + //455 "Macao, China" + //525 Singapore (Republic of) + val restrictedCountryCodes = + setOf( + "460", + "461", + "454", + "466", + "440", + "441", + "450", + "234", + "235", + "228", + "206", + "455", + "525" + ) + val currentCountryCode = getCountryCode(this) + return currentCountryCode !in restrictedCountryCodes + } } \ No newline at end of file diff --git a/app/src/main/java/relax/offline/music/activity/MoPlayDetailsActivity.kt b/app/src/main/java/relax/offline/music/activity/MoPlayDetailsActivity.kt index 5ce97b5..6bc8443 100644 --- a/app/src/main/java/relax/offline/music/activity/MoPlayDetailsActivity.kt +++ b/app/src/main/java/relax/offline/music/activity/MoPlayDetailsActivity.kt @@ -136,7 +136,7 @@ class MoPlayDetailsActivity : MoBaseActivity(), Player.Listener { binding.nameTv.text = intent.getStringExtra(PLAY_DETAILS_NAME) binding.descTv.text = intent.getStringExtra(PLAY_DETAILS_DESC) val favoriteBeans = App.appFavoriteDBManager.getAllFavoriteBeans() - val allFilteredBeans = favoriteBeans.filter { it.isFavorite}//过滤只有为true的值 + val allFilteredBeans = favoriteBeans.filter { it.isFavorite }//过滤只有为true的值 //找到当前点击进来的歌曲media val findCurrentMedia = allFilteredBeans.find { it.videoId == videoId }?.asMediaItem if (findCurrentMedia != null) { @@ -252,10 +252,6 @@ class MoPlayDetailsActivity : MoBaseActivity(), Player.Listener { if (currentScreenDownloads != null) { LogD(TAG, "updateDownloadUI id->${currentScreenDownloads.request.id}") updateDownloadUI(currentScreenDownloads) - } else { - if (id != null) { - updateDownloadUi(id) - } } } } @@ -696,6 +692,12 @@ class MoPlayDetailsActivity : MoBaseActivity(), Player.Listener { updateDownloadUi(mediaItem.mediaId) requests.trySend(Request.UpdateFavorite(mediaItem.mediaId))//更新喜欢状态 + val currentDownload = DownloadUtil.getCurrentIdDownload(mediaItem.mediaId) + if (currentDownload != null) { + updateDownloadUI(currentDownload) + } + + Glide.with(this) .asBitmap() .load(mediaItem.mediaMetadata.artworkUri) diff --git a/app/src/main/java/relax/offline/music/activity/MoSearchMoreActivity.kt b/app/src/main/java/relax/offline/music/activity/MoSearchMoreActivity.kt index 4d06e66..966b54d 100644 --- a/app/src/main/java/relax/offline/music/activity/MoSearchMoreActivity.kt +++ b/app/src/main/java/relax/offline/music/activity/MoSearchMoreActivity.kt @@ -117,16 +117,20 @@ class MoSearchMoreActivity : MoBaseActivity() { Innertube.moSearchPage(SearchBody(query = query, params = params))?.onSuccess { result -> if (result.isNotEmpty()) { showDataUi() - val title = result[0].title + var myResult = result[0] + if(myResult.searchResultList.isEmpty()){ + myResult = result[1] + } + val title = myResult.title if (title.isNullOrEmpty()) { binding.title.visibility = View.GONE } else { binding.title.visibility = View.VISIBLE binding.title.text = title } - currentContinuation = result[0].continuation + currentContinuation = myResult.continuation list.clear() - list.addAll(result[0].searchResultList) + list.addAll(myResult.searchResultList) } else { showNoContentUi() } diff --git a/app/src/main/java/relax/offline/music/fragment/ImportFragment.kt b/app/src/main/java/relax/offline/music/fragment/ImportFragment.kt index facfbdb..aeded3a 100644 --- a/app/src/main/java/relax/offline/music/fragment/ImportFragment.kt +++ b/app/src/main/java/relax/offline/music/fragment/ImportFragment.kt @@ -10,6 +10,7 @@ import android.content.Intent import android.content.pm.PackageManager import android.media.MediaPlayer import android.net.Uri +import android.os.Build import android.os.Bundle import android.provider.MediaStore import android.view.LayoutInflater @@ -55,15 +56,7 @@ class ImportFragment : Fragment() { } binding.addBtn.setOnClickListener { binding.addBtn.visibility = View.GONE - if (ContextCompat.checkSelfPermission( - requireActivity(), - Manifest.permission.READ_EXTERNAL_STORAGE - ) != PackageManager.PERMISSION_GRANTED - ) { - requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) - } else { - openAudioPicker() - } + checkAndRequestPermissions() } importAdapterList.clear() importAdapterList.addAll(relax.offline.music.App.importList) @@ -210,10 +203,9 @@ class ImportFragment : Fragment() { binding.noContentLayout.visibility = View.GONE } else { binding.noContentLayout.visibility = View.VISIBLE + showNoDataDialog() } binding.loadingLayout.visibility = View.GONE - - binding.addBtn.visibility = View.VISIBLE } } } @@ -222,4 +214,74 @@ class ImportFragment : Fragment() { return musicFiles } + private fun showNoDataDialog() { + AlertDialog.Builder(requireActivity()) + .setTitle(getString(R.string.prompt)) + .setMessage(getString(R.string.no_data_prompt_dialog_content)) + .setPositiveButton(getString(R.string.ok)) { dialog, _ -> + binding.addBtn.visibility = View.VISIBLE + dialog.dismiss() + } + .setCancelable(false) + .show() + } + + + private fun checkAndRequestPermissions() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + val permissionsToRequest = mutableListOf() + + if (ContextCompat.checkSelfPermission( + requireActivity(), + Manifest.permission.READ_MEDIA_IMAGES + ) != PackageManager.PERMISSION_GRANTED + ) { + permissionsToRequest.add(Manifest.permission.READ_MEDIA_IMAGES) + } + if (ContextCompat.checkSelfPermission( + requireActivity(), + Manifest.permission.READ_MEDIA_VIDEO + ) != PackageManager.PERMISSION_GRANTED + ) { + permissionsToRequest.add(Manifest.permission.READ_MEDIA_VIDEO) + } + if (ContextCompat.checkSelfPermission( + requireActivity(), + Manifest.permission.READ_MEDIA_AUDIO + ) != PackageManager.PERMISSION_GRANTED + ) { + permissionsToRequest.add(Manifest.permission.READ_MEDIA_AUDIO) + } + + if (permissionsToRequest.isNotEmpty()) { + requestMultiplePermissionsLauncher.launch(permissionsToRequest.toTypedArray()) + } else { + openAudioPicker() + } + } else { + // 请求旧版本的权限 + if (ContextCompat.checkSelfPermission( + requireActivity(), + Manifest.permission.READ_EXTERNAL_STORAGE + ) != PackageManager.PERMISSION_GRANTED + ) { + requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE) + } else { + openAudioPicker() + } + } + } + + private val requestMultiplePermissionsLauncher = registerForActivityResult( + ActivityResultContracts.RequestMultiplePermissions() + ) { permissions -> + permissions.forEach { (permission, isGranted) -> + if (isGranted) { + openAudioPicker() + } else { + showExplanationDialog() + } + } + } + } \ No newline at end of file diff --git a/app/src/main/java/relax/offline/music/http/AppUtil.kt b/app/src/main/java/relax/offline/music/http/AppUtil.kt new file mode 100644 index 0000000..922e7a2 --- /dev/null +++ b/app/src/main/java/relax/offline/music/http/AppUtil.kt @@ -0,0 +1,186 @@ +package relax.offline.music.http + +import android.content.Context +import android.content.pm.PackageInfo +import android.content.pm.PackageManager +import android.media.MediaDrm +import android.os.Build +import android.telephony.TelephonyManager +import android.text.TextUtils +import relax.offline.music.App +import relax.offline.music.sp.AppStore +import java.security.MessageDigest +import java.security.NoSuchAlgorithmException +import java.util.UUID + +val packageName: String = App.app.packageName + +fun getCountryCode(context: Context): String? { + var countryCode = "" + try { + val telephonyManager = + context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager + countryCode = if (telephonyManager.phoneType == TelephonyManager.PHONE_TYPE_CDMA) { + val c = Class.forName("android.os.SystemProperties") + val get = c.getMethod("get", String::class.java) + + // Gives MCC + MNC + val homeOperator = get.invoke(c, "ro.cdma.home.operator.numeric") as String + homeOperator.substring(0, 3) // the last three digits is MNC + } else { + val config = context.resources.configuration + config.mcc.toString() + } + } catch (e: Exception) { + e.printStackTrace() + } + return countryCode +} + +fun getSimCountryIso(context: Context): String? { + val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager + return telephonyManager.simCountryIso +} + +//获取国家代码 +fun getCountry(context: Context): String? { + return getSimCountryIso(context) +} + + +fun getAppVersionName(context: Context): String? { + val packageManager = context.packageManager + var packInfo: PackageInfo? = null + try { + packInfo = packageManager.getPackageInfo(context.packageName, 0) + } catch (e: PackageManager.NameNotFoundException) { + e.printStackTrace() + } + return packInfo!!.versionName +} + +fun getAppVersionCode(context: Context): Long { + return try { + val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { + context.packageManager.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(0)) + } else { + context.packageManager.getPackageInfo(context.packageName, 0) + } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + packageInfo.longVersionCode + } else { + packageInfo.versionCode.toLong() + } + } catch (e: PackageManager.NameNotFoundException) { + e.printStackTrace() + -1 + } +} + +fun userID(context: Context): String { + var id = "" + if (TextUtils.isEmpty(AppStore(context).userID)) { + val newID = UUID.randomUUID().toString() + AppStore(context).userID = newID + } else { + id = AppStore(context).userID + } + return id +} + +fun getUUId(ctx: Context): String { + val cache = AppStore(ctx).appUUID + return if (TextUtils.isEmpty(cache)) { + val u = generateImmutableUUID(ctx) + AppStore(ctx).appUUID = u + u + } else { + cache + } +} + +fun generateImmutableUUID(context: Context): String { + /*The Android ID + * 通常被认为不可信,因为它有时为null。开发文档中说明了:这个ID会改变如果进行了出厂设置。 + * 并且,如果某个Andorid手机被Root过的话,这个ID也可以被任意改变。 + * */ + val m_szAndroidID = android.provider.Settings.Secure.getString( + context.contentResolver, + android.provider.Settings.Secure.ANDROID_ID + ) + /* + *Android系统2.3版本以上可以获取硬件Serial Number + * 优点:非手机设备也可以通过该接口获取ID。 + * */ + var serial: String? = null + serial = try { + //API>=9 使用serial号 + android.os.Build::class.java.getField("SERIAL").get(null).toString() + } catch (exception: Exception) { + "serial" // serial需要一个初始化,随便一个初始化 + } + + //drm id + var drmId: String = getDrmDeviceId() + + /* + * 有一些特殊的情况,一些如平板电脑的设置没有通话功能,或者你不愿加入READ_PHONE_STATE许可。 + * 而你仍然想获得唯一序列号之类的东西。这时你可以通过取出ROM版本、制造商、CPU型号、以及其他硬件信息来实现这一点。 + * 这样计算出来的ID不是唯一的(因为如果两个手机应用了同样的硬件以及Rom 镜像)。 + * 但应当明白的是,出现类似情况的可能性基本可以忽略。要实现这一点,你可以使用Build类: + * */ + val m_szDevIDShort = "666" + + Build.HOST.length % 10 + + Build.ID.length % 10 + + Build.MANUFACTURER.length % 10 + + Build.MODEL.length % 10 + + Build.PRODUCT.length % 10 + + Build.TAGS.length % 10 + + Build.TYPE.length % 10 + + Build.BOARD.length % 10 + + Build.BRAND.length % 10 + + Build.CPU_ABI.length % 10 + + Build.DEVICE.length % 10 + + Build.DISPLAY.length % 10 + + Build.USER.length % 10 //13 digits + + val m_szLongID = serial + m_szDevIDShort + m_szAndroidID + drmId + //md5加密生成唯一uuid + var m: MessageDigest? = null + try { + m = MessageDigest.getInstance("MD5") + } catch (e: NoSuchAlgorithmException) { + e.printStackTrace() + } + + m!!.update(m_szLongID.toByteArray(), 0, m_szLongID.length) + // get md5 bytes + val p_md5Data = m!!.digest() + // create a hex string + var m_szUniqueID = StringBuilder() + for (aP_md5Data in p_md5Data) { + val b = 0xFF and aP_md5Data.toInt() + // if it is a single digit, make sure it have 0 in front (proper padding) + if (b <= 0xF) + m_szUniqueID.append("0") + // add number to string + m_szUniqueID.append(Integer.toHexString(b)) + } // hex string to uppercase + m_szUniqueID = StringBuilder(m_szUniqueID.toString().toLowerCase()) + return m_szUniqueID.toString() +} + +private fun getDrmDeviceId(): String { + var id = "" + val WIDEVINE_UUID = UUID(-0x121074568629b532L, -0x5c37d8232ae2de13L) + val COMMON_PSSH_UUID = UUID(0x1077EFECC0B24D02L, -0x531cc3e1ad1d04b5L) + val CLEARKEY_UUID = UUID(-0x1d8e62a7567a4c37L, 0x781AB030AF78D30EL) + val PLAYREADY_UUID = UUID(-0x65fb0f8667bfbd7aL, -0x546d19a41f77a06bL) + try { + val bytesId = MediaDrm(WIDEVINE_UUID) + .getPropertyByteArray(MediaDrm.PROPERTY_DEVICE_UNIQUE_ID) + id = android.util.Base64.encodeToString(bytesId, android.util.Base64.NO_WRAP) + } catch (ignore: Exception) { + } + return id +} \ No newline at end of file diff --git a/app/src/main/java/relax/offline/music/http/BaseApiUtil.kt b/app/src/main/java/relax/offline/music/http/BaseApiUtil.kt new file mode 100644 index 0000000..dab962c --- /dev/null +++ b/app/src/main/java/relax/offline/music/http/BaseApiUtil.kt @@ -0,0 +1,103 @@ +package relax.offline.music.http + +import android.content.Context +import com.google.gson.Gson +import org.json.JSONException +import org.json.JSONObject +import relax.offline.music.App +import relax.offline.music.util.AesEncryptUtil +import java.util.Locale +import java.util.UUID + + +class BaseApiUtil { + + companion object { + val shared: BaseApiUtil by lazy { BaseApiUtil() } + const val initialAddress = "/" + const val key = "7387m0ax5x0n5tca" + const val iv = "D4Q1ymaIHSYifWS9" + + const val getIPInfoUrl = "/app/common/getIPInfo" + const val getAppDataURL = "/statistic/appdatacollection/saveAppData" + + const val BaseUrl = "https://api.tikustok.com" + } + + private fun PostContentMessage.toJson(): String { + val gson = Gson() + return gson.toJson(this) + } + + private fun PostContentSecurityBody.toJson(): String { + val gson = Gson() + return gson.toJson(this) + } + + fun initPostBody( + method: String, + url: String, + query: HashMap, + json: JSONObject? = null, + currentBaseUrl: String? = null + ): String { + val randomStr = UUID.randomUUID().toString().replace("-", "") + + val headers: HashMap = HashMap() + headers["request_userid"] = userID(App.app) + headers["request_pkgname"] = packageName + headers["base_url"] = currentBaseUrl + "" + headers["request_deviceid"] = getUUId(App.app) + headers["request_id"] = UUID.randomUUID().toString() + + val requestId = UUID.randomUUID().toString() + val timestamp = "TS" + System.currentTimeMillis() + + val trueBody = PostContentMessage( + requestId, + method, + url, + query, + headers, + json.toString(), + timestamp, + randomStr + ) + val jsonString = trueBody.toJson() + val encryptJsonString = AesEncryptUtil.encrypt(jsonString, key, iv) + val postContentSecurityBody = PostContentSecurityBody(method, encryptJsonString) + return postContentSecurityBody.toJson() + } + + + fun postJson(context: Context, eventName: String?): JSONObject { + val jsonObject = JSONObject() + try { + jsonObject.put("eventName", eventName) + jsonObject.put("timestamp", System.currentTimeMillis()) + jsonObject.put("uuid", getUUId(context)) + jsonObject.put("app_version_name", getAppVersionName(context)) + jsonObject.put("app_version_code", getAppVersionCode(context)) + jsonObject.put("channel", "google") + jsonObject.put("country", getCountry(context)) + jsonObject.put("device", "android") + jsonObject.put("language", Locale.getDefault().language) + jsonObject.put("pkgName", context.packageName) + jsonObject.put("userId", userID(context)) + } catch (e: Exception) { + e.printStackTrace() + } + return jsonObject + } + + //需要添加gaid的json组装 + fun postJson(context: Context, eventName: String?, gaId: String?): JSONObject { + val jsonObject = postJson(context, eventName) + try { + jsonObject.put("adId", gaId) + } catch (e: JSONException) { + throw RuntimeException(e) + } + return jsonObject + } +} \ No newline at end of file diff --git a/app/src/main/java/relax/offline/music/http/CommonIpInfoUtil.kt b/app/src/main/java/relax/offline/music/http/CommonIpInfoUtil.kt new file mode 100644 index 0000000..190fbf4 --- /dev/null +++ b/app/src/main/java/relax/offline/music/http/CommonIpInfoUtil.kt @@ -0,0 +1,57 @@ +package relax.offline.music.http + +import okhttp3.Call +import okhttp3.Callback +import okhttp3.Response +import org.json.JSONObject +import relax.offline.music.App +import relax.offline.music.sp.AppStore +import relax.offline.music.util.AesEncryptUtil +import relax.offline.music.util.LogTag +import java.io.IOException + +class CommonIpInfoUtil { + + private val TAG = LogTag.VO_API_LOG + + companion object { + val shared: CommonIpInfoUtil by lazy { CommonIpInfoUtil() } + } + + fun initIPInfo() { + try { + MyHttpUtil.mInstance.getIPInfo( + object : Callback { + override fun onFailure(call: Call, e: IOException) { + + } + + override fun onResponse(call: Call, response: Response) { + try { + LogTag.LogD(TAG, "getIPInfo response->${response}") + if (response.code == 200) { + val responseData = response.body?.string() + if (responseData != null) { + val jsonObject = JSONObject(responseData) + val status = jsonObject.optString("status") + if (status == "Success") { + val data = jsonObject.optString("data") + val decryptData = AesEncryptUtil.desEncrypt(data) + val jsonObjectDecryptData = JSONObject(decryptData) + LogTag.LogD(TAG, "getIPInfo data->${jsonObjectDecryptData}") + val isoCode = jsonObjectDecryptData.optString("isoCode") + AppStore(App.app).ipCountryCode = isoCode + } + } + } + } catch (e: Exception) { + e.printStackTrace() + } + } + } + ) + } catch (e: Exception) { + e.printStackTrace() + } + } +} \ No newline at end of file diff --git a/app/src/main/java/relax/offline/music/http/MyCallback.kt b/app/src/main/java/relax/offline/music/http/MyCallback.kt new file mode 100644 index 0000000..86e3835 --- /dev/null +++ b/app/src/main/java/relax/offline/music/http/MyCallback.kt @@ -0,0 +1,10 @@ +package relax.offline.music.http + +import java.io.IOException + +interface MyCallback { + fun onFailure(message: String?) + + @Throws(IOException::class) + fun onSuccess(data: String) +} \ No newline at end of file diff --git a/app/src/main/java/relax/offline/music/http/MyHttpUtil.kt b/app/src/main/java/relax/offline/music/http/MyHttpUtil.kt new file mode 100644 index 0000000..aef7c68 --- /dev/null +++ b/app/src/main/java/relax/offline/music/http/MyHttpUtil.kt @@ -0,0 +1,90 @@ +package relax.offline.music.http + +import android.content.Context +import android.net.ConnectivityManager +import okhttp3.Callback +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.RequestBody.Companion.toRequestBody +import org.json.JSONObject +import java.io.IOException +import java.util.concurrent.TimeUnit + +class MyHttpUtil { + + fun isNetworkAvailable(context: Context): Boolean { + val connectivityManager = + context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + val activeNetworkInfo = connectivityManager.activeNetworkInfo + return activeNetworkInfo != null && activeNetworkInfo.isConnected + } + + private var mOkHttpClient: OkHttpClient? = null + + companion object { + val mInstance: MyHttpUtil by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { + MyHttpUtil() + } + } + + private val CONNECT_TIMEOUT: Long = 60 //超时时间,秒 + + private val READ_TIMEOUT: Long = 60 //读取时间,秒 + + private val WRITE_TIMEOUT: Long = 60 //写入时间,秒 + + init { + val builder: OkHttpClient.Builder = OkHttpClient.Builder() + .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) + .writeTimeout(READ_TIMEOUT, TimeUnit.SECONDS) + .readTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS) + mOkHttpClient = builder.build() + } + + private val mediaType = "application/json; charset=utf-8".toMediaType() + + @Throws(IOException::class) + fun postSaveAppData(json: JSONObject, callback: Callback) { + val query: HashMap = HashMap() + val body = BaseApiUtil.shared.initPostBody( + "POST", + BaseApiUtil.getAppDataURL, + query, + json + ) + val path = BaseApiUtil.BaseUrl + BaseApiUtil.initialAddress + post(path, body, callback) + } + + fun getIPInfo(callback: Callback) { + val query: HashMap = HashMap() + val body = BaseApiUtil.shared.initPostBody( + "GET", + BaseApiUtil.getIPInfoUrl, + query + ) + val path = BaseApiUtil.BaseUrl+ BaseApiUtil.initialAddress + post(path, body, callback) + } + + fun post(path: String, postBody: String, callback: Callback) { + val requestBody = postBody.toRequestBody(mediaType) + val request: Request = Request.Builder() + .url(path) + .post(requestBody) + .build() + doAsync(request, callback) + } + + /** + * 异步请求 + */ + @Throws(IOException::class) + private fun doAsync(request: Request, callback: Callback) { + //创建请求会话 + val call = mOkHttpClient!!.newCall(request) + //同步执行会话请求 + call.enqueue(callback) + } +} \ No newline at end of file diff --git a/app/src/main/java/relax/offline/music/http/PostContentMessage.kt b/app/src/main/java/relax/offline/music/http/PostContentMessage.kt new file mode 100644 index 0000000..49a46a7 --- /dev/null +++ b/app/src/main/java/relax/offline/music/http/PostContentMessage.kt @@ -0,0 +1,14 @@ +package relax.offline.music.http + +import java.io.Serializable + +data class PostContentMessage( + var requestId: String,//uuid + var method: String,// 请求原接口的http方法 GET,POST + var url: String, // 原接口url + var query: HashMap,//原接口传的url参数 + var headers: HashMap,// 原接口传的head + var body: String,// 原接口post数据的json + var timestamp: String,// 时间戳 + var randomStr: String//随机字符串和url上的一致 +) : Serializable \ No newline at end of file diff --git a/app/src/main/java/relax/offline/music/http/PostContentSecurityBody.kt b/app/src/main/java/relax/offline/music/http/PostContentSecurityBody.kt new file mode 100644 index 0000000..5f46391 --- /dev/null +++ b/app/src/main/java/relax/offline/music/http/PostContentSecurityBody.kt @@ -0,0 +1,8 @@ +package relax.offline.music.http + +import java.io.Serializable + +data class PostContentSecurityBody( + var method: String, + var body: String, +): Serializable \ No newline at end of file diff --git a/app/src/main/java/relax/offline/music/http/UploadEventName.kt b/app/src/main/java/relax/offline/music/http/UploadEventName.kt new file mode 100644 index 0000000..28c2e3a --- /dev/null +++ b/app/src/main/java/relax/offline/music/http/UploadEventName.kt @@ -0,0 +1,123 @@ +package relax.offline.music.http + +import android.content.Context +import okhttp3.Call +import okhttp3.Response +import org.json.JSONObject +import relax.offline.music.sp.AppStore +import relax.offline.music.util.LogTag +import java.io.IOException + +class UploadEventName { + private val TAG = LogTag.VO_API_LOG + + companion object { + val shared: UploadEventName by lazy { UploadEventName() } + } + + fun init(context: Context) { + if (MyHttpUtil.mInstance.isNetworkAvailable(context)) { + initFirstOpen(context) + initStartProgram(context) + } + } + + private fun initFirstOpen(context: Context) { + if (!AppStore(context).firstOpenIsSucceed) { + try { + MyHttpUtil.mInstance.postSaveAppData( + BaseApiUtil.shared.postJson(context, "first_open"), + object : okhttp3.Callback { + override fun onFailure(call: Call, e: IOException) { + + } + + override fun onResponse(call: Call, response: Response) { + try { + LogTag.LogD(TAG, "first_open response->${response}") + if (response.code == 200) { + val responseData = response.body?.string() + if (responseData != null) { + val jsonObject = JSONObject(responseData) + val status = jsonObject.getString("status") + LogTag.LogD(TAG, "first_open jsonObject->${jsonObject}") + LogTag.LogD(TAG, "first_open status->${status}") + if (status.equals("Success")) { + AppStore(context).firstOpenIsSucceed = true + } + } + } + } catch (e: Exception) { + e.printStackTrace() + } + } + }) + } catch (e: Exception) { + LogTag.LogD(TAG, e.toString()) + } + } + } + + private fun initStartProgram(context: Context) { + try { + MyHttpUtil.mInstance.postSaveAppData( + BaseApiUtil.shared.postJson(context, "app_open"), + object : okhttp3.Callback { + override fun onFailure(call: Call, e: IOException) { + + } + + override fun onResponse(call: Call, response: Response) { + try { + LogTag.LogD(TAG, "start_program response->${response}") + if (response.code == 200) { + val responseData = response.body?.string() + if (responseData != null) { + val jsonObject = JSONObject(responseData) + val status = jsonObject.getString("status") + LogTag.LogD(TAG, "start_program jsonObject->${jsonObject}") + LogTag.LogD(TAG, "start_program status->${status}") + } + } + } catch (e: Exception) { + e.printStackTrace() + } + } + }) + } catch (e: Exception) { + LogTag.LogE(TAG, e.toString()) + } + } + + fun initAppEventData(json: JSONObject) { + try { + MyHttpUtil.mInstance.postSaveAppData( + json, + object : okhttp3.Callback { + override fun onFailure(call: Call, e: IOException) { + LogTag.LogD(TAG, "AppEventData onFailure->${e}") + } + + override fun onResponse(call: Call, response: Response) { + try { + LogTag.LogD(TAG, "AppEventData response->${response}") + if (response.code == 200) { + val responseData = response.body?.string() + if (responseData != null) { + val jsonObject = JSONObject(responseData) + val status = jsonObject.getString("status") + LogTag.LogD(TAG, "AppEventData jsonObject->${jsonObject}") + LogTag.LogD(TAG, "AppEventData status->${status}") + } + } + } catch (e: Exception) { + e.printStackTrace() + } + } + }) + } catch (e: Exception) { + LogTag.LogE(TAG, e.toString()) + } + } + +} \ No newline at end of file diff --git a/app/src/main/java/relax/offline/music/service/PlaybackService.kt b/app/src/main/java/relax/offline/music/service/PlaybackService.kt index 57a67af..2e5b73f 100644 --- a/app/src/main/java/relax/offline/music/service/PlaybackService.kt +++ b/app/src/main/java/relax/offline/music/service/PlaybackService.kt @@ -98,7 +98,7 @@ class PlaybackService : MediaSessionService(), Player.Listener { // setSmallIcon(R.mipmap.app_logo_img) // } setMediaNotificationProvider(DefaultMediaNotificationProvider(this).apply { - setSmallIcon(R.mipmap.app_logo) + setSmallIcon(R.mipmap.app_logo_no_bg) }) } diff --git a/app/src/main/java/relax/offline/music/sp/AppStore.kt b/app/src/main/java/relax/offline/music/sp/AppStore.kt index d4c8292..c51e26c 100644 --- a/app/src/main/java/relax/offline/music/sp/AppStore.kt +++ b/app/src/main/java/relax/offline/music/sp/AppStore.kt @@ -27,10 +27,33 @@ class AppStore(context: Context) { defaultValue = PlayMode.LIST_LOOP.value ) + var userID: String by store.string( + key = APP_USERID, + defaultValue = "" + ) + + var appUUID : String by store.string( + key = APP_UUID, + defaultValue = "" + ) + + var ipCountryCode: String by store.string( + key = IP_COUNTRY_CODE, + defaultValue = "" + ) + + var firstOpenIsSucceed : Boolean by store.boolean( + key = FIRST_OPEN_IS_SUCCEED, + defaultValue = false + ) companion object { private const val FILE_NAME = "music_oo_app" const val SEARCH_HISTORY = "search_history" const val MY_VISITOR_DATA = "my_visitor_data" const val PLAY_MUSIC_MODE = "play_music_mode" + const val APP_USERID = "app_userid" + const val APP_UUID = "app_uuid" + const val IP_COUNTRY_CODE = "ip_country_code" + const val FIRST_OPEN_IS_SUCCEED = "first_open_is_succeed" } } \ No newline at end of file diff --git a/app/src/main/java/relax/offline/music/util/AesEncryptUtil.java b/app/src/main/java/relax/offline/music/util/AesEncryptUtil.java new file mode 100644 index 0000000..4a2f669 --- /dev/null +++ b/app/src/main/java/relax/offline/music/util/AesEncryptUtil.java @@ -0,0 +1,64 @@ +package relax.offline.music.util; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; + +import relax.offline.music.http.BaseApiUtil; + +public class AesEncryptUtil { + + private static final String AES_MODE = "AES/CBC/NOPadding"; + + public static String encrypt(String data, String key, String iv) { + try { + Cipher cipher = Cipher.getInstance(AES_MODE); + int blockSize = cipher.getBlockSize(); + byte[] dataBytes = data.getBytes(); + int plaintextLength = dataBytes.length; + if (plaintextLength % blockSize != 0) { + plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize)); + } + byte[] plaintext = new byte[plaintextLength]; + System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); + SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); + IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); + cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); + byte[] encrypted = cipher.doFinal(plaintext); + return Base64.encodeBytes(encrypted); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + + public static String desEncrypt(String data) { + return desEncrypt(data, BaseApiUtil.key, BaseApiUtil.iv); + } + + /** + * 解密方法 + * + * @param data 要解密的数据 + * @param key 解密key + * @param iv 解密iv + * @return 解密的结果 + * @throws Exception + */ + public static String desEncrypt(String data, String key, String iv) { + try { + byte[] encrypted1 = Base64.decode(data); + Cipher cipher = Cipher.getInstance(AES_MODE); + SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); + IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); + cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); + byte[] original = cipher.doFinal(encrypted1); + String originalString = new String(original); + return originalString.trim(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/app/src/main/java/relax/offline/music/util/Base64.java b/app/src/main/java/relax/offline/music/util/Base64.java new file mode 100644 index 0000000..715d634 --- /dev/null +++ b/app/src/main/java/relax/offline/music/util/Base64.java @@ -0,0 +1,1426 @@ +package relax.offline.music.util; + +import java.nio.charset.StandardCharsets; + +public class Base64 { + public final static int NO_OPTIONS = 0; + public final static int ENCODE = 1; + public final static int DECODE = 0; + public final static int GZIP = 2; + public final static int DONT_GUNZIP = 4; + public final static int DO_BREAK_LINES = 8; + public final static int URL_SAFE = 16; + public final static int ORDERED = 32; + + + + + /** Maximum line length (76) of Base64 output. */ + private final static int MAX_LINE_LENGTH = 76; + + + /** The equals sign (=) as a byte. */ + private final static byte EQUALS_SIGN = (byte)'='; + + + /** The new line character (\n) as a byte. */ + private final static byte NEW_LINE = (byte)'\n'; + + + /** Preferred encoding. */ + private final static String PREFERRED_ENCODING = "US-ASCII"; + + + private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding + private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding + + + + /** The 64 valid Base64 values. */ + /* Host platform me be something funny like EBCDIC, so we hardcode these values. */ + private final static byte[] _STANDARD_ALPHABET = { + (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', + (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', + (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', + (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', + (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', + (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', + (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', + (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', + (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', + (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' + }; + + + /** + * Translates a Base64 value to either its 6-bit reconstruction value + * or a negative number indicating some other meaning. + **/ + private final static byte[] _STANDARD_DECODABET = { + -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 + -5,-5, // Whitespace: Tab and Linefeed + -9,-9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 + -9,-9,-9,-9,-9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 + 62, // Plus sign at decimal 43 + -9,-9,-9, // Decimal 44 - 46 + 63, // Slash at decimal 47 + 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine + -9,-9,-9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9,-9,-9, // Decimal 62 - 64 + 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' + 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' + -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 + 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' + 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' + -9,-9,-9,-9,-9 // Decimal 123 - 127 + ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 + }; + + +/* ******** U R L S A F E B A S E 6 4 A L P H A B E T ******** */ + + /** + * Used in the URL- and Filename-safe dialect described in Section 4 of RFC3548: + * http://www.faqs.org/rfcs/rfc3548.html. + * Notice that the last two bytes become "hyphen" and "underscore" instead of "plus" and "slash." + */ + private final static byte[] _URL_SAFE_ALPHABET = { + (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', + (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', + (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', + (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', + (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', + (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', + (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', + (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', + (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', + (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'-', (byte)'_' + }; + + /** + * Used in decoding URL- and Filename-safe dialects of Base64. + */ + private final static byte[] _URL_SAFE_DECODABET = { + -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 + -5,-5, // Whitespace: Tab and Linefeed + -9,-9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 + -9,-9,-9,-9,-9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 + -9, // Plus sign at decimal 43 + -9, // Decimal 44 + 62, // Minus sign at decimal 45 + -9, // Decimal 46 + -9, // Slash at decimal 47 + 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine + -9,-9,-9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9,-9,-9, // Decimal 62 - 64 + 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' + 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' + -9,-9,-9,-9, // Decimal 91 - 94 + 63, // Underscore at decimal 95 + -9, // Decimal 96 + 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' + 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' + -9,-9,-9,-9,-9 // Decimal 123 - 127 + ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 + }; + + + +/* ******** O R D E R E D B A S E 6 4 A L P H A B E T ******** */ + + /** + * I don't get the point of this technique, but someone requested it, + * and it is described here: + * http://www.faqs.org/qa/rfcc-1940.html. + */ + private final static byte[] _ORDERED_ALPHABET = { + (byte)'-', + (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', + (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', + (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', + (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', + (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', + (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', + (byte)'_', + (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', + (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', + (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', + (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z' + }; + + /** + * Used in decoding the "ordered" dialect of Base64. + */ + private final static byte[] _ORDERED_DECODABET = { + -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 + -5,-5, // Whitespace: Tab and Linefeed + -9,-9, // Decimal 11 - 12 + -5, // Whitespace: Carriage Return + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 + -9,-9,-9,-9,-9, // Decimal 27 - 31 + -5, // Whitespace: Space + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 + -9, // Plus sign at decimal 43 + -9, // Decimal 44 + 0, // Minus sign at decimal 45 + -9, // Decimal 46 + -9, // Slash at decimal 47 + 1,2,3,4,5,6,7,8,9,10, // Numbers zero through nine + -9,-9,-9, // Decimal 58 - 60 + -1, // Equals sign at decimal 61 + -9,-9,-9, // Decimal 62 - 64 + 11,12,13,14,15,16,17,18,19,20,21,22,23, // Letters 'A' through 'M' + 24,25,26,27,28,29,30,31,32,33,34,35,36, // Letters 'N' through 'Z' + -9,-9,-9,-9, // Decimal 91 - 94 + 37, // Underscore at decimal 95 + -9, // Decimal 96 + 38,39,40,41,42,43,44,45,46,47,48,49,50, // Letters 'a' through 'm' + 51,52,53,54,55,56,57,58,59,60,61,62,63, // Letters 'n' through 'z' + -9,-9,-9,-9,-9 // Decimal 123 - 127 + ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 + -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 + }; + + +/* ******** D E T E R M I N E W H I C H A L H A B E T ******** */ + + + /** + * Returns one of the _SOMETHING_ALPHABET byte arrays depending on + * the options specified. + * It's possible, though silly, to specify ORDERED and URLSAFE + * in which case one of them will be picked, though there is + * no guarantee as to which one will be picked. + */ + private final static byte[] getAlphabet( int options ) { + if ((options & URL_SAFE) == URL_SAFE) { + return _URL_SAFE_ALPHABET; + } else if ((options & ORDERED) == ORDERED) { + return _ORDERED_ALPHABET; + } else { + return _STANDARD_ALPHABET; + } + } // end getAlphabet + + private final static byte[] getDecodabet( int options ) { + if( (options & URL_SAFE) == URL_SAFE) { + return _URL_SAFE_DECODABET; + } else if ((options & ORDERED) == ORDERED) { + return _ORDERED_DECODABET; + } else { + return _STANDARD_DECODABET; + } + } // end getAlphabet + private Base64(){} + private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) { + encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); + return b4; + } // end encode3to4 + private static byte[] encode3to4( + byte[] source, int srcOffset, int numSigBytes, + byte[] destination, int destOffset, int options ) { + + byte[] ALPHABET = getAlphabet( options ); + int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) + | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) + | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); + + switch( numSigBytes ) + { + case 3: + destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; + destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; + destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; + destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; + return destination; + + case 2: + destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; + destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; + destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; + destination[ destOffset + 3 ] = EQUALS_SIGN; + return destination; + + case 1: + destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; + destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; + destination[ destOffset + 2 ] = EQUALS_SIGN; + destination[ destOffset + 3 ] = EQUALS_SIGN; + return destination; + + default: + return destination; + } // end switch + } // end encode3to4 + public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){ + byte[] raw3 = new byte[3]; + byte[] enc4 = new byte[4]; + + while( raw.hasRemaining() ){ + int rem = Math.min(3,raw.remaining()); + raw.get(raw3,0,rem); + Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); + encoded.put(enc4); + } // end input remaining + } + + + public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){ + byte[] raw3 = new byte[3]; + byte[] enc4 = new byte[4]; + + while( raw.hasRemaining() ){ + int rem = Math.min(3,raw.remaining()); + raw.get(raw3,0,rem); + Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); + for( int i = 0; i < 4; i++ ){ + encoded.put( (char)(enc4[i] & 0xFF) ); + } + } // end input remaining + } + public static String encodeObject( java.io.Serializable serializableObject ) + throws java.io.IOException { + return encodeObject( serializableObject, NO_OPTIONS ); + } // end encodeObject + + public static String encodeObject( java.io.Serializable serializableObject, int options ) + throws java.io.IOException { + + if( serializableObject == null ){ + throw new NullPointerException( "Cannot serialize a null object." ); + } // end if: null + + // Streams + java.io.ByteArrayOutputStream baos = null; + java.io.OutputStream b64os = null; + java.util.zip.GZIPOutputStream gzos = null; + java.io.ObjectOutputStream oos = null; + + + try { + baos = new java.io.ByteArrayOutputStream(); + b64os = new OutputStream( baos, ENCODE | options ); + if( (options & GZIP) != 0 ){ + gzos = new java.util.zip.GZIPOutputStream(b64os); + oos = new java.io.ObjectOutputStream( gzos ); + } else { + // Not gzipped + oos = new java.io.ObjectOutputStream( b64os ); + } + oos.writeObject( serializableObject ); + } // end try + catch( java.io.IOException e ) { + throw e; + } // end catch + finally { + try{ oos.close(); } catch( Exception e ){} + try{ gzos.close(); } catch( Exception e ){} + try{ b64os.close(); } catch( Exception e ){} + try{ baos.close(); } catch( Exception e ){} + } // end finally + try { + return new String( baos.toByteArray(), PREFERRED_ENCODING ); + } // end try + catch (java.io.UnsupportedEncodingException uue){ + // Fall back to some Java default + return new String( baos.toByteArray() ); + } // end catch + + } // end encode + + + + public static String encodeBytes( byte[] source ) { + // Since we're not going to have the GZIP encoding turned on, + // we're not going to have an java.io.IOException thrown, so + // we should not force the user to have to catch it. + String encoded = null; + try { + encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); + } catch (java.io.IOException ex) { + assert false : ex.getMessage(); + } // end catch + assert encoded != null; + return encoded; + } // end encodeBytes + public static String encodeBytes( byte[] source, int options ) throws java.io.IOException { + return encodeBytes( source, 0, source.length, options ); + } // end encodeBytes + + public static String encodeBytes( byte[] source, int off, int len ) { + // Since we're not going to have the GZIP encoding turned on, + // we're not going to have an java.io.IOException thrown, so + // we should not force the user to have to catch it. + String encoded = null; + try { + encoded = encodeBytes( source, off, len, NO_OPTIONS ); + } catch (java.io.IOException ex) { + assert false : ex.getMessage(); + } // end catch + assert encoded != null; + return encoded; + } // end encodeBytes + + public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { + byte[] encoded = encodeBytesToBytes( source, off, len, options ); + + // Return value according to relevant encoding. + try { + return new String( encoded, PREFERRED_ENCODING ); + } // end try + catch (java.io.UnsupportedEncodingException uue) { + return new String( encoded ); + } // end catch + + } // end encodeBytes + public static byte[] encodeBytesToBytes( byte[] source ) { + byte[] encoded = null; + try { + encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS ); + } catch( java.io.IOException ex ) { + assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); + } + return encoded; + } + + public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { + + if( source == null ){ + throw new NullPointerException( "Cannot serialize a null array." ); + } // end if: null + + if( off < 0 ){ + throw new IllegalArgumentException( "Cannot have negative offset: " + off ); + } // end if: off < 0 + + if( len < 0 ){ + throw new IllegalArgumentException( "Cannot have length offset: " + len ); + } // end if: len < 0 + + if( off + len > source.length ){ + throw new IllegalArgumentException( + String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); + } // end if: off < 0 + + + + // Compress? + if( (options & GZIP) != 0 ) { + java.io.ByteArrayOutputStream baos = null; + java.util.zip.GZIPOutputStream gzos = null; + OutputStream b64os = null; + + try { + // GZip -> Base64 -> ByteArray + baos = new java.io.ByteArrayOutputStream(); + b64os = new OutputStream( baos, ENCODE | options ); + gzos = new java.util.zip.GZIPOutputStream( b64os ); + + gzos.write( source, off, len ); + gzos.close(); + } // end try + catch( java.io.IOException e ) { + // Catch it and then throw it immediately so that + // the finally{} block is called for cleanup. + throw e; + } // end catch + finally { + try{ gzos.close(); } catch( Exception e ){} + try{ b64os.close(); } catch( Exception e ){} + try{ baos.close(); } catch( Exception e ){} + } // end finally + + return baos.toByteArray(); + } // end if: compress + + else { + boolean breakLines = (options & DO_BREAK_LINES) != 0; + + int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding + if( breakLines ){ + encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters + } + byte[] outBuff = new byte[ encLen ]; + + + int d = 0; + int e = 0; + int len2 = len - 2; + int lineLength = 0; + for( ; d < len2; d+=3, e+=4 ) { + encode3to4( source, d+off, 3, outBuff, e, options ); + + lineLength += 4; + if( breakLines && lineLength >= MAX_LINE_LENGTH ) + { + outBuff[e+4] = NEW_LINE; + e++; + lineLength = 0; + } // end if: end of line + } // en dfor: each piece of array + + if( d < len ) { + encode3to4( source, d+off, len - d, outBuff, e, options ); + e += 4; + } // end if: some padding needed + + if( e <= outBuff.length - 1 ){ + byte[] finalOut = new byte[e]; + System.arraycopy(outBuff,0, finalOut,0,e); + return finalOut; + } else { + return outBuff; + } + + } // end else: don't compress + + } // end encodeBytesToBytes + + + + + + private static int decode4to3( + byte[] source, int srcOffset, + byte[] destination, int destOffset, int options ) { + + // Lots of error checking and exception throwing + if( source == null ){ + throw new NullPointerException( "Source array was null." ); + } // end if + if( destination == null ){ + throw new NullPointerException( "Destination array was null." ); + } // end if + if( srcOffset < 0 || srcOffset + 3 >= source.length ){ + throw new IllegalArgumentException( String.format( + "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); + } // end if + if( destOffset < 0 || destOffset +2 >= destination.length ){ + throw new IllegalArgumentException( String.format( + "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); + } // end if + + + byte[] DECODABET = getDecodabet( options ); + + // Example: Dk== + if( source[ srcOffset + 2] == EQUALS_SIGN ) { + // Two ways to do the same thing. Don't know which way I like best. + //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) + // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); + int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) + | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); + + destination[ destOffset ] = (byte)( outBuff >>> 16 ); + return 1; + } + + // Example: DkL= + else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { + // Two ways to do the same thing. Don't know which way I like best. + //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) + // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) + // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); + int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) + | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) + | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); + + destination[ destOffset ] = (byte)( outBuff >>> 16 ); + destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); + return 2; + } + + // Example: DkLE + else { + // Two ways to do the same thing. Don't know which way I like best. + //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) + // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) + // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) + // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); + int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) + | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) + | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) + | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); + + + destination[ destOffset ] = (byte)( outBuff >> 16 ); + destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); + destination[ destOffset + 2 ] = (byte)( outBuff ); + + return 3; + } + } // end decodeToBytes + + + + + public static byte[] decode( byte[] source ) + throws java.io.IOException { + byte[] decoded = null; +// try { + decoded = decode( source, 0, source.length, Base64.NO_OPTIONS ); +// } catch( java.io.IOException ex ) { +// assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); +// } + return decoded; + } + public static byte[] decode( byte[] source, int off, int len, int options ) + throws java.io.IOException { + + // Lots of error checking and exception throwing + if( source == null ){ + throw new NullPointerException( "Cannot decode null source array." ); + } // end if + if( off < 0 || off + len > source.length ){ + throw new IllegalArgumentException( String.format( + "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) ); + } // end if + + if( len == 0 ){ + return new byte[0]; + }else if( len < 4 ){ + throw new IllegalArgumentException( + "Base64-encoded string must have at least four characters, but length specified was " + len ); + } // end if + + byte[] DECODABET = getDecodabet( options ); + + int len34 = len * 3 / 4; // Estimate on array size + byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output + int outBuffPosn = 0; // Keep track of where we're writing + + byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space + int b4Posn = 0; // Keep track of four byte input buffer + int i = 0; // Source array counter + byte sbiDecode = 0; // Special value from DECODABET + + for( i = off; i < off+len; i++ ) { // Loop through source + + sbiDecode = DECODABET[ source[i]&0xFF ]; + + // White space, Equals sign, or legit Base64 character + // Note the values such as -5 and -9 in the + // DECODABETs at the top of the file. + if( sbiDecode >= WHITE_SPACE_ENC ) { + if( sbiDecode >= EQUALS_SIGN_ENC ) { + b4[ b4Posn++ ] = source[i]; // Save non-whitespace + if( b4Posn > 3 ) { // Time to decode? + outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); + b4Posn = 0; + + // If that was the equals sign, break out of 'for' loop + if( source[i] == EQUALS_SIGN ) { + break; + } // end if: equals sign + } // end if: quartet built + } // end if: equals sign or better + } // end if: white space, equals sign or better + else { + // There's a bad input character in the Base64 stream. + throw new java.io.IOException( String.format( + "Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) ); + } // end else: + } // each input character + + byte[] out = new byte[ outBuffPosn ]; + System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); + return out; + } // end decode + public static byte[] decode( String s ) throws java.io.IOException { + return decode( s, NO_OPTIONS ); + } + public static byte[] decode( String s, int options ) throws java.io.IOException { + + if( s == null ){ + throw new NullPointerException( "Input string was null." ); + } // end if + + byte[] bytes; + try { + bytes = s.getBytes( PREFERRED_ENCODING ); + } // end try + catch( java.io.UnsupportedEncodingException uee ) { + bytes = s.getBytes(); + } // end catch + // + + // Decode + bytes = decode( bytes, 0, bytes.length, options ); + + // Check to see if it's gzip-compressed + // GZIP Magic Two-Byte Number: 0x8b1f (35615) + boolean dontGunzip = (options & DONT_GUNZIP) != 0; + if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { + + int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); + if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { + java.io.ByteArrayInputStream bais = null; + java.util.zip.GZIPInputStream gzis = null; + java.io.ByteArrayOutputStream baos = null; + byte[] buffer = new byte[2048]; + int length = 0; + + try { + baos = new java.io.ByteArrayOutputStream(); + bais = new java.io.ByteArrayInputStream( bytes ); + gzis = new java.util.zip.GZIPInputStream( bais ); + + while( ( length = gzis.read( buffer ) ) >= 0 ) { + baos.write(buffer,0,length); + } // end while: reading input + + // No error? Get new bytes. + bytes = baos.toByteArray(); + + } // end try + catch( java.io.IOException e ) { + e.printStackTrace(); + // Just return originally-decoded bytes + } // end catch + finally { + try{ baos.close(); } catch( Exception e ){} + try{ gzis.close(); } catch( Exception e ){} + try{ bais.close(); } catch( Exception e ){} + } // end finally + + } // end if: gzipped + } // end if: bytes.length >= 2 + + return bytes; + } // end decode + public static Object decodeToObject( String encodedObject ) + throws java.io.IOException, ClassNotFoundException { + return decodeToObject(encodedObject,NO_OPTIONS,null); + } + public static Object decodeToObject( + String encodedObject, int options, final ClassLoader loader ) + throws java.io.IOException, ClassNotFoundException { + + // Decode and gunzip if necessary + byte[] objBytes = decode( encodedObject, options ); + + java.io.ByteArrayInputStream bais = null; + java.io.ObjectInputStream ois = null; + Object obj = null; + + try { + bais = new java.io.ByteArrayInputStream( objBytes ); + + // If no custom class loader is provided, use Java's builtin OIS. + if( loader == null ){ + ois = new java.io.ObjectInputStream( bais ); + } // end if: no loader provided + + // Else make a customized object input stream that uses + // the provided class loader. + else { + ois = new java.io.ObjectInputStream(bais){ + @Override + public Class resolveClass(java.io.ObjectStreamClass streamClass) + throws java.io.IOException, ClassNotFoundException { + Class c = Class.forName(streamClass.getName(), false, loader); + if( c == null ){ + return super.resolveClass(streamClass); + } else { + return c; // Class loader knows of this class. + } // end else: not null + } // end resolveClass + }; // end ois + } // end else: no custom class loader + + obj = ois.readObject(); + } // end try + catch( java.io.IOException e ) { + throw e; // Catch and throw in order to execute finally{} + } // end catch + catch( ClassNotFoundException e ) { + throw e; // Catch and throw in order to execute finally{} + } // end catch + finally { + try{ bais.close(); } catch( Exception e ){} + try{ ois.close(); } catch( Exception e ){} + } // end finally + + return obj; + } // end decodeObject + public static void encodeToFile( byte[] dataToEncode, String filename ) + throws java.io.IOException { + + if( dataToEncode == null ){ + throw new NullPointerException( "Data to encode was null." ); + } // end iff + + OutputStream bos = null; + try { + bos = new OutputStream( + new java.io.FileOutputStream( filename ), Base64.ENCODE ); + bos.write( dataToEncode ); + } // end try + catch( java.io.IOException e ) { + throw e; // Catch and throw to execute finally{} block + } // end catch: java.io.IOException + finally { + try{ bos.close(); } catch( Exception e ){} + } // end finally + + } // end encodeToFile + public static void decodeToFile( String dataToDecode, String filename ) + throws java.io.IOException { + + OutputStream bos = null; + try{ + bos = new OutputStream( + new java.io.FileOutputStream( filename ), Base64.DECODE ); + bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); + } // end try + catch( java.io.IOException e ) { + throw e; // Catch and throw to execute finally{} block + } // end catch: java.io.IOException + finally { + try{ bos.close(); } catch( Exception e ){} + } // end finally + + } // end decodeToFile + + + + + /** + * Convenience method for reading a base64-encoded + * file and decoding it. + * + *

As of v 2.3, if there is a error, + * the method will throw an java.io.IOException. This is new to v2.3! + * In earlier versions, it just returned false, but + * in retrospect that's a pretty poor way to handle it.

+ * + * @param filename Filename for reading encoded data + * @return decoded byte array + * @throws java.io.IOException if there is an error + * @since 2.1 + */ + public static byte[] decodeFromFile( String filename ) + throws java.io.IOException { + + byte[] decodedData = null; + InputStream bis = null; + try + { + // Set up some useful variables + java.io.File file = new java.io.File( filename ); + byte[] buffer = null; + int length = 0; + int numBytes = 0; + + // Check for size of file + if( file.length() > Integer.MAX_VALUE ) + { + throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." ); + } // end if: file too big for int index + buffer = new byte[ (int)file.length() ]; + + // Open a stream + bis = new InputStream( + new java.io.BufferedInputStream( + new java.io.FileInputStream( file ) ), Base64.DECODE ); + + // Read until done + while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { + length += numBytes; + } // end while + + // Save in a variable to return + decodedData = new byte[ length ]; + System.arraycopy( buffer, 0, decodedData, 0, length ); + + } // end try + catch( java.io.IOException e ) { + throw e; // Catch and release to execute finally{} + } // end catch: java.io.IOException + finally { + try{ bis.close(); } catch( Exception e) {} + } // end finally + + return decodedData; + } // end decodeFromFile + + + + /** + * Convenience method for reading a binary file + * and base64-encoding it. + * + *

As of v 2.3, if there is a error, + * the method will throw an java.io.IOException. This is new to v2.3! + * In earlier versions, it just returned false, but + * in retrospect that's a pretty poor way to handle it.

+ * + * @param filename Filename for reading binary data + * @return base64-encoded string + * @throws java.io.IOException if there is an error + * @since 2.1 + */ + public static String encodeFromFile( String filename ) + throws java.io.IOException { + + String encodedData = null; + InputStream bis = null; + try + { + // Set up some useful variables + java.io.File file = new java.io.File( filename ); + byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5) + int length = 0; + int numBytes = 0; + + // Open a stream + bis = new InputStream( + new java.io.BufferedInputStream( + new java.io.FileInputStream( file ) ), Base64.ENCODE ); + + // Read until done + while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { + length += numBytes; + } // end while + + // Save in a variable to return + encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); + + } // end try + catch( java.io.IOException e ) { + throw e; // Catch and release to execute finally{} + } // end catch: java.io.IOException + finally { + try{ bis.close(); } catch( Exception e) {} + } // end finally + + return encodedData; + } // end encodeFromFile + + /** + * Reads infile and encodes it to outfile. + * + * @param infile Input file + * @param outfile Output file + * @throws java.io.IOException if there is an error + * @since 2.2 + */ + public static void encodeFileToFile( String infile, String outfile ) + throws java.io.IOException { + + String encoded = Base64.encodeFromFile( infile ); + java.io.OutputStream out = null; + try{ + out = new java.io.BufferedOutputStream( + new java.io.FileOutputStream( outfile ) ); + out.write( encoded.getBytes(StandardCharsets.US_ASCII) ); // Strict, 7-bit output. + } // end try + catch( java.io.IOException e ) { + throw e; // Catch and release to execute finally{} + } // end catch + finally { + try { out.close(); } + catch( Exception ex ){} + } // end finally + } // end encodeFileToFile + + + /** + * Reads infile and decodes it to outfile. + * + * @param infile Input file + * @param outfile Output file + * @throws java.io.IOException if there is an error + * @since 2.2 + */ + public static void decodeFileToFile( String infile, String outfile ) + throws java.io.IOException { + + byte[] decoded = Base64.decodeFromFile( infile ); + java.io.OutputStream out = null; + try{ + out = new java.io.BufferedOutputStream( + new java.io.FileOutputStream( outfile ) ); + out.write( decoded ); + } // end try + catch( java.io.IOException e ) { + throw e; // Catch and release to execute finally{} + } // end catch + finally { + try { out.close(); } + catch( Exception ex ){} + } // end finally + } // end decodeFileToFile + + + /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ + + + + /** + * A {@link InputStream} will read data from another + * java.io.InputStream, given in the constructor, + * and encode/decode to/from Base64 notation on the fly. + * + * @see Base64 + * @since 1.3 + */ + public static class InputStream extends java.io.FilterInputStream { + + private boolean encode; // Encoding or decoding + private int position; // Current position in the buffer + private byte[] buffer; // Small buffer holding converted data + private int bufferLength; // Length of buffer (3 or 4) + private int numSigBytes; // Number of meaningful bytes in the buffer + private int lineLength; + private boolean breakLines; // Break lines at less than 80 characters + private int options; // Record options used to create the stream. + private byte[] decodabet; // Local copies to avoid extra method calls + + + /** + * Constructs a {@link InputStream} in DECODE mode. + * + * @param in the java.io.InputStream from which to read data. + * @since 1.3 + */ + public InputStream( java.io.InputStream in ) { + this( in, DECODE ); + } // end constructor + + + /** + * Constructs a {@link InputStream} in + * either ENCODE or DECODE mode. + *

+ * Valid options:

+         *   ENCODE or DECODE: Encode or Decode as data is read.
+         *   DO_BREAK_LINES: break lines at 76 characters
+         *     (only meaningful when encoding)
+         * 
+ *

+ * Example: new Base64.InputStream( in, Base64.DECODE ) + * + * + * @param in the java.io.InputStream from which to read data. + * @param options Specified options + * @see Base64#ENCODE + * @see Base64#DECODE + * @see Base64#DO_BREAK_LINES + * @since 2.0 + */ + public InputStream( java.io.InputStream in, int options ) { + + super( in ); + this.options = options; // Record for later + this.breakLines = (options & DO_BREAK_LINES) > 0; + this.encode = (options & ENCODE) > 0; + this.bufferLength = encode ? 4 : 3; + this.buffer = new byte[ bufferLength ]; + this.position = -1; + this.lineLength = 0; + this.decodabet = getDecodabet(options); + } // end constructor + + /** + * Reads enough of the input stream to convert + * to/from Base64 and returns the next byte. + * + * @return next byte + * @since 1.3 + */ + @Override + public int read() throws java.io.IOException { + + // Do we need to get data? + if( position < 0 ) { + if( encode ) { + byte[] b3 = new byte[3]; + int numBinaryBytes = 0; + for( int i = 0; i < 3; i++ ) { + int b = in.read(); + + // If end of stream, b is -1. + if( b >= 0 ) { + b3[i] = (byte)b; + numBinaryBytes++; + } else { + break; // out of for loop + } // end else: end of stream + + } // end for: each needed input byte + + if( numBinaryBytes > 0 ) { + encode3to4( b3, 0, numBinaryBytes, buffer, 0, options ); + position = 0; + numSigBytes = 4; + } // end if: got data + else { + return -1; // Must be end of stream + } // end else + } // end if: encoding + + // Else decoding + else { + byte[] b4 = new byte[4]; + int i = 0; + for( i = 0; i < 4; i++ ) { + // Read four "meaningful" bytes: + int b = 0; + do{ b = in.read(); } + while( b >= 0 && decodabet[ b & 0x7f ] <= WHITE_SPACE_ENC ); + + if( b < 0 ) { + break; // Reads a -1 if end of stream + } // end if: end of stream + + b4[i] = (byte)b; + } // end for: each needed input byte + + if( i == 4 ) { + numSigBytes = decode4to3( b4, 0, buffer, 0, options ); + position = 0; + } // end if: got four characters + else if( i == 0 ){ + return -1; + } // end else if: also padded correctly + else { + // Must have broken out from above. + throw new java.io.IOException( "Improperly padded Base64 input." ); + } // end + + } // end else: decode + } // end else: get data + + // Got data? + if( position >= 0 ) { + // End of relevant data? + if( /*!encode &&*/ position >= numSigBytes ){ + return -1; + } // end if: got data + + if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { + lineLength = 0; + return '\n'; + } // end if + else { + lineLength++; // This isn't important when decoding + // but throwing an extra "if" seems + // just as wasteful. + + int b = buffer[ position++ ]; + + if( position >= bufferLength ) { + position = -1; + } // end if: end + + return b & 0xFF; // This is how you "cast" a byte that's + // intended to be unsigned. + } // end else + } // end if: position >= 0 + + // Else error + else { + throw new java.io.IOException( "Error in Base64 code reading stream." ); + } // end else + } // end read + + + /** + * Calls {@link #read()} repeatedly until the end of stream + * is reached or len bytes are read. + * Returns number of bytes read into array or -1 if + * end of stream is encountered. + * + * @param dest array to hold values + * @param off offset for array + * @param len max number of bytes to read into array + * @return bytes read into array or -1 if end of stream is encountered. + * @since 1.3 + */ + @Override + public int read( byte[] dest, int off, int len ) + throws java.io.IOException { + int i; + int b; + for( i = 0; i < len; i++ ) { + b = read(); + + if( b >= 0 ) { + dest[off + i] = (byte) b; + } + else if( i == 0 ) { + return -1; + } + else { + break; // Out of 'for' loop + } // Out of 'for' loop + } // end for: each byte read + return i; + } // end read + + } // end inner class InputStream + + + + + + + /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ + + + + /** + * A {@link OutputStream} will write data to another + * java.io.OutputStream, given in the constructor, + * and encode/decode to/from Base64 notation on the fly. + * + * @see Base64 + * @since 1.3 + */ + public static class OutputStream extends java.io.FilterOutputStream { + + private boolean encode; + private int position; + private byte[] buffer; + private int bufferLength; + private int lineLength; + private boolean breakLines; + private byte[] b4; // Scratch used in a few places + private boolean suspendEncoding; + private int options; // Record for later + private byte[] decodabet; // Local copies to avoid extra method calls + + /** + * Constructs a {@link OutputStream} in ENCODE mode. + * + * @param out the java.io.OutputStream to which data will be written. + * @since 1.3 + */ + public OutputStream( java.io.OutputStream out ) { + this( out, ENCODE ); + } // end constructor + + + /** + * Constructs a {@link OutputStream} in + * either ENCODE or DECODE mode. + *

+ * Valid options:

+         *   ENCODE or DECODE: Encode or Decode as data is read.
+         *   DO_BREAK_LINES: don't break lines at 76 characters
+         *     (only meaningful when encoding)
+         * 
+ *

+ * Example: new Base64.OutputStream( out, Base64.ENCODE ) + * + * @param out the java.io.OutputStream to which data will be written. + * @param options Specified options. + * @see Base64#ENCODE + * @see Base64#DECODE + * @see Base64#DO_BREAK_LINES + * @since 1.3 + */ + public OutputStream( java.io.OutputStream out, int options ) { + super( out ); + this.breakLines = (options & DO_BREAK_LINES) != 0; + this.encode = (options & ENCODE) != 0; + this.bufferLength = encode ? 3 : 4; + this.buffer = new byte[ bufferLength ]; + this.position = 0; + this.lineLength = 0; + this.suspendEncoding = false; + this.b4 = new byte[4]; + this.options = options; + this.decodabet = getDecodabet(options); + } // end constructor + + + /** + * Writes the byte to the output stream after + * converting to/from Base64 notation. + * When encoding, bytes are buffered three + * at a time before the output stream actually + * gets a write() call. + * When decoding, bytes are buffered four + * at a time. + * + * @param theByte the byte to write + * @since 1.3 + */ + @Override + public void write(int theByte) + throws java.io.IOException { + // Encoding suspended? + if( suspendEncoding ) { + this.out.write( theByte ); + return; + } // end if: supsended + + // Encode? + if( encode ) { + buffer[ position++ ] = (byte)theByte; + if( position >= bufferLength ) { // Enough to encode. + + this.out.write( encode3to4( b4, buffer, bufferLength, options ) ); + + lineLength += 4; + if( breakLines && lineLength >= MAX_LINE_LENGTH ) { + this.out.write( NEW_LINE ); + lineLength = 0; + } // end if: end of line + + position = 0; + } // end if: enough to output + } // end if: encoding + + // Else, Decoding + else { + // Meaningful Base64 character? + if( decodabet[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { + buffer[ position++ ] = (byte)theByte; + if( position >= bufferLength ) { // Enough to output. + + int len = Base64.decode4to3( buffer, 0, b4, 0, options ); + out.write( b4, 0, len ); + position = 0; + } // end if: enough to output + } // end if: meaningful base64 character + else if( decodabet[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { + throw new java.io.IOException( "Invalid character in Base64 data." ); + } // end else: not white space either + } // end else: decoding + } // end write + + + + /** + * Calls {@link #write(int)} repeatedly until len + * bytes are written. + * + * @param theBytes array from which to read bytes + * @param off offset for array + * @param len max number of bytes to read into array + * @since 1.3 + */ + @Override + public void write( byte[] theBytes, int off, int len ) + throws java.io.IOException { + // Encoding suspended? + if( suspendEncoding ) { + this.out.write( theBytes, off, len ); + return; + } // end if: supsended + + for( int i = 0; i < len; i++ ) { + write( theBytes[ off + i ] ); + } // end for: each byte written + + } // end write + + + + /** + * Method added by PHIL. [Thanks, PHIL. -Rob] + * This pads the buffer without closing the stream. + * @throws java.io.IOException if there's an error. + */ + public void flushBase64() throws java.io.IOException { + if( position > 0 ) { + if( encode ) { + out.write( encode3to4( b4, buffer, position, options ) ); + position = 0; + } // end if: encoding + else { + throw new java.io.IOException( "Base64 input not properly padded." ); + } // end else: decoding + } // end if: buffer partially full + + } // end flush + + + /** + * Flushes and closes (I think, in the superclass) the stream. + * + * @since 1.3 + */ + @Override + public void close() throws java.io.IOException { + // 1. Ensure that pending characters are written + flushBase64(); + + // 2. Actually close the stream + // Base class both flushes and closes. + super.close(); + + buffer = null; + out = null; + } // end close + + + + /** + * Suspends encoding of the stream. + * May be helpful if you need to embed a piece of + * base64-encoded data in a stream. + * + * @throws java.io.IOException if there's an error flushing + * @since 1.5.1 + */ + public void suspendEncoding() throws java.io.IOException { + flushBase64(); + this.suspendEncoding = true; + } // end suspendEncoding + + + /** + * Resumes encoding of the stream. + * May be helpful if you need to embed a piece of + * base64-encoded data in a stream. + * + * @since 1.5.1 + */ + public void resumeEncoding() { + this.suspendEncoding = false; + } // end resumeEncoding + + + + } // end inner class OutputStream +} diff --git a/app/src/main/java/relax/offline/music/util/DownloadUtil.kt b/app/src/main/java/relax/offline/music/util/DownloadUtil.kt index 29df1a6..1d3c053 100644 --- a/app/src/main/java/relax/offline/music/util/DownloadUtil.kt +++ b/app/src/main/java/relax/offline/music/util/DownloadUtil.kt @@ -171,7 +171,7 @@ object DownloadUtil { return isExist } - fun getCurrentIdDownloadState(id: String): Int { + fun getCurrentIdDownload(id: String): Download? { if (downloadManager != null) { val downloadIndex = downloadManager!!.downloadIndex downloadIndex.getDownloads() @@ -179,12 +179,12 @@ object DownloadUtil { while (cursor.moveToNext()) { val download = cursor.download if (download.request.id == id) { - return download.state + return download } } } } - return -1 + return null } fun getDownloadCount(): Int { diff --git a/app/src/main/java/relax/offline/music/util/LogTag.kt b/app/src/main/java/relax/offline/music/util/LogTag.kt index ec7da78..b5413d2 100644 --- a/app/src/main/java/relax/offline/music/util/LogTag.kt +++ b/app/src/main/java/relax/offline/music/util/LogTag.kt @@ -1,6 +1,7 @@ package relax.offline.music.util import android.util.Log +import relax.offline.music.BuildConfig object LogTag { const val VO_ACT_LOG = "vo-act—log" @@ -11,14 +12,14 @@ object LogTag { const val VO_TEST_ONLY = "vo-only—log" fun LogD(tag: String, message: String) { - Log.d(tag, message) + if (BuildConfig.DEBUG) { + Log.d(tag, message) + } } fun LogE(tag: String, message: String) { - Log.e(tag, message) - } - - fun LogI(tag: String, message: String) { - Log.i(tag, message) + if (BuildConfig.DEBUG) { + Log.e(tag, message) + } } } \ No newline at end of file diff --git a/app/src/main/java/relax/offline/music/view/SearchResultOptimalView.kt b/app/src/main/java/relax/offline/music/view/SearchResultOptimalView.kt index 757b857..ca5433f 100644 --- a/app/src/main/java/relax/offline/music/view/SearchResultOptimalView.kt +++ b/app/src/main/java/relax/offline/music/view/SearchResultOptimalView.kt @@ -57,6 +57,16 @@ class SearchResultOptimalView(context: Context, data: Innertube.SearchDataPage) ) context.startActivity(intent) } + + "MUSIC_PAGE_TYPE_PLAYLIST" -> { + val intent = Intent(context, MoListDetailsActivity::class.java) + intent.putExtra( + MoListDetailsActivity.PLAY_LIST_PAGE_BROWSE_ID, + optimalBean.browseId + ) + context.startActivity(intent) + } + else -> { val intent = Intent(context, MoSingerDetailsActivity::class.java) intent.putExtra( diff --git a/app/src/main/res/layout/fragment_import.xml b/app/src/main/res/layout/fragment_import.xml index 3ab34a1..db277f9 100644 --- a/app/src/main/res/layout/fragment_import.xml +++ b/app/src/main/res/layout/fragment_import.xml @@ -78,6 +78,7 @@ android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" + android:orientation="vertical" android:visibility="visible"> New playlist You haven\'t liked any songs yet. You haven\'t saved any songs for offline listening yet. + It looks like there\'s no data. Please add some and try again. + Prompt \ No newline at end of file