Skip to content
Merged
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
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# 更新日志

## 1.2.3

- 修复下载页展开后灰屏,简化专辑任务状态与操作。
- 减少启动日志开销,缓解资料加载卡顿。
- 修复下架内容反复重试,以及更新、订阅和评论加载异常。
- 修复 Android 外部目录音频打开与后台下载异常。
- 优化返回动画,播放界面支持平滑缩回常驻播放栏。

## 1.2.2

- 完善发现、分类、榜单、主播与专辑浏览。
Expand Down
9 changes: 5 additions & 4 deletions android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,6 @@
<action android:name="android.media.browse.MediaBrowserService" />
</intent-filter>
</service>
<service
android:name=".DownloadForegroundService"
android:exported="false"
android:foregroundServiceType="dataSync" />
<receiver
android:name="com.ryanheise.audioservice.MediaButtonReceiver"
android:exported="true"
Expand All @@ -59,6 +55,11 @@
android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" />
</provider>
<provider
android:name=".SharedAudioProvider"
android:authorities="${applicationId}.audio"
android:exported="false"
android:grantUriPermissions="true" />
<meta-data android:name="flutterEmbedding" android:value="2" />
</application>
<queries>
Expand Down
113 changes: 15 additions & 98 deletions android/app/src/main/kotlin/teikengstudio/xmplus/MainActivity.kt
Original file line number Diff line number Diff line change
@@ -1,18 +1,9 @@
package teikengstudio.xmplus

import android.Manifest
import android.app.NotificationManager
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.os.ResultReceiver
import android.provider.Settings
import android.provider.DocumentsContract
import android.widget.Toast
import android.content.ClipData
import android.content.Intent
import android.os.StatFs
import android.system.ErrnoException
Expand All @@ -32,8 +23,6 @@ import java.io.OutputStream
import java.util.concurrent.atomic.AtomicBoolean

class MainActivity : AudioServiceActivity() {
private var notificationPermissionResult: MethodChannel.Result? = null
private val notificationPermissionRequest = 2102
private val logExportRequest = 2103
private var pendingLogExport: LogExport? = null
private val updatePermissionRequest = 2104
Expand Down Expand Up @@ -73,11 +62,22 @@ class MainActivity : AudioServiceActivity() {
result.success(StatFs(File(path).canonicalPath).availableBytes)
}
"openAudioFile" -> {
val file = File(requireNotNull(call.argument<String>("path"))).canonicalFile
require(file.isFile) { "Audio file does not exist" }
val uri = FileProvider.getUriForFile(this, "$packageName.files", file)
val path = requireNotNull(call.argument<String>("path"))
val requested = Uri.parse(path)
val uri = if (requested.scheme == "content") {
requested
} else {
val file = (if (requested.scheme == "file") File(requireNotNull(requested.path)) else File(path)).canonicalFile
require(file.isFile && file.canRead()) { "Audio file does not exist or is not readable" }
try {
FileProvider.getUriForFile(this, "$packageName.files", file)
} catch (_: IllegalArgumentException) {
SharedAudioProvider.uriForFile(this, file)
}
}
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "audio/*")
clipData = ClipData.newRawUri("audio", uri)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
startActivity(Intent.createChooser(intent, "打开音频"))
Expand Down Expand Up @@ -172,77 +172,6 @@ class MainActivity : AudioServiceActivity() {
}
}
}
DownloadForegroundService.messenger = flutterEngine.dartExecutor.binaryMessenger
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, DownloadForegroundService.CHANNEL)
.setMethodCallHandler { call, result ->
try {
when (call.method) {
"downloadNotificationPermission" -> {
val enabled = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
getSystemService(NotificationManager::class.java).areNotificationsEnabled()
} else true
if (enabled || Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU ||
call.argument<Boolean>("request") != true) {
result.success(enabled)
} else if (notificationPermissionResult != null) {
result.error("permission_pending", "通知权限请求尚未结束", null)
} else {
notificationPermissionResult = result
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), notificationPermissionRequest)
}
}
"downloadForeground" -> {
val intent = Intent(this, DownloadForegroundService::class.java).apply {
putExtra("title", requireNotNull(call.argument<String>("title")))
putExtra("text", requireNotNull(call.argument<String>("text")))
putExtra("receivedBytes", requireNotNull(call.argument<Number>("receivedBytes")).toLong())
putExtra("totalBytes", call.argument<Number>("totalBytes")?.toLong() ?: 0L)
}
val service = DownloadForegroundService.instance
if (service != null) {
service.update(intent)
result.success(null)
} else {
intent.putExtra("reply", object : ResultReceiver(Handler(Looper.getMainLooper())) {
override fun onReceiveResult(code: Int, data: Bundle?) {
if (code == 0) result.success(null)
else result.error("download_foreground", data?.getString("error"), null)
}
})
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startForegroundService(intent)
else startService(intent)
}
}
"stopDownloadForeground" -> {
val service = DownloadForegroundService.instance
if (service != null) {
service.stopPresenting { result.success(null) }
} else {
stopService(Intent(this, DownloadForegroundService::class.java))
result.success(null)
}
}
"batteryOptimizationExempt" -> result.success(
getSystemService(PowerManager::class.java).isIgnoringBatteryOptimizations(packageName)
)
"requestBatteryOptimizationExemption" -> {
startActivity(Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS,
Uri.parse("package:$packageName")))
result.success(null)
}
"showDownloadBackgroundError" -> {
Toast.makeText(applicationContext, call.argument<String>("message"), Toast.LENGTH_LONG).show()
result.success(null)
}
else -> result.notImplemented()
}
} catch (error: Exception) {
if (call.method == "downloadForeground") {
Toast.makeText(applicationContext, "下载后台服务启动失败,请保持应用在前台:${error.message}", Toast.LENGTH_LONG).show()
}
result.error("android_background", error.message, null)
}
}
}

