controller.dart 2.3 KB

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