tuijam 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. #!/usr/bin/env python3
  2. import urwid
  3. import gmusicapi
  4. class MusicObject:
  5. @staticmethod
  6. def to_ui(*txts):
  7. first, *rest = [str(txt) for txt in txts]
  8. items = [urwid.SelectableIcon(first, 0)]
  9. for line in rest:
  10. items.append(urwid.Text(line))
  11. line = urwid.Columns(items)
  12. line = urwid.AttrMap(line, 'search normal', 'search select')
  13. return line
  14. @staticmethod
  15. def header_ui(*txts):
  16. header = urwid.Columns([('weight', 1, urwid.Text(('header', txt)))
  17. for txt in txts])
  18. return urwid.AttrMap(header, 'header_bg')
  19. class Song(MusicObject):
  20. def __init__(self, title, album, albumId, artist, artistId, id_):
  21. self.title = title
  22. self.album = album
  23. self.albumId = albumId
  24. self.artist = artist
  25. self.artistId = artistId
  26. self.id = id_
  27. def __repr__(self):
  28. return f'<Song title:{self.title}, album:{self.album}, artist:{self.artist}>'
  29. def __str__(self):
  30. return f'{self.title} by {self.artist}'
  31. def ui(self):
  32. return self.to_ui(self.title, self.album, self.artist)
  33. @staticmethod
  34. def header():
  35. return MusicObject.header_ui('Title', 'Album', 'Artist')
  36. @staticmethod
  37. def from_dict(d):
  38. title = d['title']
  39. album = d['album']
  40. albumId = d['albumId']
  41. artist = d['artist']
  42. artistId = d['artistId'][0]
  43. try:
  44. id_ = d['id']
  45. except KeyError:
  46. id_ = d['storeId']
  47. return Song(title, album, albumId, artist, artistId, id_)
  48. class Album(MusicObject):
  49. def __init__(self, title, artist, artistId, year, id_):
  50. self.title = title
  51. self.artist = artist
  52. self.artistId = artistId
  53. self.year = year
  54. self.id = id_
  55. def __repr__(self):
  56. return f'<Album title:{self.title}, artist:{self.artist}, year:{self.year}>'
  57. def ui(self):
  58. return self.to_ui(self.title, self.artist, self.year)
  59. @staticmethod
  60. def header():
  61. return MusicObject.header_ui('Album', 'Artist', 'Year')
  62. @staticmethod
  63. def from_dict(d):
  64. title = d['name']
  65. artist = d['albumArtist']
  66. artistId = d['artistId'][0]
  67. year = d['year']
  68. id_ = d['albumId']
  69. return Album(title, artist, artistId, year, id_)
  70. class Artist(MusicObject):
  71. def __init__(self, name, id_):
  72. self.name = name
  73. self.id = id_
  74. def __repr__(self):
  75. return f'<Artist name:{self.name}>'
  76. def ui(self):
  77. return self.to_ui(self.name)
  78. @staticmethod
  79. def header():
  80. return MusicObject.header_ui('Artist')
  81. @staticmethod
  82. def from_dict(d):
  83. name = d['name']
  84. id_ = d['artistId']
  85. return Artist(name, id_)
  86. class CommandInput(urwid.Edit):
  87. def __init__(self, app):
  88. self.app = app
  89. super().__init__('search > ', multiline=False, allow_tab=False)
  90. def keypress(self, size, key):
  91. if key == 'enter':
  92. txt = self.edit_text
  93. if txt:
  94. self.set_edit_text('')
  95. self.app.search(txt)
  96. return None
  97. else:
  98. size = (size[0],)
  99. return super().keypress(size, key)
  100. class SearchPanel(urwid.ListBox):
  101. def __init__(self, app):
  102. self.app = app
  103. self.walker = urwid.SimpleFocusListWalker([])
  104. super().__init__(self.walker)
  105. def keypress(self, size, key):
  106. if key == 'q':
  107. selected = self.selected_search_obj()
  108. if selected:
  109. if type(selected) == Song:
  110. self.app.queue_panel.add_song_to_queue(selected)
  111. elif type(selected) == Album:
  112. self.app.queue_panel.add_album_to_queue(selected)
  113. elif key == 'e':
  114. self.app.expand(self.selected_search_obj())
  115. elif key == 'j':
  116. super().keypress(size, 'down')
  117. elif key == 'k':
  118. super().keypress(size, 'up')
  119. else:
  120. super().keypress(size, key)
  121. def set_search_results(self, songs, albums, artists):
  122. self.search_results = (songs, albums, artists)
  123. self.walker.clear()
  124. if artists:
  125. self.walker.append(Artist.header())
  126. for artist in artists:
  127. self.walker.append(artist.ui())
  128. if albums:
  129. self.walker.append(Album.header())
  130. for album in albums:
  131. self.walker.append(album.ui())
  132. if songs:
  133. self.walker.append(Song.header())
  134. for song in songs:
  135. self.walker.append(song.ui())
  136. if self.walker:
  137. self.walker.set_focus(1)
  138. def selected_search_obj(self):
  139. focus_id = self.walker.get_focus()[1]
  140. songs, albums, artists = self.search_results
  141. try:
  142. focus_id -= 1
  143. if focus_id < len(artists):
  144. return artists[focus_id]
  145. focus_id -= (1 + len(artists))
  146. if focus_id < len(albums):
  147. return albums[focus_id]
  148. focus_id -= (1 + len(albums))
  149. return songs[focus_id]
  150. except IndexError:
  151. return None
  152. class QueuePanel(urwid.ListBox):
  153. def __init__(self, app):
  154. self.app = app
  155. self.walker = urwid.SimpleFocusListWalker([])
  156. self.queue = []
  157. super().__init__(self.walker)
  158. def add_song_to_queue(self, song):
  159. self.queue.append(song)
  160. self.walker.append(song.ui())
  161. def add_album_to_queue(self, album):
  162. album_info = self.app.g_api.get_album_info(album.id)
  163. for track in album_info['tracks']:
  164. song = Song.from_dict(track)
  165. self.queue.append(song)
  166. self.walker.append(song.ui())
  167. def drop(self, idx):
  168. if 0 <= idx < len(self.queue):
  169. self.queue.pop(idx)
  170. self.walker.pop(idx)
  171. def swap(self, idx1, idx2):
  172. if (0 <= idx1 < len(self.queue)) and (0 <= idx2 < len(self.queue)):
  173. obj1, obj2 = self.queue[idx1], self.queue[idx2]
  174. self.queue[idx1], self.queue[idx2] = obj2, obj1
  175. ui1, ui2 = self.walker[idx1], self.walker[idx2]
  176. self.walker[idx1], self.walker[idx2] = ui2, ui1
  177. def play_next(self):
  178. if self.walker:
  179. self.walker.pop(0)
  180. self.app.play(self.queue.pop(0))
  181. def keypress(self, size, key):
  182. focus_id = self.walker.get_focus()[1]
  183. if focus_id is None:
  184. return super().keypress(size, key)
  185. if key == 'u':
  186. self.swap(focus_id, focus_id-1)
  187. self.keypress(size, 'up')
  188. elif key == 'd':
  189. self.swap(focus_id, focus_id+1)
  190. self.keypress(size, 'down')
  191. elif key == 'delete':
  192. self.drop(focus_id)
  193. elif key == 'j':
  194. super().keypress(size, 'down')
  195. elif key == 'k':
  196. super().keypress(size, 'up')
  197. elif key == ' ':
  198. if self.app.play_state == 'stop':
  199. self.play_next()
  200. else:
  201. self.app.toggle_play()
  202. else:
  203. return super().keypress(size, key)
  204. class App(urwid.Pile):
  205. palette = [
  206. ('header', 'white,underline', 'black'),
  207. ('header_bg', 'white', 'black'),
  208. ('line', 'white', ''),
  209. ('search normal', 'white', ''),
  210. ('search select', 'white', 'dark red'),
  211. ('region_bg normal', '', ''),
  212. ('region_bg select', '', 'black'),
  213. ]
  214. def __init__(self):
  215. self.read_config()
  216. self.g_api = gmusicapi.Mobileclient()
  217. self.g_api.login(self.email, self.password, self.device_id)
  218. import mpv
  219. self.player = mpv.MPV()
  220. @self.player.event_callback('end_file')
  221. def callback(event):
  222. if event['event']['reason'] == 0:
  223. self.queue_panel.play_next()
  224. self.search_panel = SearchPanel(self)
  225. search_panel_wrapped = urwid.LineBox(self.search_panel, title='Search Results')
  226. search_panel_wrapped = urwid.AttrMap(search_panel_wrapped, 'region_bg normal', 'region_bg select')
  227. self.search_panel_wrapped = search_panel_wrapped
  228. self.now_playing = urwid.Text('')
  229. self.progress = urwid.Text('0:00/0:00', align='right')
  230. status_line = urwid.Columns([('weight', 3, self.now_playing),
  231. ('weight', 1, self.progress)])
  232. self.queue_panel = QueuePanel(self)
  233. queue_panel_wrapped = urwid.LineBox(self.queue_panel, title='Queue')
  234. queue_panel_wrapped = urwid.AttrMap(queue_panel_wrapped, 'region_bg normal', 'region_bg select')
  235. self.queue_panel_wrapped = queue_panel_wrapped
  236. self.command_input = urwid.Edit('> ', multiline=False)
  237. self.command_input = CommandInput(self)
  238. urwid.Pile.__init__(self, [('weight', 12, search_panel_wrapped),
  239. ('pack', status_line),
  240. ('weight', 7, queue_panel_wrapped),
  241. ('pack', self.command_input)
  242. ])
  243. self.set_focus(self.command_input)
  244. self.play_state = 'stop'
  245. self.current_song = None
  246. def read_config(self):
  247. from os.path import join, expanduser
  248. import yaml
  249. config_file = join(expanduser('~'), '.config', 'tuijam', 'config.yaml')
  250. with open(config_file) as f:
  251. config = yaml.load(f.read())
  252. self.email = config['email']
  253. self.password = config['password']
  254. self.device_id = config['device_id']
  255. @staticmethod
  256. def sec_to_min_sec(sec_tot):
  257. if sec_tot is None:
  258. return 0, 0
  259. else:
  260. min_ = int(sec_tot // 60)
  261. sec = int(sec_tot % 60)
  262. return min_, sec
  263. def update_progress(self):
  264. curr_time_s = self.player.time_pos
  265. rem_time_s = self.player.time_remaining
  266. if curr_time_s is not None and rem_time_s is not None:
  267. curr_time = self.sec_to_min_sec(curr_time_s)
  268. total_time = self.sec_to_min_sec(curr_time_s+rem_time_s)
  269. else:
  270. curr_time = (0, 0)
  271. total_time = (0, 0)
  272. self.progress.set_text(f'{curr_time[0]}:{curr_time[1]:02d}/{total_time[0]}:{total_time[1]:02d}')
  273. def update_now_playing(self):
  274. if self.play_state == 'play':
  275. self.update_progress()
  276. self.now_playing.set_text(f'Now Playing: {str(self.current_song)}')
  277. self.schedule_refresh()
  278. elif self.play_state == 'pause':
  279. self.update_progress()
  280. self.now_playing.set_text(f'Paused: {str(self.current_song)}')
  281. else:
  282. self.now_playing.set_text('')
  283. def refresh(self, *args, **kwargs):
  284. if self.play_state == 'play' and self.player.eof_reached:
  285. self.queue_panel.play_next()
  286. self.update_now_playing()
  287. def schedule_refresh(self, dt=0.2):
  288. self.loop.set_alarm_in(dt, self.refresh)
  289. def play(self, song):
  290. self.current_song = song
  291. url = self.g_api.get_stream_url(song.id)
  292. self.player.play(url)
  293. self.play_state = 'play'
  294. self.update_now_playing()
  295. self.schedule_refresh()
  296. def stop(self, song):
  297. self.current_song = None
  298. self.player.quit()
  299. self.play_state = 'stop'
  300. self.update_now_playing()
  301. def seek(self, dt):
  302. try:
  303. self.player.seek(dt)
  304. except SystemError:
  305. pass
  306. def toggle_play(self):
  307. if self.play_state == 'play':
  308. self.player.pause = True
  309. self.play_state = 'pause'
  310. self.update_now_playing()
  311. elif self.play_state == 'pause':
  312. self.player.pause = False
  313. self.play_state = 'play'
  314. self.update_now_playing()
  315. self.schedule_refresh()
  316. def keypress(self, size, key):
  317. if key == 'tab':
  318. current_focus = self.focus
  319. if current_focus == self.search_panel_wrapped:
  320. self.set_focus(self.queue_panel_wrapped)
  321. elif current_focus == self.queue_panel_wrapped:
  322. self.set_focus(self.command_input)
  323. else:
  324. self.set_focus(self.search_panel_wrapped)
  325. elif key == 'shift tab':
  326. current_focus = self.focus
  327. if current_focus == self.search_panel_wrapped:
  328. self.set_focus(self.command_input)
  329. elif current_focus == self.queue_panel_wrapped:
  330. self.set_focus(self.search_panel_wrapped)
  331. else:
  332. self.set_focus(self.queue_panel_wrapped)
  333. elif key == 'ctrl p':
  334. self.toggle_play()
  335. elif key == 'ctrl q':
  336. self.stop()
  337. elif key == '>':
  338. self.seek(10)
  339. elif key == '<':
  340. self.seek(-10)
  341. elif key == 'ctrl n':
  342. self.queue_panel.play_next()
  343. else:
  344. return self.focus.keypress(size, key)
  345. def expand(self, obj):
  346. if type(obj) == Song:
  347. album_info = self.g_api.get_album_info(obj.albumId)
  348. songs = [Song.from_dict(track) for track in album_info['tracks']]
  349. albums = [obj]
  350. artists = [Artist(obj.artist, obj.artistId)]
  351. elif type(obj) == Album:
  352. album_info = self.g_api.get_album_info(obj.id)
  353. songs = [Song.from_dict(track) for track in album_info['tracks']]
  354. albums = [obj]
  355. artists = [Artist(obj.artist, obj.artistId)]
  356. else: # Artist
  357. artist_info = self.g_api.get_artist_info(obj.id)
  358. songs = [Song.from_dict(track) for track in artist_info['topTracks']]
  359. albums = [Album.from_dict(album) for album in artist_info['albums']]
  360. artists = [Artist.from_dict(artist) for artist in artist_info['related_artists']]
  361. artists.insert(0, obj)
  362. self.search_panel.set_search_results(songs, albums, artists)
  363. def search(self, query):
  364. results = self.g_api.search(query)
  365. songs = [Song.from_dict(hit['track']) for hit in results['song_hits']]
  366. albums = [Album.from_dict(hit['album']) for hit in results['album_hits']]
  367. artists = [Artist.from_dict(hit['artist']) for hit in results['artist_hits']]
  368. self.search_panel.set_search_results(songs, albums, artists)
  369. self.set_focus(self.search_panel_wrapped)
  370. def cleanup(self):
  371. self.player.quit()
  372. del self.player
  373. self.g_api.logout()
  374. if __name__ == '__main__':
  375. app = App()
  376. import signal
  377. def handle_sigint(signum, frame):
  378. raise urwid.ExitMainLoop()
  379. signal.signal(signal.SIGINT, handle_sigint)
  380. loop = urwid.MainLoop(app, app.palette)
  381. app.loop = loop
  382. loop.run()
  383. app.cleanup()