tuijam 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  1. #!/usr/bin/env python3
  2. from os.path import join, expanduser
  3. import urwid
  4. import gmusicapi
  5. import logging
  6. def sec_to_min_sec(sec_tot):
  7. if sec_tot is None:
  8. return 0, 0
  9. else:
  10. min_ = int(sec_tot // 60)
  11. sec = int(sec_tot % 60)
  12. return min_, sec
  13. class PlayBar(urwid.ProgressBar):
  14. # Class stolen from: https://github.com/and3rson/clay/blob/master/clay/playbar.py
  15. vol_inds = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█']
  16. def __init__(self, app, *args, **kwargs):
  17. super(PlayBar, self).__init__(*args, **kwargs)
  18. self.app = app
  19. def get_prog_tot(self):
  20. curr_time_s = self.app.player.time_pos
  21. rem_time_s = self.app.player.time_remaining
  22. if curr_time_s is None or rem_time_s is None:
  23. return 0, 0
  24. else:
  25. progress = int(curr_time_s)
  26. total = int(curr_time_s + rem_time_s)
  27. return progress, total
  28. def get_text(self):
  29. if self.app.current_song is None:
  30. return 'Idle'
  31. progress, total = self.get_prog_tot()
  32. # return [u' \u25B6 ' if self.app.play_state == 'play' else u' \u25A0 ',
  33. # ('np_artist', self.app.current_song.artist),
  34. # ' - ',
  35. # ('np_song', self.app.current_song.title),
  36. # ' [{:02d}:{:02d} / {:02d}:{:02d}]'.format(progress // 60,
  37. # progress % 60,
  38. # total // 60,
  39. # total % 60)
  40. # ]
  41. return ' {} {} - {} [{:02d}:{:02d} / {:02d}:{:02d}] {}'.format(
  42. '▶' if self.app.play_state == 'play' else '■',
  43. self.app.current_song.artist,
  44. self.app.current_song.title,
  45. progress // 60,
  46. progress % 60,
  47. total // 60,
  48. total % 60,
  49. self.vol_inds[self.app.volume]
  50. )
  51. def update(self):
  52. self._invalidate()
  53. progress, total = self.get_prog_tot()
  54. if progress >= 0 and total > 0:
  55. percent = progress / total * 100
  56. self.set_completion(percent)
  57. else:
  58. self.set_completion(0)
  59. def render(self, size, focus=False):
  60. """
  61. Render the progress bar - fixed implementation.
  62. For details see https://github.com/urwid/urwid/pull/261
  63. """
  64. (maxcol,) = size
  65. txt = urwid.Text(self.get_text(), self.text_align, urwid.widget.CLIP)
  66. c = txt.render((maxcol,))
  67. cf = float(self.current) * maxcol / self.done
  68. ccol_dirty = int(cf)
  69. ccol = len(c._text[0][:ccol_dirty].decode(
  70. 'utf-8', 'ignore'
  71. ).encode(
  72. 'utf-8'
  73. ))
  74. cs = 0
  75. if self.satt is not None:
  76. cs = int((cf - ccol) * 8)
  77. if ccol < 0 or (ccol == 0 and cs == 0):
  78. c._attr = [[(self.normal, maxcol)]]
  79. elif ccol >= maxcol:
  80. c._attr = [[(self.complete, maxcol)]]
  81. elif cs and c._text[0][ccol] == " ":
  82. t = c._text[0]
  83. cenc = self.eighths[cs].encode("utf-8")
  84. c._text[0] = t[:ccol] + cenc + t[ccol + 1:]
  85. a = []
  86. if ccol > 0:
  87. a.append((self.complete, ccol))
  88. a.append((self.satt, len(cenc)))
  89. if maxcol - ccol - 1 > 0:
  90. a.append((self.normal, maxcol - ccol - 1))
  91. c._attr = [a]
  92. c._cs = [[(None, len(c._text[0]))]]
  93. else:
  94. c._attr = [[(self.complete, ccol),
  95. (self.normal, maxcol - ccol)]]
  96. return c
  97. class MusicObject:
  98. @staticmethod
  99. def to_ui(*txts):
  100. first, *rest = [str(txt) for txt in txts]
  101. items = [urwid.SelectableIcon(first, 0)]
  102. for line in rest:
  103. items.append(urwid.Text(line))
  104. line = urwid.Columns(items)
  105. line = urwid.AttrMap(line, 'search normal', 'search select')
  106. return line
  107. @staticmethod
  108. def header_ui(*txts):
  109. header = urwid.Columns([('weight', 1, urwid.Text(('header', txt)))
  110. for txt in txts])
  111. return urwid.AttrMap(header, 'header_bg')
  112. class Song(MusicObject):
  113. def __init__(self, title, album, albumId, artist, artistId, id_, type_, length):
  114. self.title = title
  115. self.album = album
  116. self.albumId = albumId
  117. self.artist = artist
  118. self.artistId = artistId
  119. self.id = id_
  120. self.type = type_
  121. self.length = length
  122. def __repr__(self):
  123. return f'<Song title:{self.title}, album:{self.album}, artist:{self.artist}>'
  124. def __str__(self):
  125. return f'{self.title} by {self.artist}'
  126. def fmt_str(self):
  127. return [('np_song', f'{self.title} '), 'by ', ('np_artist', f'{self.artist}')]
  128. def ui(self):
  129. return self.to_ui(self.title, self.album, self.artist,
  130. '{:02d}:{:02d}'.format(*self.length))
  131. @staticmethod
  132. def header():
  133. return MusicObject.header_ui('Title', 'Album', 'Artist', 'Length')
  134. @staticmethod
  135. def from_dict(d):
  136. try:
  137. title = d['title']
  138. album = d['album']
  139. albumId = d['albumId']
  140. artist = d['artist']
  141. artistId = d['artistId'][0]
  142. try:
  143. id_ = d['id']
  144. type_ = 'library'
  145. except KeyError:
  146. id_ = d['storeId']
  147. type_ = 'store'
  148. length = sec_to_min_sec(int(d['durationMillis']) / 1000)
  149. return Song(title, album, albumId, artist, artistId, id_, type_, length)
  150. except KeyError as e:
  151. logging.exception(f"Missing Key {e} in dict \n{d}")
  152. return None
  153. class Album(MusicObject):
  154. def __init__(self, title, artist, artistId, year, id_):
  155. self.title = title
  156. self.artist = artist
  157. self.artistId = artistId
  158. self.year = year
  159. self.id = id_
  160. def __repr__(self):
  161. return f'<Album title:{self.title}, artist:{self.artist}, year:{self.year}>'
  162. def ui(self):
  163. return self.to_ui(self.title, self.artist, self.year)
  164. @staticmethod
  165. def header():
  166. return MusicObject.header_ui('Album', 'Artist', 'Year')
  167. @staticmethod
  168. def from_dict(d):
  169. try:
  170. title = d['name']
  171. artist = d['albumArtist']
  172. artistId = d['artistId'][0]
  173. try:
  174. year = d['year']
  175. except KeyError:
  176. year = ''
  177. id_ = d['albumId']
  178. return Album(title, artist, artistId, year, id_)
  179. except KeyError as e:
  180. logging.exception(f"Missing Key {e} in dict \n{d}")
  181. return None
  182. class Artist(MusicObject):
  183. def __init__(self, name, id_):
  184. self.name = name
  185. self.id = id_
  186. def __repr__(self):
  187. return f'<Artist name:{self.name}>'
  188. def ui(self):
  189. return self.to_ui(self.name)
  190. @staticmethod
  191. def header():
  192. return MusicObject.header_ui('Artist')
  193. @staticmethod
  194. def from_dict(d):
  195. try:
  196. name = d['name']
  197. id_ = d['artistId']
  198. return Artist(name, id_)
  199. except KeyError as e:
  200. logging.exception(f"Missing Key {e} in dict \n{d}")
  201. return None
  202. class SearchInput(urwid.Edit):
  203. def __init__(self, app):
  204. self.app = app
  205. super().__init__('search > ', multiline=False, allow_tab=False)
  206. def keypress(self, size, key):
  207. if key == 'enter':
  208. txt = self.edit_text
  209. if txt:
  210. self.set_edit_text('')
  211. self.app.search(txt)
  212. return None
  213. else:
  214. size = (size[0],)
  215. return super().keypress(size, key)
  216. class SearchPanel(urwid.ListBox):
  217. def __init__(self, app):
  218. self.app = app
  219. self.walker = urwid.SimpleFocusListWalker([])
  220. self.history = []
  221. self.search_results = ([], [], [])
  222. super().__init__(self.walker)
  223. def keypress(self, size, key):
  224. if key == 'q':
  225. selected = self.selected_search_obj()
  226. if selected:
  227. if type(selected) == Song:
  228. self.app.queue_panel.add_song_to_queue(selected)
  229. elif type(selected) == Album:
  230. self.app.queue_panel.add_album_to_queue(selected)
  231. elif key == 'e':
  232. if self.selected_search_obj() is not None:
  233. self.app.expand(self.selected_search_obj())
  234. elif key == 'backspace':
  235. self.back()
  236. elif key == 'r':
  237. if self.selected_search_obj() is not None:
  238. self.app.create_radio_station(self.selected_search_obj())
  239. elif key == 'j':
  240. super().keypress(size, 'down')
  241. elif key == 'k':
  242. super().keypress(size, 'up')
  243. else:
  244. super().keypress(size, key)
  245. def back(self):
  246. if self.history:
  247. self.set_search_results(*self.history.pop())
  248. def update_search_results(self, songs, albums, artists):
  249. self.history.append(self.search_results)
  250. self.set_search_results(songs, albums, artists)
  251. def set_search_results(self, songs, albums, artists):
  252. songs = [obj for obj in songs if obj is not None]
  253. albums = [obj for obj in albums if obj is not None]
  254. artists = [obj for obj in artists if obj is not None]
  255. self.search_results = (songs, albums, artists)
  256. self.walker.clear()
  257. if artists:
  258. self.walker.append(Artist.header())
  259. for artist in artists:
  260. self.walker.append(artist.ui())
  261. if albums:
  262. self.walker.append(Album.header())
  263. for album in albums:
  264. self.walker.append(album.ui())
  265. if songs:
  266. self.walker.append(Song.header())
  267. for song in songs:
  268. self.walker.append(song.ui())
  269. if self.walker:
  270. self.walker.set_focus(1)
  271. def selected_search_obj(self):
  272. focus_id = self.walker.get_focus()[1]
  273. songs, albums, artists = self.search_results
  274. try:
  275. if artists:
  276. focus_id -= 1
  277. if focus_id < len(artists):
  278. return artists[focus_id]
  279. focus_id -= len(artists)
  280. if albums:
  281. focus_id -= 1
  282. if focus_id < len(albums):
  283. return albums[focus_id]
  284. focus_id -= len(albums)
  285. focus_id -= 1
  286. return songs[focus_id]
  287. except (IndexError, TypeError):
  288. return None
  289. class QueuePanel(urwid.ListBox):
  290. def __init__(self, app):
  291. self.app = app
  292. self.walker = urwid.SimpleFocusListWalker([])
  293. self.queue = []
  294. super().__init__(self.walker)
  295. def add_song_to_queue(self, song):
  296. if song:
  297. self.queue.append(song)
  298. self.walker.append(song.ui())
  299. def add_album_to_queue(self, album):
  300. album_info = self.app.g_api.get_album_info(album.id)
  301. for track in album_info['tracks']:
  302. song = Song.from_dict(track)
  303. if song:
  304. self.queue.append(song)
  305. self.walker.append(song.ui())
  306. def drop(self, idx):
  307. if 0 <= idx < len(self.queue):
  308. self.queue.pop(idx)
  309. self.walker.pop(idx)
  310. def clear(self, idx):
  311. self.queue.clear()
  312. self.walker.clear()
  313. def swap(self, idx1, idx2):
  314. if (0 <= idx1 < len(self.queue)) and (0 <= idx2 < len(self.queue)):
  315. obj1, obj2 = self.queue[idx1], self.queue[idx2]
  316. self.queue[idx1], self.queue[idx2] = obj2, obj1
  317. ui1, ui2 = self.walker[idx1], self.walker[idx2]
  318. self.walker[idx1], self.walker[idx2] = ui2, ui1
  319. def shuffle(self):
  320. from random import shuffle as rshuffle
  321. rshuffle(self.queue)
  322. self.walker.clear()
  323. for s in self.queue:
  324. self.walker.append(s.ui())
  325. def play_next(self):
  326. if self.walker:
  327. self.walker.pop(0)
  328. self.app.play(self.queue.pop(0))
  329. else:
  330. self.app.stop()
  331. def selected_queue_obj(self):
  332. try:
  333. focus_id = self.walker.get_focus()[1]
  334. return self.queue[focus_id]
  335. except (IndexError, TypeError):
  336. return None
  337. def keypress(self, size, key):
  338. focus_id = self.walker.get_focus()[1]
  339. if focus_id is None:
  340. return super().keypress(size, key)
  341. if key == 'u':
  342. self.swap(focus_id, focus_id-1)
  343. self.keypress(size, 'up')
  344. elif key == 'd':
  345. self.swap(focus_id, focus_id+1)
  346. self.keypress(size, 'down')
  347. elif key == 'delete':
  348. self.drop(focus_id)
  349. elif key == 'j':
  350. super().keypress(size, 'down')
  351. elif key == 'k':
  352. super().keypress(size, 'up')
  353. elif key == 'e':
  354. self.app.expand(self.selected_queue_obj())
  355. elif key == ' ':
  356. if self.app.play_state == 'stop':
  357. self.play_next()
  358. else:
  359. self.app.toggle_play()
  360. else:
  361. return super().keypress(size, key)
  362. class App(urwid.Pile):
  363. palette = [
  364. ('header', 'white,underline', 'black'),
  365. ('header_bg', 'white', 'black'),
  366. ('line', 'white', ''),
  367. ('search normal', 'white', ''),
  368. ('search select', '', '', '', 'white', '#D32'),
  369. ('region_bg normal', '', ''),
  370. ('region_bg select', '', 'black'),
  371. ('progress', '', '', '', '#FFF', '#F54'),
  372. ('progress_remaining', '', '', '', '#FFF', '#444'),
  373. ]
  374. def __init__(self):
  375. self.read_config()
  376. self.g_api = gmusicapi.Mobileclient(debug_logging=False)
  377. self.g_api.login(self.email, self.password, self.device_id)
  378. import mpv
  379. self.player = mpv.MPV()
  380. self.player.volume = 100
  381. self.volume = 8
  382. @self.player.event_callback('end_file')
  383. def callback(event):
  384. if event['event']['reason'] == 0:
  385. self.queue_panel.play_next()
  386. self.search_panel = SearchPanel(self)
  387. search_panel_wrapped = urwid.LineBox(self.search_panel, title='Search Results')
  388. search_panel_wrapped = urwid.AttrMap(search_panel_wrapped, 'region_bg normal', 'region_bg select')
  389. self.search_panel_wrapped = search_panel_wrapped
  390. self.playbar = PlayBar(self, 'progress_remaining', 'progress', current=0, done=100)
  391. # self.now_playing = urwid.Text('')
  392. # self.progress = urwid.Text('0:00/0:00', align='right')
  393. # status_line = urwid.Columns([('weight', 3, self.now_playing),
  394. # ('weight', 1, self.progress)])
  395. self.queue_panel = QueuePanel(self)
  396. queue_panel_wrapped = urwid.LineBox(self.queue_panel, title='Queue')
  397. queue_panel_wrapped = urwid.AttrMap(queue_panel_wrapped, 'region_bg normal', 'region_bg select')
  398. self.queue_panel_wrapped = queue_panel_wrapped
  399. self.search_input = urwid.Edit('> ', multiline=False)
  400. self.search_input = SearchInput(self)
  401. urwid.Pile.__init__(self, [('weight', 12, search_panel_wrapped),
  402. ('pack', self.playbar),
  403. ('weight', 7, queue_panel_wrapped),
  404. ('pack', self.search_input)
  405. ])
  406. self.set_focus(self.search_input)
  407. self.play_state = 'stop'
  408. self.current_song = None
  409. self.history = []
  410. def read_config(self):
  411. import yaml
  412. config_file = join(expanduser('~'), '.config', 'tuijam', 'config.yaml')
  413. with open(config_file) as f:
  414. config = yaml.load(f.read())
  415. self.email = config['email']
  416. self.password = config['password']
  417. self.device_id = config['device_id']
  418. def refresh(self, *args, **kwargs):
  419. if self.play_state == 'play' and self.player.eof_reached:
  420. self.queue_panel.play_next()
  421. self.playbar.update()
  422. self.loop.draw_screen()
  423. if self.play_state == 'play':
  424. self.schedule_refresh()
  425. def schedule_refresh(self, dt=0.5):
  426. self.loop.set_alarm_in(dt, self.refresh)
  427. def play(self, song):
  428. self.current_song = song
  429. url = self.g_api.get_stream_url(song.id)
  430. self.player.play(url)
  431. self.player.pause = False
  432. self.play_state = 'play'
  433. self.playbar.update()
  434. self.history.append(song)
  435. self.schedule_refresh()
  436. def stop(self):
  437. self.current_song = None
  438. self.player.pause = True
  439. self.play_state = 'stop'
  440. self.playbar.update()
  441. def seek(self, dt):
  442. try:
  443. self.player.seek(dt)
  444. except SystemError:
  445. pass
  446. def toggle_play(self):
  447. if self.play_state == 'play':
  448. self.player.pause = True
  449. self.play_state = 'pause'
  450. self.playbar.update()
  451. elif self.play_state == 'pause':
  452. self.player.pause = False
  453. self.play_state = 'play'
  454. self.playbar.update()
  455. self.schedule_refresh()
  456. elif self.play_state == 'stop':
  457. self.queue_panel.play_next()
  458. def volume_down(self):
  459. self.volume = max([0, self.volume-1])
  460. self.player.volume = int(self.volume * 100 / 8)
  461. self.playbar.update()
  462. def volume_up(self):
  463. self.volume = min([8, self.volume+1])
  464. self.player.volume = int(self.volume * 100 / 8)
  465. self.playbar.update()
  466. def keypress(self, size, key):
  467. if key == 'tab':
  468. current_focus = self.focus
  469. if current_focus == self.search_panel_wrapped:
  470. self.set_focus(self.queue_panel_wrapped)
  471. elif current_focus == self.queue_panel_wrapped:
  472. self.set_focus(self.search_input)
  473. else:
  474. self.set_focus(self.search_panel_wrapped)
  475. elif key == 'shift tab':
  476. current_focus = self.focus
  477. if current_focus == self.search_panel_wrapped:
  478. self.set_focus(self.search_input)
  479. elif current_focus == self.queue_panel_wrapped:
  480. self.set_focus(self.search_panel_wrapped)
  481. else:
  482. self.set_focus(self.queue_panel_wrapped)
  483. elif key == 'ctrl p':
  484. self.toggle_play()
  485. elif key == 'ctrl q':
  486. self.stop()
  487. elif key == '>':
  488. self.seek(10)
  489. elif key == '<':
  490. self.seek(-10)
  491. elif key == 'ctrl n':
  492. self.queue_panel.play_next()
  493. elif key == 'ctrl r':
  494. self.search_panel.update_search_results(self.history, [], [])
  495. elif key == 'ctrl s':
  496. self.queue_panel.shuffle()
  497. elif key in '-_':
  498. self.volume_down()
  499. elif key in '+=':
  500. self.volume_up()
  501. else:
  502. return self.focus.keypress(size, key)
  503. def expand(self, obj):
  504. if obj is None:
  505. return
  506. if type(obj) == Song:
  507. album_info = self.g_api.get_album_info(obj.albumId)
  508. songs = [Song.from_dict(track) for track in album_info['tracks']]
  509. albums = [Album.from_dict(album_info)]
  510. artists = [Artist(obj.artist, obj.artistId)]
  511. elif type(obj) == Album:
  512. album_info = self.g_api.get_album_info(obj.id)
  513. songs = [Song.from_dict(track) for track in album_info['tracks']]
  514. albums = [obj]
  515. artists = [Artist(obj.artist, obj.artistId)]
  516. else: # Artist
  517. artist_info = self.g_api.get_artist_info(obj.id)
  518. songs = [Song.from_dict(track) for track in artist_info['topTracks']]
  519. albums = [Album.from_dict(album) for album in artist_info.get('albums', [])]
  520. artists = [Artist.from_dict(artist) for artist in artist_info['related_artists']]
  521. artists.insert(0, obj)
  522. self.search_panel.update_search_results(songs, albums, artists)
  523. def search(self, query):
  524. results = self.g_api.search(query)
  525. songs = [Song.from_dict(hit['track']) for hit in results['song_hits']]
  526. albums = [Album.from_dict(hit['album']) for hit in results['album_hits']]
  527. artists = [Artist.from_dict(hit['artist']) for hit in results['artist_hits']]
  528. self.search_panel.update_search_results(songs, albums, artists)
  529. self.set_focus(self.search_panel_wrapped)
  530. def create_radio_station(self, obj):
  531. if type(obj) == Song:
  532. station_name = obj.title + " radio"
  533. station_id = self.g_api.create_station(station_name, track_id=obj.id)
  534. elif type(obj) == Album:
  535. station_name = obj.title + " radio"
  536. station_id = self.g_api.create_station(station_name, album_id=obj.id)
  537. else: # Artist
  538. station_name = obj.name + " radio"
  539. station_id = self.g_api.create_station(station_name, artist_id=obj.id)
  540. song_dicts = self.g_api.get_station_tracks(station_id, num_tracks=50)
  541. for song_dict in song_dicts:
  542. self.queue_panel.add_song_to_queue(Song.from_dict(song_dict))
  543. def cleanup(self):
  544. self.player.quit()
  545. del self.player
  546. self.g_api.logout()
  547. if __name__ == '__main__':
  548. log_file = join(expanduser('~'), '.config', 'tuijam', 'log.txt')
  549. logging.basicConfig(filename=log_file, filemode='w', level=logging.ERROR)
  550. app = App()
  551. import signal
  552. def handle_sigint(signum, frame):
  553. raise urwid.ExitMainLoop()
  554. signal.signal(signal.SIGINT, handle_sigint)
  555. loop = urwid.MainLoop(app, app.palette)
  556. app.loop = loop
  557. loop.screen.set_terminal_properties(256)
  558. try:
  559. loop.run()
  560. except Exception as e:
  561. logging.exception(e)
  562. print("Something bad happened! :( see log file ($HOME/.config/tuijam/log.txt) for more information.")
  563. app.cleanup()