controller.dart 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import 'dart:convert';
  2. import 'package:get/get.dart';
  3. import 'package:web_socket_channel/io.dart';
  4. import './actions.dart' as actions;
  5. import './preferences.dart' as Preferences;
  6. class Player {
  7. double currentTime = 0;
  8. double seekTime = -1;
  9. String master;
  10. int songId;
  11. bool playing = false;
  12. List<int> queue = [];
  13. Map<String, dynamic> stringify() {
  14. return {
  15. 'currentTime': this.currentTime,
  16. 'seekTime': this.seekTime,
  17. 'master': this.master,
  18. 'songId': this.songId,
  19. 'playing': this.playing,
  20. 'queue': this.queue,
  21. };
  22. }
  23. }
  24. class Client {
  25. String name;
  26. int lastPing;
  27. Client(String name, int lastPing) {
  28. this.name = name;
  29. this.lastPing = lastPing;
  30. }
  31. }
  32. class Controller extends GetxController {
  33. RxString apiUrl = ''.obs;
  34. RxBool connected = false.obs;
  35. RxString name = ''.obs;
  36. RxString uniqueName = ''.obs;
  37. IOWebSocketChannel channel;
  38. Rx<Player> player = new Player().obs;
  39. RxList<Client> clients = <Client>[].obs;
  40. Controller({
  41. this.apiUrl,
  42. this.name,
  43. });
  44. setApiUrl(String apiUrl) {
  45. this.apiUrl = apiUrl.obs;
  46. Preferences.setApiUrl(apiUrl);
  47. }
  48. setName(String newName) {
  49. name.value = newName;
  50. Preferences.setClientName(newName);
  51. }
  52. setClients(List<Client> newClients) {
  53. this.clients.assignAll(newClients);
  54. }
  55. void _remoteDispatch(String action) {
  56. if (this.channel == null) {
  57. return;
  58. }
  59. this.channel.sink.add(action);
  60. }
  61. bool _isMaster() => this.uniqueName.value == this.player.value.master;
  62. void playPause() {
  63. this.player.value.playing = !this.player.value.playing;
  64. if (!this._isMaster()) {
  65. this._remoteDispatch(jsonEncode({
  66. 'type': actions.STATE_SET,
  67. 'payload': this.player.value.stringify(),
  68. }));
  69. }
  70. }
  71. void playSong(int songId) {
  72. if (this._isMaster()) {
  73. throw Exception('Playing songs on mobile not yet implemented!');
  74. }
  75. this.player.value.songId = songId;
  76. this.player.value.currentTime = 0;
  77. this.player.value.seekTime = -1;
  78. this.player.value.playing = true;
  79. this._remoteDispatch(jsonEncode({
  80. 'type': actions.STATE_SET,
  81. 'payload': this.player.value.stringify(),
  82. }));
  83. }
  84. }