Skip to content
This repository has been archived by the owner on Jan 25, 2024. It is now read-only.

Commit

Permalink
refactor 2
Browse files Browse the repository at this point in the history
  • Loading branch information
boyan01 committed Feb 22, 2020
1 parent 781f2a6 commit ed4f6b2
Show file tree
Hide file tree
Showing 11 changed files with 63 additions and 172 deletions.
4 changes: 2 additions & 2 deletions android/gradle.properties
@@ -1,5 +1,5 @@
android.enableJetifier=true
android.useAndroidX=true
org.gradle.jvmargs=-Xmx1536M
#-DsocksProxyHost=127.0.0.1 -DsocksProxyPort=1080
#org.gradle.jvmargs=-Xmx1536M -DsocksProxyHost=127.0.0.1 -DsocksProxyPort=1080
android.enableR8=true
kotlin.code.style=official
4 changes: 2 additions & 2 deletions lib/component/player/bottom_player_bar.dart
Expand Up @@ -77,11 +77,11 @@ class BottomControllerBar extends StatelessWidget {
aspectRatio: 1,
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(3)),
child: music.description.iconUri == null
child: music.imageUrl == null
? Container(color: Colors.grey)
: Image(
fit: BoxFit.cover,
image: CachedImage(music.description.iconUri.toString()),
image: CachedImage(music.imageUrl),
),
),
),
Expand Down
6 changes: 3 additions & 3 deletions lib/component/player/interceptors.dart
Expand Up @@ -16,8 +16,8 @@ class BackgroundInterceptors {
return result.asValue.value;
}

