tuijam 19 KB

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