tuijam 15 KB

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