static Future<Uint8List> loadImageInterceptor(MediaDescription description) async {
final ImageStream stream = CachedImage(description.iconUri.toString()).resolve(ImageConfiguration(
static Future<Uint8List> loadImageInterceptor(MusicMetadata metadata) async {
final ImageStream stream = CachedImage(metadata.iconUri.toString()).resolve(ImageConfiguration(
size: const Size(150, 150),
devicePixelRatio: WidgetsBinding.instance.window.devicePixelRatio,
));
Expand All @@ -31,7 +31,7 @@ class BackgroundInterceptors {
.then((image) => image.image.toByteData(format: ImageByteFormat.png))
.then((byte) => byte.buffer.asUint8List())
.timeout(const Duration(seconds: 10));
debugPrint("load image for : ${description.title} ${result.length}");
debugPrint("load image for : ${metadata.title} ${result.length}");
return result;
}
}
43 changes: 9 additions & 34 deletions lib/component/player/player.dart
Expand Up @@ -52,9 +52,9 @@ extension QuitPlayerExt on BuildContext {
return ScopedModel.of<QuietModel>(this, rebuildOnChange: true).player.value;
}

PlaybackState get playbackState => playerValue.playbackState;
PlaybackState get playbackState => playerValue.state;

PlayList get playList => playerValue.playList;
PlayQueue get playList => playerValue.queue;
}

extension MusicPlayerExt on MusicPlayer {
Expand All @@ -66,51 +66,26 @@ extension MusicPlayerValueExt on MusicPlayerValue {
///might be null
Music get current => Music.fromMetadata(metadata);

List<Music> get playingList => playList.queue.map((e) => Music.fromMetadata(e)).toList();
List<Music> get playingList => queue.queue.map((e) => Music.fromMetadata(e)).toList();
}

extension PlaybackStateExt on PlaybackState {
bool get hasError => state == PlaybackState.STATE_ERROR;
bool get hasError => state == PlayerState.Error;

bool get isPlaying => (state == PlaybackState.STATE_PLAYING) && !hasError;
bool get isPlaying => (state == PlayerState.Playing) && !hasError;

///audio is buffering
bool get isBuffering => state == PlaybackState.STATE_BUFFERING;
bool get isBuffering => state == PlayerState.Buffering;

bool get initialized => state != PlaybackState.STATE_NONE;
bool get initialized => state != PlayerState.None;

/// Current real position
int get positionWithOffset => position + (DateTime.now().millisecondsSinceEpoch - lastPositionUpdateTime);
int get positionWithOffset => position + (DateTime.now().millisecondsSinceEpoch - updateTime);
}

@visibleForTesting
class QuietModel extends Model {
MusicPlayer player = MusicPlayer(onServiceConnected: (player) async {
if (player.value.playList.queue.isNotEmpty && player.value.metadata != null) {
return;
}
// try {
// //load former player information from SharedPreference
// var preference = await SharedPreferences.getInstance();
// final playingMediaId = preference.getString(_PREF_KEY_PLAYING);
// final token = preference.getString(_PREF_KEY_TOKEN);
// final playingList = (json.decode(preference.get(_PREF_KEY_PLAYLIST)) as List)
// ?.cast<Map>()
// ?.map((e) => MediaMetadata.fromMap(e))
// ?.toList();
// final playMode = PlayMode.values[preference.getInt(_PREF_KEY_PLAY_MODE) ?? 0];
// player.transportControls
// ..setPlayMode(playMode)
// ..prepareFromMediaId(playingMediaId);
// debugPrint("loaded : $playingMediaId");
// debugPrint("loaded : $playingList");
// debugPrint("loaded : $token");
// debugPrint("loaded : $playMode");
// } catch (e, stacktrace) {
// debugPrint(e.toString());
// debugPrint(stacktrace.toString());
// }
});
MusicPlayer player = MusicPlayer();

QuietModel() {
player.addListener(() {
Expand Down
72 changes: 19 additions & 53 deletions lib/model/music.dart
@@ -1,11 +1,17 @@
import 'dart:convert';

import 'package:music_player/music_player.dart';

import 'model.dart';

class Music {
Music({this.id, this.title, this.url, this.album, this.artist, int mvId}) : this.mvId = mvId ?? 0;
Music({
this.id,
this.title,
this.url,
this.album,
this.artist,
int mvId,
this.imageUrl,
}) : this.mvId = mvId ?? 0;

final int id;

Expand All @@ -20,21 +26,18 @@ class Music {
///歌曲mv id,当其为0时,表示没有mv
final int mvId;

MediaDescription get description => metadata.getDescription();
final String imageUrl;

MediaMetadata _metadata;
MusicMetadata _metadata;

MediaMetadata get metadata {
MusicMetadata get metadata {
if (_metadata != null) return _metadata;
_metadata = MediaMetadata(
_metadata = MusicMetadata(
mediaId: id.toString(),
title: title,
artist: json.encode(artist.map((e) => e.toMap()).toList()),
album: json.encode(album.toMap()),
albumArtUri: album.coverImageUrl,
mediaUri: url,
displayTitle: title,
displaySubtitle: subTitle,
subtitle: subTitle,
duration: 0,
extras: MusicExt(this).toMap(),
);
return _metadata;
}
Expand All @@ -56,11 +59,11 @@ class Music {
return 'Music{id: $id, title: $title, url: $url, album: $album, artist: $artist}';
}

factory Music.fromMetadata(MediaMetadata metadata) {
factory Music.fromMetadata(MusicMetadata metadata) {
if (metadata == null) {
return null;
}
return _MediaMetadataMusic(metadata);
return fromMap(metadata.extras);
}

static Music fromMap(Map map) {
Expand Down Expand Up @@ -91,46 +94,9 @@ extension MusicExt on Music {
}
}

extension MusicBuilder on MediaMetadata {
extension MusicBuilder on MusicMetadata {
/// convert metadata to [Music]
Music toMusic() {
return Music.fromMetadata(this);
}
}

class _MediaMetadataMusic extends Music {
@override
final MediaMetadata _metadata;

@override
MediaMetadata get metadata => _metadata;

_MediaMetadataMusic(this._metadata)
: album = Album.fromMap(json.decode(_metadata.album)),
artist = (json.decode(_metadata.artist) as List).cast<Map>().map((e) => Artist.fromMap(e)).toList();

@override
int get id => int.tryParse(description.mediaId);

@override
String get title => description.title;

@override
String get subTitle => description.subtitle;

@override
String get url => description.mediaUri.toString();

@override
final Album album;

@override
final List<Artist> artist;

//TODO MV ID
@override
int get mvId => 0;

@override
set _metadata(MediaMetadata __metadata) {}
}
33 changes: 11 additions & 22 deletions lib/pages/comments/page_comment.dart
Expand Up @@ -79,9 +79,7 @@ class _CommentInputState extends State<_CommentInput> {
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
border:
Border(top: BorderSide(color: Theme.of(context).dividerColor))),
decoration: BoxDecoration(border: Border(top: BorderSide(color: Theme.of(context).dividerColor))),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Expand All @@ -91,8 +89,7 @@ class _CommentInputState extends State<_CommentInput> {
child: TextField(
focusNode: _focusNode,
controller: _controller,
decoration:
InputDecoration(hintText: "随乐而起,有感而发", errorText: _error),
decoration: InputDecoration(hintText: "随乐而起,有感而发", errorText: _error),
),
)),
IconButton(
Expand All @@ -104,8 +101,7 @@ class _CommentInputState extends State<_CommentInput> {
}
_error = null;
_isPosting = true;
final result =
await _postComment(_controller.text, widget.threadId);
final result = await _postComment(_controller.text, widget.threadId);
if (result.isValue) {
_controller.text = "";
if (_focusNode.hasFocus) {
Expand All @@ -126,8 +122,7 @@ class _CommentInputState extends State<_CommentInput> {
}

class CommentThreadId {
CommentThreadId(this.id, this.type, {this.payload})
: assert(id != null && type != null);
CommentThreadId(this.id, this.type, {this.payload}) : assert(id != null && type != null);

final int id;

Expand Down Expand Up @@ -187,7 +182,7 @@ class CommentThreadPayload {

CommentThreadPayload.music(Music music)
: this.obj = music,
coverImage = music.description.iconUri?.toString(),
coverImage = music.imageUrl?.toString(),
title = music.title,
subtitle = music.subTitle;

Expand Down Expand Up @@ -220,27 +215,21 @@ enum CommentType {

///like or unlike a comment
///return true when operation succeed
Future<bool> _like(
bool like, int commentId, CommentThreadId commentThread) async {
Future<bool> _like(bool like, int commentId, CommentThreadId commentThread) async {
String op = like ? "like" : "unlike";
var result = await neteaseRepository.doRequest(
"https://music.163.com/weapi/v1/comment/$op",
{"threadId": commentThread.threadId, "commentId": commentId});
"https://music.163.com/weapi/v1/comment/$op", {"threadId": commentThread.threadId, "commentId": commentId});
return result.isValue;
}

///post comment to a comment thread
Future<Result<Map>> _postComment(
String content, CommentThreadId commentThread) async {
Future<Result<Map>> _postComment(String content, CommentThreadId commentThread) async {
return await neteaseRepository.doRequest(
"https://music.163.com/weapi/resource/comments/add",
{"content": content, "threadId": commentThread.threadId});
"https://music.163.com/weapi/resource/comments/add", {"content": content, "threadId": commentThread.threadId});
}

Future<bool> _deleteComment(
CommentThreadId commentThread, int commentId) async {
var result = await neteaseRepository.doRequest(
"https://music.163.com/weapi/resource/comments/delete",
Future<bool> _deleteComment(CommentThreadId commentThread, int commentId) async {
var result = await neteaseRepository.doRequest("https://music.163.com/weapi/resource/comments/delete",
{"commentId": commentId, "threadId": commentThread.threadId});
debugPrint("_deleteComment :$result");
return result.isValue;
Expand Down
5 changes: 3 additions & 2 deletions lib/pages/page_playing_list.dart
Expand Up @@ -112,7 +112,8 @@ class _Header extends StatelessWidget {
icon: Icon(Icons.delete_outline),
onPressed: () async {
Navigator.pop(context);
context.player.setPlayList(PlayList.empty());
//FIXME
// context.player.setPlayList(PlayList.empty());
})
],
),
Expand Down Expand Up @@ -178,7 +179,7 @@ class _MusicTile extends StatelessWidget {
IconButton(
icon: Icon(Icons.close),
onPressed: () {
context.player.removeQueueItem(music.metadata.mediaId);
context.player.removeMusicItem(music.metadata);
})
],
),
Expand Down
9 changes: 5 additions & 4 deletions lib/pages/player/cover.dart
Expand Up @@ -78,8 +78,9 @@ class _AlbumCoverState extends State<AlbumCover> with TickerProviderStateMixin {
return;
}
_previousNextDirty = false;
_previous = _player.playList.getPrevious(_current.metadata)?.toMusic();
_next = _player.playList.getNext(_current.metadata)?.toMusic();
//TODO fetch previous and next
_previous = null;
_next = null;
if (mounted) {
setState(() {});
}
Expand Down Expand Up @@ -337,10 +338,10 @@ class _RotationCoverImageState extends State<_RotationCoverImage> with SingleTic
@override
Widget build(BuildContext context) {
ImageProvider image;
if (widget.music == null || widget.music.description.iconUri == null) {
if (widget.music == null || widget.music.imageUrl == null) {
image = AssetImage("assets/playing_page_disc.png");
} else {
image = CachedImage(widget.music.description.iconUri.toString());
image = CachedImage(widget.music.imageUrl.toString());
}
return Transform.rotate(
angle: rotation,
Expand Down
2 changes: 1 addition & 1 deletion lib/pages/player/page_playing.dart
Expand Up @@ -341,7 +341,7 @@ class _BlurBackground extends StatelessWidget {
fit: StackFit.expand,
children: <Widget>[
Image(
image: CachedImage(music.description.iconUri.toString()),
image: CachedImage(music.imageUrl.toString()),
fit: BoxFit.cover,
height: 15,
width: 15,
Expand Down

0 comments on commit ed4f6b2

Please sign in to comment.