tuijam 19 KB

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