private fun openUpdateInstaller(file: File) {
Expand Down Expand Up @@ -443,19 +372,7 @@ class MainActivity : AudioServiceActivity() {
}.start()
}

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == notificationPermissionRequest) {
notificationPermissionResult?.success(
grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED
)
notificationPermissionResult = null
}
}

override fun onDestroy() {
notificationPermissionResult?.success(false)
notificationPermissionResult = null
pendingUpdate?.second?.error("update_install", "安装授权已中断,请重试", null)
pendingUpdate = null
pendingLogExport?.let {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
package teikengstudio.xmplus

import android.content.ContentProvider
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.MatrixCursor
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.util.Base64
import android.provider.OpenableColumns
import java.io.File
import java.io.FileNotFoundException
import java.security.MessageDigest

/** Shares only individual files explicitly opened by this app, never a storage root. */
class SharedAudioProvider : ContentProvider() {
companion object {
private const val FILES = "shared_audio_files"

fun uriForFile(context: Context, file: File): Uri {
require(file.isAbsolute && file.isFile && file.canRead()) { "Audio file is not readable" }
val path = file.canonicalPath
val id = Base64.encodeToString(
MessageDigest.getInstance("SHA-256").digest(path.toByteArray(Charsets.UTF_8)),
Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING
)
val files = context.getSharedPreferences(FILES, Context.MODE_PRIVATE)
if (files.getString(id, null) != path) {
check(files.edit().putString(id, path).commit()) { "Cannot register audio file for sharing" }
}
return Uri.Builder().scheme("content").authority("${context.packageName}.audio")
.appendPath(id).build()
}
}

override fun onCreate(): Boolean = true

private fun file(uri: Uri): File {
val context = requireNotNull(context)
if (uri.authority != "${context.packageName}.audio" || uri.pathSegments.size != 1) {
throw FileNotFoundException("Invalid audio URI")
}
val path = context.getSharedPreferences(FILES, Context.MODE_PRIVATE)
.getString(uri.lastPathSegment, null) ?: throw FileNotFoundException("Unknown audio URI")
val file = File(path)
if (file.canonicalPath != path || !file.isFile || !file.canRead()) {
throw FileNotFoundException("Audio file is no longer available")
}
return file
}

override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor {
if (mode != "r") throw SecurityException("Audio sharing is read-only")
return ParcelFileDescriptor.open(file(uri), ParcelFileDescriptor.MODE_READ_ONLY)
}

override fun getType(uri: Uri): String {
file(uri)
return "audio/*"
}

override fun query(uri: Uri, projection: Array<out String>?, selection: String?,
selectionArgs: Array<out String>?, sortOrder: String?): Cursor {
val file = file(uri)
val columns = (projection ?: arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE))
.filter { it == OpenableColumns.DISPLAY_NAME || it == OpenableColumns.SIZE }.toTypedArray()
return MatrixCursor(columns, 1).apply {
addRow(columns.map { if (it == OpenableColumns.DISPLAY_NAME) file.name else file.length() })
}
}

override fun insert(uri: Uri, values: ContentValues?): Uri = throw SecurityException("Read-only provider")
override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int =
throw SecurityException("Read-only provider")
override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int =
throw SecurityException("Read-only provider")
}
7 changes: 7 additions & 0 deletions lib/api/xmly_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -880,6 +880,12 @@ class XmlyClient {
definitive: true,
);
}
if (origin == mobile && code == '924')
throw const XmlyException(
'content_removed',
'该内容已下架',
definitive: true,
);
if (['5', '403', '726'].contains(code))
throw const XmlyException(
'permission_denied',
Expand Down Expand Up @@ -920,6 +926,7 @@ class XmlyClient {
'login_required',
'login_expired',
'permission_denied',
'content_removed',
'rate_limited',
}.contains(error.code)),
);
Expand Down
38 changes: 34 additions & 4 deletions lib/api/xmly_comments.dart
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,16 @@ class AlbumReview {
AlbumReviewReply? preview;
if (replies is List && replies.isNotEmpty) {
if (replies.first is! Map) throw XmlyComments._invalid;
preview = AlbumReviewReply.fromApi(xmlyMap(replies.first), commentId: id);
final reply = xmlyMap(replies.first);
// The reply-list endpoint's RootComment embeds only a reference, not a
// renderable preview. Full previews still require all reply fields.
if (reply.length == 2 &&
reply.containsKey('replyId') &&
reply['unFollowAnchor'] is bool) {
xmlyIdentifier('${reply['replyId'] ?? ''}');
} else {
preview = AlbumReviewReply.fromApi(reply, commentId: id);
}
}
return AlbumReview(
id: id,
Expand Down Expand Up @@ -414,13 +423,34 @@ class XmlyComments {
final pages = _count(data['maxPageId']);
_count(data['totalCount']);
final list = data['list'];
// A page past the current maxPageId is returned with the requested pageId
// and an empty list. Preserve those bounds rather than inventing a page.
if (pageId != page ||
size < 1 ||
size > requestedSize ||
(pages > 0 && page > pages) ||
list is! List ||
list.length > size) {
throw _invalid;
list.length > size ||
(pages > 0 && page > pages && list.isNotEmpty)) {
throw XmlyException(
'invalid_comments',
_invalid.message,
diagnostics: {
'requestedPage': page,
'requestedSize': requestedSize,
for (final key in [
'pageId',
'pageSize',
'maxPageId',
'totalCount',
'list',
])
key: _diagnosticField(
data[key],
present: data.containsKey(key),
includeNumber: true,
),
},
);
}
}

Expand Down
9 changes: 6 additions & 3 deletions lib/api/xmly_experience.dart
Original file line number Diff line number Diff line change
Expand Up @@ -828,7 +828,8 @@ class XmlyExperience {
'GET',
XmlyClient.mobile,
'/fsubscribe-web/subscribe/comprehensive/rank/$_stamp',
query: {'pageId': page, 'sign': 2, 'size': pageSize},
// sign=2 refreshes the first page even when pageId is greater than one.
query: {'pageId': page, 'sign': page == 1 ? 2 : 1, 'size': pageSize},
);
if (response['data'] is! Map<String, dynamic>) throw _invalid;
final data = response['data'] as Map<String, dynamic>;
Expand Down Expand Up @@ -1086,6 +1087,7 @@ class XmlyExperience {
if (!ids.add(track.id))
throw const XmlyException('repeated_page', '更新列表重复,请刷新后重试');
final timeline = _time(row['timeline']);
if (timeline <= 0) throw _invalid;
if (cursor != null && timeline > cursor) throw _invalid;
cursor = timeline;
items.add(
Expand All @@ -1095,13 +1097,14 @@ class XmlyExperience {
),
);
}
final more = _more(data);
// The live feed can advertise more for a subscribed account yet return an
// empty page without a cursor. There is no next request until a refresh.
final more = _more(data) && items.isNotEmpty;
// The live service may ignore timeline; do not present the repeated newest
// page as older updates or claim that the complete feed was loaded.
if (before != null && cursor != null && cursor >= before) {
throw const XmlyException('repeated_page', '暂时无法读取更早的更新,已保留当前列表');
}
if (more && (cursor == null || cursor <= 0)) throw _invalid;
return UpdatePage(items: items, hasMore: more, nextTimeline: cursor);
}
}
Loading
Loading