Player.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import React, {Component} from 'react';
  2. import Select from "react-virtualized-select";
  3. import Sound from 'react-sound';
  4. import AlbumList from './AlbumList.js';
  5. import MediaSession from './MediaSession.js';
  6. import Controls from './Controls.js';
  7. import Playlist from './Playlist.js';
  8. import {getQueryString} from './utils.js';
  9. const fetchOpts = { credentials: 'same-origin' }
  10. export default class Player extends Component {
  11. selects = [{type: 'artist', title: 'Artists'},
  12. {type: 'year', title: 'Years'},
  13. {type: 'genre', title: 'Genres'},
  14. {type: 'publisher', title: 'Labels'},
  15. {type: 'country', title: 'Countries'},
  16. {type: 'type', title: 'Album types'},
  17. {type: 'status', title: 'Album statuses'}];
  18. constructor(props) {
  19. super(props);
  20. this.state = {
  21. albumList: {key:'', albums: [], error: false, hasMore: false},
  22. filters: {},
  23. filter: '',
  24. sound: {url: '', playStatus: Sound.status.STOPPED},
  25. tracks: null,
  26. activeTrack: -1,
  27. activeAlbum: null,
  28. metadata: {artist: '', album: '', title: '', cover: ''}
  29. };
  30. this.filterTimeout = null;
  31. }
  32. genAlbumListKey() {
  33. const {filter, filters} = this.state
  34. return `${filter}-${this.selects.map(({type}) => filters[type] ? filters[type].item : '').join('-')}`
  35. }
  36. loadAlbums = (page) => {
  37. const {filter, filters} = this.state
  38. const limit = 15;
  39. const offset = page * limit;
  40. const params = {filter, offset, limit:(limit+1)};
  41. let key = (page === 0 ? this.genAlbumListKey() : this.state.albumList.key)
  42. for (const {type} of this.selects) {
  43. if (filters[type]) {
  44. params[type] = filters[type].item;
  45. }
  46. }
  47. return fetch(`/cat/album?${getQueryString(params)}`, fetchOpts)
  48. .then(res => (res.ok ? res.json() : Promise.reject({message:res.statusText})))
  49. .then(data => {
  50. const hasMore = (data.length > limit)
  51. const albums = page === 0 ? data.slice(0, limit) : this.state.albumList.albums.concat(data.slice(0, limit))
  52. const albumList = {key, albums, hasMore}
  53. this.setState({albumList})
  54. return albums;
  55. })
  56. .catch(error => {
  57. console.log(error)
  58. const albumList = {key, error}
  59. this.setState({albumList})
  60. })
  61. }
  62. componentDidMount() {
  63. this.loadAlbums(0)
  64. }
  65. componentDidUpdate(prevProps, prevState) {
  66. const {filters} = this.state;
  67. if (filters !== prevState.filters) {
  68. this.loadAlbums(0);
  69. }
  70. if (this.state.activeAlbum !== prevState.activeAlbum) {
  71. this.fetchTracks(this.state.activeAlbum);
  72. }
  73. if (this.state.activeTrack !== prevState.activeTrack) {
  74. if (this.state.activeTrack !== -1 && Array.isArray(this.state.tracks)) {
  75. const track = this.state.tracks[this.state.activeTrack];
  76. if (!track) {
  77. console.log('Bad activeTrack', this.state.tracks, this.state.activeTrack);
  78. } else {
  79. this.setState({
  80. sound: {
  81. url: track.url,
  82. position: 0,
  83. playStatus: Sound.status.PLAYING
  84. },
  85. metadata: {
  86. title: track.title,
  87. artist: track.artist,
  88. album: track.album,
  89. cover: this.state.activeAlbum.cover
  90. }
  91. })
  92. }
  93. }
  94. }
  95. }
  96. fetchTracks(album) {
  97. fetch(`/album/${album.id}/tracks`, fetchOpts)
  98. .then(res => (res.ok ? res.json() : Promise.reject({message:res.statusText})))
  99. .then(result => this.setState({tracks: result, activeTrack: 0}))
  100. .catch(error => this.setState({tracks: error.message}));
  101. this.setState({tracks: "Loading", activeTrack: -1})
  102. }
  103. handleFilterChange = (e) => {
  104. if (this.filterTimeout) {
  105. clearInterval(this.filterTimeout);
  106. }
  107. const filter = e.target.value;
  108. this.filterTimeout = setTimeout(() => {
  109. this.loadAlbums(0);
  110. }, 500);
  111. this.setState({filter})
  112. }
  113. handleControlPrev = () => {
  114. if (!Array.isArray(this.state.tracks)) {
  115. return;
  116. }
  117. var activeTrack = this.state.activeTrack - 1
  118. if (activeTrack < 0) {
  119. activeTrack = -1;
  120. }
  121. this.setState({activeTrack: activeTrack})
  122. }
  123. handleControlPlayPause = () => {
  124. const playStatus = (this.state.sound.playStatus === Sound.status.PLAYING ? Sound.status.PAUSED : Sound.status.PLAYING);
  125. this.setState({sound: Object.assign({}, this.state.sound, {playStatus: playStatus})});
  126. }
  127. handleControlStop = () => {
  128. this.setState({
  129. sound: Object.assign({}, this.state.sound, {
  130. playStatus: Sound.status.STOPPED,
  131. position: 0}),
  132. activeTrack: -1});
  133. }
  134. handleControlNext = () => {
  135. if (!Array.isArray(this.state.tracks)) {
  136. return;
  137. }
  138. var activeTrack = this.state.activeTrack + 1
  139. if (activeTrack >= this.state.tracks.length) {
  140. activeTrack = -1;
  141. }
  142. this.setState({activeTrack: activeTrack})
  143. }
  144. handleSoundError = (errorCode, description) => {
  145. console.log('sound error', errorCode, description)
  146. // try next track
  147. this.handleControlNext();
  148. }
  149. handleSoundLoading = (sound) => {
  150. // TODOconsole.log('sound loading', sound)
  151. }
  152. handleSoundPlaying = (sound) => {
  153. this.setState({sound: Object.assign({}, this.state.sound, {
  154. position: sound.position,
  155. duration: sound.duration
  156. })})
  157. }
  158. handleSoundFinished = () => {
  159. console.log('sound finished');
  160. this.setState({sound: Object.assign({}, this.state.sound, {playStatus: Sound.status.STOPPED})});
  161. this.handleControlNext();
  162. }
  163. handleActivateTrack = (activeTrack) => {
  164. this.setState({activeTrack: activeTrack})
  165. }
  166. handlePlayAlbum = (album) => {
  167. this.setState({activeAlbum: album})
  168. }
  169. handleLoadOptions(cat, q, page) {
  170. const pageSize = 100
  171. const params = {filter:q}
  172. params.offset = (page - 1) * pageSize;
  173. params.limit = pageSize;
  174. return fetch(`/cat/${cat}?${getQueryString(params)}`, fetchOpts)
  175. .then(res => (res.ok ? res.json() : Promise.reject({message:res.statusText})))
  176. .then(options => ({options}))
  177. }
  178. handleSelectChange(cat, option) {
  179. const filters = Object.assign({}, this.state.filters, {[cat]: option});
  180. this.setState({filters, filter: ''})
  181. }
  182. _optionRenderer ({ focusedOption, focusOption, key, labelKey, option, selectValue, style, valueArray }) {
  183. const className = ['VirtualizedSelectOption']
  184. if (option === focusedOption) {
  185. className.push('VirtualizedSelectFocusedOption')
  186. }
  187. if (option.disabled) {
  188. className.push('VirtualizedSelectDisabledOption')
  189. }
  190. if (valueArray && valueArray.indexOf(option) >= 0) {
  191. className.push('VirtualizedSelectSelectedOption')
  192. }
  193. if (option.className) {
  194. className.push(option.className)
  195. }
  196. const events = option.disabled
  197. ? {}
  198. : {
  199. onClick: () => selectValue(option),
  200. onMouseEnter: () => focusOption(option)
  201. }
  202. return (
  203. <div
  204. className={className.join(' ')}
  205. key={key}
  206. style={style}
  207. title={option.title}
  208. {...events}
  209. >
  210. {option.item} - {option.count}
  211. </div>
  212. )
  213. }
  214. render() {
  215. return (
  216. <div className="Player">
  217. <div className="PlayerFilters">
  218. {this.selects.map(({type, title}) => (
  219. <div className="section" key={type}>
  220. <h3>{title}</h3>
  221. <Select
  222. async
  223. pagination
  224. autoload={true}
  225. optionRenderer={this._optionRenderer}
  226. loadOptions={(q,p) => this.handleLoadOptions(type, q, p)}
  227. onChange={o => this.handleSelectChange(type, o)}
  228. labelKey="item"
  229. valueKey="item"
  230. value={this.state.filters[type]}
  231. />
  232. </div>
  233. ))}
  234. <div className="section">
  235. <h3>Search</h3>
  236. <input className="Filter"
  237. type="text"
  238. value={this.state.filter}
  239. placeholder="Search albums"
  240. onChange={this.handleFilterChange} />
  241. </div>
  242. </div><br style={{clear:'both'}} />
  243. <Controls
  244. visible={true}
  245. {...this.state.sound}
  246. onPrev={this.handleControlPrev}
  247. onPlayPause={this.handleControlPlayPause}
  248. onStop={this.handleControlStop}
  249. onNext={this.handleControlNext} />
  250. <Playlist
  251. tracks={this.state.tracks}
  252. activeTrack={this.state.activeTrack}
  253. onActivateTrack={this.handleActivateTrack} />
  254. <AlbumList
  255. title="Albums"
  256. {...this.state.albumList}
  257. loadMore={this.loadAlbums}
  258. onPlayAlbum={this.handlePlayAlbum} />
  259. <Sound {...this.state.sound}
  260. onError={this.handleSoundError}
  261. onLoading={this.handleSoundLoading}
  262. onPlaying={this.handleSoundPlaying}
  263. onFinishedPlaying={this.handleSoundFinished} />
  264. <MediaSession
  265. {...this.state.metadata}
  266. onPlay={this.handleControlPlayPause}
  267. onPause={this.handleControlPlayPause}
  268. onPreviousTrack={this.handleControlPrev}
  269. onNextTrack={this.handleControlNext}
  270. />
  271. </div>
  272. );
  273. }
  274. }