Player.js 9.6 KB

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