tuijam 19 KB

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