/usr/lib/python3/dist-packages/gnomemusic/player.py is in gnome-music 3.18.2-1ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 | # Copyright (c) 2013 Vadim Rutkovsky <vrutkovs@redhat.com>
# Copyright (c) 2013 Arnel A. Borja <kyoushuu@yahoo.com>
# Copyright (c) 2013 Seif Lotfy <seif@lotfy.com>
# Copyright (c) 2013 Eslam Mostafa <cseslam@gmail.com>
# Copyright (c) 2013 Sai Suman Prayaga <suman.sai14@gmail.com>
# Copyright (c) 2013 Shivani Poddar <shivani.poddar92@gmail.com>
# Copyright (c) 2013 Guillaume Quintard <guillaume.quintard@gmail.com>
# Copyright (c) 2014 Cedric Bellegarde <gnumdk@gmail.com>
# Copyright (C) 2010 Jonathan Matthew (replay gain code)
#
# GNOME Music is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# GNOME Music is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with GNOME Music; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# The GNOME Music authors hereby grant permission for non-GPL compatible
# GStreamer plugins to be used and distributed together with GStreamer
# and GNOME Music. This permission is above and beyond the permissions
# granted by the GPL license by which GNOME Music is covered. If you
# modify this code, you may extend this exception to your version of the
# code, but you are not obligated to do so. If you do not wish to do so,
# delete this exception statement from your version.
from gi.repository import GIRepository
GIRepository.Repository.prepend_search_path('libgd')
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstAudio', '1.0')
gi.require_version('GstPbutils', '1.0')
from gi.repository import Gtk, Gdk, GLib, Gio, GObject, Gst, GstAudio, GstPbutils
from gettext import gettext as _, ngettext
from random import randint
from collections import deque
from gnomemusic.albumArtCache import AlbumArtCache
from gnomemusic.playlists import Playlists
playlists = Playlists.get_default()
from hashlib import md5
import requests
import time
from threading import Thread
from gnomemusic import log
import logging
logger = logging.getLogger(__name__)
ART_SIZE = 34
class RepeatType:
NONE = 0
SONG = 1
ALL = 2
SHUFFLE = 3
class PlaybackStatus:
PLAYING = 0
PAUSED = 1
STOPPED = 2
class DiscoveryStatus:
PENDING = 0
FAILED = 1
SUCCEEDED = 2
class Player(GObject.GObject):
nextTrack = None
timeout = None
shuffleHistory = deque(maxlen=10)
__gsignals__ = {
'playing-changed': (GObject.SignalFlags.RUN_FIRST, None, ()),
'playlist-changed': (GObject.SignalFlags.RUN_FIRST, None, ()),
'playlist-item-changed': (GObject.SignalFlags.RUN_FIRST, None, (Gtk.TreeModel, Gtk.TreeIter)),
'current-changed': (GObject.SignalFlags.RUN_FIRST, None, ()),
'playback-status-changed': (GObject.SignalFlags.RUN_FIRST, None, ()),
'repeat-mode-changed': (GObject.SignalFlags.RUN_FIRST, None, ()),
'volume-changed': (GObject.SignalFlags.RUN_FIRST, None, ()),
'prev-next-invalidated': (GObject.SignalFlags.RUN_FIRST, None, ()),
'seeked': (GObject.SignalFlags.RUN_FIRST, None, (int,)),
'thumbnail-updated': (GObject.SignalFlags.RUN_FIRST, None, (str,)),
}
def __repr__(self):
return '<Player>'
@log
def __init__(self, parent_window):
GObject.GObject.__init__(self)
self._parent_window = parent_window
self.playlist = None
self.playlistType = None
self.playlistId = None
self.playlistField = None
self.currentTrack = None
self.currentTrackUri = None
self._lastState = Gst.State.PAUSED
self.cache = AlbumArtCache.get_default()
self._noArtworkIcon = self.cache.get_default_icon(ART_SIZE, ART_SIZE)
self._loadingIcon = self.cache.get_default_icon(ART_SIZE, ART_SIZE, True)
self._missingPluginMessages = []
Gst.init(None)
GstPbutils.pb_utils_init()
self.discoverer = GstPbutils.Discoverer()
self.discoverer.connect('discovered', self._on_discovered)
self.discoverer.start()
self._discovering_urls = {}
self.player = Gst.ElementFactory.make('playbin', 'player')
self.bus = self.player.get_bus()
self.bus.add_signal_watch()
self.setup_replaygain()
self._settings = Gio.Settings.new('org.gnome.Music')
self._settings.connect('changed::repeat', self._on_repeat_setting_changed)
self._settings.connect('changed::replaygain', self._on_replaygain_setting_changed)
self.repeat = self._settings.get_enum('repeat')
self.replaygain = self._settings.get_value('replaygain') is not None
self.toggle_replaygain(self.replaygain)
self.bus.connect('message::state-changed', self._on_bus_state_changed)
self.bus.connect('message::error', self._onBusError)
self.bus.connect('message::element', self._on_bus_element)
self.bus.connect('message::eos', self._on_bus_eos)
self._setup_view()
self.playlist_insert_handler = 0
self.playlist_delete_handler = 0
self._check_last_fm()
@log
def _check_last_fm(self):
try:
self.last_fm = None
gi.require_version('Goa', '1.0')
from gi.repository import Goa
client = Goa.Client.new_sync(None)
accounts = client.get_accounts()
for obj in accounts:
account = obj.get_account()
if account.props.provider_name == "Last.fm":
self.last_fm = obj.get_oauth2_based()
return
except Exception as e:
logger.info("Error reading Last.fm credentials: %s" % str(e))
self.last_fm = None
@log
def _on_replaygain_setting_changed(self, settings, value):
self.replaygain = settings.get_value('replaygain') is not None
self.toggle_replaygain(self.replaygain)
@log
def setup_replaygain(self):
"""
Set up replaygain
See https://github.com/gnumdk/lollypop/commit/429383c3742e631b34937d8987d780edc52303c0
"""
self._rgfilter = Gst.ElementFactory.make("bin", "bin")
self._rg_audioconvert1 = Gst.ElementFactory.make("audioconvert", "audioconvert")
self._rg_audioconvert2 = Gst.ElementFactory.make("audioconvert", "audioconvert2")
self._rgvolume = Gst.ElementFactory.make("rgvolume", "rgvolume")
self._rglimiter = Gst.ElementFactory.make("rglimiter", "rglimiter")
self._rg_audiosink = Gst.ElementFactory.make("autoaudiosink", "autoaudiosink")
if not self._rgfilter or not self._rg_audioconvert1 or not self._rg_audioconvert2 \
or not self._rgvolume or not self._rglimiter or not self._rg_audiosink:
logger.debug("Replay Gain is not available")
return
self._rgvolume.props.pre_amp = 0.0
self._rgfilter.add(self._rgvolume)
self._rgfilter.add(self._rg_audioconvert1)
self._rgfilter.add(self._rg_audioconvert2)
self._rgfilter.add(self._rglimiter)
self._rgfilter.add(self._rg_audiosink)
self._rg_audioconvert1.link(self._rgvolume)
self._rgvolume.link(self._rg_audioconvert2)
self._rgvolume.link(self._rglimiter)
self._rg_audioconvert2.link(self._rg_audiosink)
self._rgfilter.add_pad(Gst.GhostPad.new("sink", self._rg_audioconvert1.get_static_pad("sink")))
@log
def toggle_replaygain(self, state=False):
if state and self._rgfilter:
self.player.set_property("audio-sink", self._rgfilter)
else:
self.player.set_property("audio-sink", None)
def discover_item(self, item, callback, data=None):
url = item.get_url()
if not url:
logger.warn("The item %s doesn't have a URL set", item)
return
if not url.startswith("file://"):
logger.debug("Skipping discovery of %s as not a local file", url)
return
obj = (callback, data)
if url in self._discovering_urls:
self._discovering_urls[url] += [obj]
else:
self._discovering_urls[url] = [obj]
self.discoverer.discover_uri_async(url)
def _on_discovered(self, discoverer, info, error):
try:
cbs = self._discovering_urls[info.get_uri()]
del(self._discovering_urls[info.get_uri()])
for callback, data in cbs:
if data is not None:
callback(info, error, data)
else:
callback(info, error)
except KeyError:
# Not something we're interested in
return
@log
def _on_repeat_setting_changed(self, settings, value):
self.repeat = settings.get_enum('repeat')
self._sync_prev_next()
self._sync_repeat_image()
@log
def _on_bus_state_changed(self, bus, message):
# Note: not all state changes are signaled through here, in particular
# transitions between Gst.State.READY and Gst.State.NULL are never async
# and thus don't cause a message
# In practice, self means only Gst.State.PLAYING and Gst.State.PAUSED are
self._sync_playing()
@log
def _gst_plugins_base_check_version(self, major, minor, micro):
gst_major, gst_minor, gst_micro, gst_nano = GstPbutils.plugins_base_version()
return ((gst_major > major) or
(gst_major == major and gst_minor > minor) or
(gst_major == major and gst_minor == minor and gst_micro >= micro) or
(gst_major == major and gst_minor == minor and gst_micro + 1 == micro and gst_nano > 0))
@log
def _start_plugin_installation(self, missing_plugin_messages, confirm_search):
install_ctx = GstPbutils.InstallPluginsContext.new()
if self._gst_plugins_base_check_version(1, 5, 0):
install_ctx.set_desktop_id('gnome-music.desktop')
install_ctx.set_confirm_search(confirm_search)
startup_id = '_TIME%u' % Gtk.get_current_event_time()
install_ctx.set_startup_notification_id(startup_id)
installer_details = []
for message in missing_plugin_messages:
installer_detail = GstPbutils.missing_plugin_message_get_installer_detail(message)
installer_details.append(installer_detail)
def on_install_done(res):
# We get the callback too soon, before the installation has
# actually finished. Do nothing for now.
pass
GstPbutils.install_plugins_async(installer_details, install_ctx, on_install_done)
@log
def _show_codec_confirmation_dialog(self, install_helper_name, missing_plugin_messages):
dialog = MissingCodecsDialog(self._parent_window, install_helper_name)
def on_dialog_response(dialog, response_type):
if response_type == Gtk.ResponseType.ACCEPT:
self._start_plugin_installation(missing_plugin_messages, False)
dialog.destroy()
descriptions = []
for message in missing_plugin_messages:
description = GstPbutils.missing_plugin_message_get_description(message)
descriptions.append(description)
dialog.set_codec_names(descriptions)
dialog.connect('response', on_dialog_response)
dialog.present()
@log
def _handle_missing_plugins(self):
if not self._missingPluginMessages:
return
missing_plugin_messages = self._missingPluginMessages
self._missingPluginMessages = []
if self._gst_plugins_base_check_version(1, 5, 0):
proxy = Gio.DBusProxy.new_sync(Gio.bus_get_sync(Gio.BusType.SESSION, None),
Gio.DBusProxyFlags.NONE,
None,
'org.freedesktop.PackageKit',
'/org/freedesktop/PackageKit',
'org.freedesktop.PackageKit.Modify2',
None)
prop = Gio.DBusProxy.get_cached_property(proxy, 'DisplayName')
if prop:
display_name = prop.get_string()
if display_name:
self._show_codec_confirmation_dialog(display_name, missing_plugin_messages)
return
# If the above failed, fall back to immediately starting the codec installation
self._start_plugin_installation(missing_plugin_messages, True)
@log
def _is_missing_plugin_message(self, message):
error, debug = message.parse_error()
if error.matches(Gst.CoreError.quark(), Gst.CoreError.MISSING_PLUGIN):
return True
return False
@log
def _on_bus_element(self, bus, message):
if GstPbutils.is_missing_plugin_message(message):
self._missingPluginMessages.append(message)
def _onBusError(self, bus, message):
if self._is_missing_plugin_message(message):
self.pause()
self._handle_missing_plugins()
return True
media = self.get_current_media()
if media is not None:
if self.currentTrack and self.currentTrack.valid():
currentTrack = self.playlist.get_iter(self.currentTrack.get_path())
self.playlist.set_value(currentTrack, self.discovery_status_field, DiscoveryStatus.FAILED)
uri = media.get_url()
else:
uri = 'none'
logger.warn('URI: %s', uri)
error, debug = message.parse_error()
debug = debug.split('\n')
debug = [(' ') + line.lstrip() for line in debug]
debug = '\n'.join(debug)
logger.warn('Error from element %s: %s', message.src.get_name(), error.message)
logger.warn('Debugging info:\n%s', debug)
self.play_next()
return True
@log
def _on_bus_eos(self, bus, message):
if self.nextTrack:
GLib.idle_add(self._on_glib_idle)
elif (self.repeat == RepeatType.NONE):
self.stop()
self.playBtn.set_image(self._playImage)
self.progressScale.set_value(0)
self.progressScale.set_sensitive(False)
if self.playlist is not None:
currentTrack = self.playlist.get_path(self.playlist.get_iter_first())
if currentTrack:
self.currentTrack = Gtk.TreeRowReference.new(self.playlist, currentTrack)
self.currentTrackUri = self.playlist.get_value(
self.playlist.get_iter(self.currentTrack.get_path()), 5).get_url()
else:
self.currentTrack = None
self.load(self.get_current_media())
else:
# Stop playback
self.stop()
self.playBtn.set_image(self._playImage)
self.progressScale.set_value(0)
self.progressScale.set_sensitive(False)
self.emit('playback-status-changed')
@log
def _on_glib_idle(self):
self.currentTrack = self.nextTrack
if self.currentTrack and self.currentTrack.valid():
self.currentTrackUri = self.playlist.get_value(
self.playlist.get_iter(self.currentTrack.get_path()), 5).get_url()
self.play()
@log
def _on_playlist_size_changed(self, path, _iter=None, data=None):
self._sync_prev_next()
@log
def _get_random_iter(self, currentTrack):
first_iter = self.playlist.get_iter_first()
if not currentTrack:
currentTrack = first_iter
if not currentTrack:
return None
if hasattr(self.playlist, "iter_is_valid") and\
not self.playlist.iter_is_valid(currentTrack):
return None
currentPath = int(self.playlist.get_path(currentTrack).to_string())
rows = self.playlist.iter_n_children(None)
if rows == 1:
return currentTrack
rand = currentPath
while rand == currentPath:
rand = randint(0, rows - 1)
return self.playlist.get_iter_from_string(str(rand))
@log
def _get_next_track(self):
if self.currentTrack and self.currentTrack.valid():
currentTrack = self.playlist.get_iter(self.currentTrack.get_path())
else:
currentTrack = None
nextTrack = None
if self.repeat == RepeatType.SONG:
if currentTrack:
nextTrack = currentTrack
else:
nextTrack = self.playlist.get_iter_first()
elif self.repeat == RepeatType.ALL:
if currentTrack:
nextTrack = self.playlist.iter_next(currentTrack)
if not nextTrack:
nextTrack = self.playlist.get_iter_first()
elif self.repeat == RepeatType.NONE:
if currentTrack:
nextTrack = self.playlist.iter_next(currentTrack)
elif self.repeat == RepeatType.SHUFFLE:
nextTrack = self._get_random_iter(currentTrack)
if currentTrack:
self.shuffleHistory.append(currentTrack)
if nextTrack:
return Gtk.TreeRowReference.new(self.playlist, self.playlist.get_path(nextTrack))
else:
return None
@log
def _get_iter_last(self):
iter = self.playlist.get_iter_first()
last = None
while iter is not None:
last = iter
iter = self.playlist.iter_next(iter)
return last
@log
def _get_previous_track(self):
if self.currentTrack and self.currentTrack.valid():
currentTrack = self.playlist.get_iter(self.currentTrack.get_path())
else:
currentTrack = None
previousTrack = None
if self.repeat == RepeatType.SONG:
if currentTrack:
previousTrack = currentTrack
else:
previousTrack = self.playlist.get_iter_first()
elif self.repeat == RepeatType.ALL:
if currentTrack:
previousTrack = self.playlist.iter_previous(currentTrack)
if not previousTrack:
previousTrack = self._get_iter_last()
elif self.repeat == RepeatType.NONE:
if currentTrack:
previousTrack = self.playlist.iter_previous(currentTrack)
elif self.repeat == RepeatType.SHUFFLE:
if currentTrack:
if self.played_seconds < 10 and len(self.shuffleHistory) > 0:
previousTrack = self.shuffleHistory.pop()
# Discard the current song, which is already queued
if self.playlist.get_path(previousTrack) == self.playlist.get_path(currentTrack):
previousTrack = None
if previousTrack is None and len(self.shuffleHistory) > 0:
previousTrack = self.shuffleHistory.pop()
else:
previousTrack = self._get_random_iter(currentTrack)
if previousTrack:
return Gtk.TreeRowReference.new(self.playlist, self.playlist.get_path(previousTrack))
else:
return None
@log
def has_next(self):
if not self.playlist or self.playlist.iter_n_children(None) < 1:
return False
elif not self.currentTrack:
return False
elif self.repeat in [RepeatType.ALL, RepeatType.SONG, RepeatType.SHUFFLE]:
return True
elif self.currentTrack.valid():
tmp = self.playlist.get_iter(self.currentTrack.get_path())
return self.playlist.iter_next(tmp) is not None
else:
return True
@log
def has_previous(self):
if not self.playlist or self.playlist.iter_n_children(None) < 1:
return False
elif not self.currentTrack:
return False
elif self.repeat in [RepeatType.ALL, RepeatType.SONG, RepeatType.SHUFFLE]:
return True
elif self.currentTrack.valid():
tmp = self.playlist.get_iter(self.currentTrack.get_path())
return self.playlist.iter_previous(tmp) is not None
else:
return True
@log
def _get_playing(self):
ok, state, pending = self.player.get_state(0)
# log('get playing(), [ok, state, pending] = [%s, %s, %s]'.format(ok, state, pending))
if ok == Gst.StateChangeReturn.ASYNC:
return pending == Gst.State.PLAYING
elif ok == Gst.StateChangeReturn.SUCCESS:
return state == Gst.State.PLAYING
else:
return False
@property
def playing(self):
return self._get_playing()
@log
def _sync_playing(self):
if self._get_playing():
image = self._pauseImage
tooltip = _("Pause")
else:
image = self._playImage
tooltip = _("Play")
if self.playBtn.get_image() != image:
self.playBtn.set_image(image)
self.playBtn.set_tooltip_text(tooltip)
@log
def _sync_prev_next(self):
hasNext = self.has_next()
hasPrevious = self.has_previous()
self.nextBtn.set_sensitive(hasNext)
self.prevBtn.set_sensitive(hasPrevious)
self.emit('prev-next-invalidated')
@log
def set_playing(self, value):
self.actionbar.show()
if value:
self.play()
else:
self.pause()
media = self.get_current_media()
self.playBtn.set_image(self._pauseImage)
return media
@log
def load(self, media):
self.progressScale.set_value(0)
self._set_duration(media.get_duration())
self.songTotalTimeLabel.set_label(self.seconds_to_string(media.get_duration()))
self.progressScale.set_sensitive(True)
self.playBtn.set_sensitive(True)
self._sync_prev_next()
artist = _("Unknown Artist")
try:
assert media.get_artist() is not None
artist = media.get_artist()
except:
pass
finally:
self.artistLabel.set_label(artist)
self._currentArtist = artist
album = _("Unknown Album")
try:
assert media.get_album() is not None
album = media.get_album()
except:
self._currentAlbum = album
self.coverImg.set_from_pixbuf(self._noArtworkIcon)
self.cache.lookup(
media, ART_SIZE, ART_SIZE, self._on_cache_lookup, None, artist, album)
self._currentTitle = AlbumArtCache.get_media_title(media)
self.titleLabel.set_label(self._currentTitle)
self._currentTimestamp = int(time.time())
url = media.get_url()
if url != self.player.get_value('current-uri', 0):
self.player.set_property('uri', url)
if self.currentTrack and self.currentTrack.valid():
currentTrack = self.playlist.get_iter(self.currentTrack.get_path())
self.emit('playlist-item-changed', self.playlist, currentTrack)
self.emit('current-changed')
self._validate_next_track()
def _on_next_item_validated(self, info, error, _iter):
if error:
print("Info %s: error: %s" % (info, error))
self.playlist.set_value(_iter, self.discovery_status_field, DiscoveryStatus.FAILED)
nextTrack = self.playlist.iter_next(_iter)
if nextTrack:
self._validate_next_track(Gtk.TreeRowReference.new(self.playlist, self.playlist.get_path(nextTrack)))
@log
def _validate_next_track(self, track=None):
if track is None:
track = self._get_next_track()
self.nextTrack = track
if track is None:
return
_iter = self.playlist.get_iter(self.nextTrack.get_path())
status = self.playlist.get_value(_iter, self.discovery_status_field)
nextSong = self.playlist.get_value(_iter, self.playlistField)
url = self.playlist.get_value(_iter, 5).get_url()
# Skip remote tracks discovery
if url.startswith("http://"):
status = DiscoveryStatus.SUCCEEDED
elif status == DiscoveryStatus.PENDING:
self.discover_item(nextSong, self._on_next_item_validated, _iter)
elif status == DiscoveryStatus.FAILED:
GLib.idle_add(self._validate_next_track)
return False
@log
def _on_cache_lookup(self, pixbuf, path, data=None):
if pixbuf is not None:
self.coverImg.set_from_pixbuf(pixbuf)
self.emit('thumbnail-updated', path)
@log
def play(self):
if self.playlist is None:
return
media = None
if self.player.get_state(1)[1] != Gst.State.PAUSED:
self.stop()
media = self.get_current_media()
if not media:
return
self.load(media)
self.player.set_state(Gst.State.PLAYING)
self._update_position_callback()
if media:
t = Thread(target=self.update_now_playing_in_lastfm, args=(media.get_url(),))
t.setDaemon(True)
t.start()
if not self.timeout:
self.timeout = GLib.timeout_add(1000, self._update_position_callback)
self.emit('playback-status-changed')
self.emit('playing-changed')
@log
def pause(self):
if self.timeout:
GLib.source_remove(self.timeout)
self.timeout = None
self.player.set_state(Gst.State.PAUSED)
self.emit('playback-status-changed')
self.emit('playing-changed')
@log
def stop(self):
if self.timeout:
GLib.source_remove(self.timeout)
self.timeout = None
self.player.set_state(Gst.State.NULL)
self.emit('playing-changed')
@log
def play_next(self):
if self.playlist is None:
return True
if not self.nextBtn.get_sensitive():
return True
self.stop()
self.currentTrack = self._get_next_track()
if self.currentTrack and self.currentTrack.valid():
self.currentTrackUri = self.playlist.get_value(
self.playlist.get_iter(self.currentTrack.get_path()), 5).get_url()
self.play()
@log
def play_previous(self):
if self.playlist is None:
return
if self.prevBtn.get_sensitive() is False:
return
position = self.get_position() / 1000000
if position >= 5:
self.progressScale.set_value(0)
self.on_progress_scale_change_value(self.progressScale)
return
self.stop()
self.currentTrack = self._get_previous_track()
if self.currentTrack and self.currentTrack.valid():
self.currentTrackUri = self.playlist.get_value(
self.playlist.get_iter(self.currentTrack.get_path()), 5).get_url()
self.play()
@log
def play_pause(self):
if self.player.get_state(1)[1] == Gst.State.PLAYING:
self.set_playing(False)
else:
self.set_playing(True)
@log
def set_playlist(self, type, id, model, iter, field, discovery_status_field):
self.stop()
old_playlist = self.playlist
if old_playlist != model:
self.playlist = model
if self.playlist_insert_handler:
old_playlist.disconnect(self.playlist_insert_handler)
if self.playlist_delete_handler:
old_playlist.disconnect(self.playlist_delete_handler)
self.playlistType = type
self.playlistId = id
self.currentTrack = Gtk.TreeRowReference.new(model, model.get_path(iter))
if self.currentTrack and self.currentTrack.valid():
self.currentTrackUri = self.playlist.get_value(
self.playlist.get_iter(self.currentTrack.get_path()), 5).get_url()
self.playlistField = field
self.discovery_status_field = discovery_status_field
if old_playlist != model:
self.playlist_insert_handler = model.connect('row-inserted', self._on_playlist_size_changed)
self.playlist_delete_handler = model.connect('row-deleted', self._on_playlist_size_changed)
self.emit('playlist-changed')
self.emit('current-changed')
@log
def running_playlist(self, type, id):
if type == self.playlistType and id == self.playlistId:
return self.playlist
else:
return None
@log
def _setup_view(self):
self._ui = Gtk.Builder()
self._ui.add_from_resource('/org/gnome/Music/PlayerToolbar.ui')
self.actionbar = self._ui.get_object('actionbar')
self.prevBtn = self._ui.get_object('previous_button')
self.playBtn = self._ui.get_object('play_button')
self.nextBtn = self._ui.get_object('next_button')
self._playImage = self._ui.get_object('play_image')
self._pauseImage = self._ui.get_object('pause_image')
self.progressScale = self._ui.get_object('progress_scale')
self.songPlaybackTimeLabel = self._ui.get_object('playback')
self.songTotalTimeLabel = self._ui.get_object('duration')
self.titleLabel = self._ui.get_object('title')
self.artistLabel = self._ui.get_object('artist')
self.coverImg = self._ui.get_object('cover')
self.duration = self._ui.get_object('duration')
self.repeatBtnImage = self._ui.get_object('playlistRepeat')
if Gtk.Settings.get_default().get_property('gtk_application_prefer_dark_theme'):
color = Gdk.RGBA(red=1.0, green=1.0, blue=1.0, alpha=1.0)
else:
color = Gdk.RGBA(red=0.0, green=0.0, blue=0.0, alpha=0.0)
self._playImage.override_color(Gtk.StateFlags.ACTIVE, color)
self._pauseImage.override_color(Gtk.StateFlags.ACTIVE, color)
self._sync_repeat_image()
self.prevBtn.connect('clicked', self._on_prev_btn_clicked)
self.playBtn.connect('clicked', self._on_play_btn_clicked)
self.nextBtn.connect('clicked', self._on_next_btn_clicked)
self.progressScale.connect('button-press-event', self._on_progress_scale_event)
self.progressScale.connect('value-changed', self._on_progress_value_changed)
self.progressScale.connect('button-release-event', self._on_progress_scale_button_released)
@log
def _on_progress_scale_button_released(self, scale, data):
self.on_progress_scale_change_value(self.progressScale)
self._update_position_callback()
self.player.set_state(self._lastState)
self.timeout = GLib.timeout_add(1000, self._update_position_callback)
return False
def _on_progress_value_changed(self, widget):
seconds = int(self.progressScale.get_value() / 60)
self.songPlaybackTimeLabel.set_label(self.seconds_to_string(seconds))
return False
@log
def _on_progress_scale_event(self, scale, data):
self._lastState = self.player.get_state(1)[1]
self.player.set_state(Gst.State.PAUSED)
if self.timeout:
GLib.source_remove(self.timeout)
self.timeout = None
return False
def seconds_to_string(self, duration):
seconds = duration
minutes = seconds // 60
seconds %= 60
return '%i:%02i' % (minutes, seconds)
@log
def _on_play_btn_clicked(self, btn):
if self._get_playing():
self.pause()
else:
self.play()
@log
def _on_next_btn_clicked(self, btn):
self.play_next()
@log
def _on_prev_btn_clicked(self, btn):
self.play_previous()
@log
def _set_duration(self, duration):
self.duration = duration
self.played_seconds = 0
self.scrobbled = False
self.progressScale.set_range(0.0, duration * 60)
@log
def scrobble_song(self, url):
# Update playlists
playlists.update_playcount(url)
playlists.update_last_played(url)
playlists.update_all_static_playlists()
if self.last_fm:
api_key = self.last_fm.props.client_id
sk = self.last_fm.call_get_access_token_sync(None)[0]
secret = self.last_fm.props.client_secret
sig = "api_key%sartist[0]%smethodtrack.scrobblesk%stimestamp[0]%strack[0]%s%s" %\
(api_key, self._currentArtist, sk, self._currentTimestamp, self._currentTitle, secret)
api_sig = md5(sig.encode()).hexdigest()
requests_dict = {
"api_key": api_key,
"method": "track.scrobble",
"artist[0]": self._currentArtist,
"track[0]": self._currentTitle,
"timestamp[0]": self._currentTimestamp,
"sk": sk,
"api_sig": api_sig
}
try:
r = requests.post("https://ws.audioscrobbler.com/2.0/", requests_dict)
if r.status_code != 200:
logger.warn("Failed to scrobble track: %s %s" % (r.status_code, r.reason))
logger.warn(r.text)
except Exception as e:
logger.warn(e)
@log
def update_now_playing_in_lastfm(self, url):
if self.last_fm:
api_key = self.last_fm.props.client_id
sk = self.last_fm.call_get_access_token_sync(None)[0]
secret = self.last_fm.props.client_secret
sig = "api_key%sartist%smethodtrack.updateNowPlayingsk%strack%s%s" % \
(api_key, self._currentArtist, sk, self._currentTitle, secret)
api_sig = md5(sig.encode()).hexdigest()
request_dict = {
"api_key": api_key,
"method": "track.updateNowPlaying",
"artist": self._currentArtist,
"track": self._currentTitle,
"sk": sk,
"api_sig": api_sig
}
try:
r = requests.post("https://ws.audioscrobbler.com/2.0/", request_dict)
if r.status_code != 200:
logger.warn("Failed to update currently played track: %s %s" % (r.status_code, r.reason))
logger.warn(r.text)
except Exception as e:
logger.warn(e)
def _update_position_callback(self):
position = self.player.query_position(Gst.Format.TIME)[1] / 1000000000
if position > 0:
self.progressScale.set_value(position * 60)
self.played_seconds += 1
try:
percentage = self.played_seconds / self.duration
if not self.scrobbled and percentage > 0.4:
current_media = self.get_current_media()
self.scrobbled = True
if current_media:
just_played_url = self.get_current_media().get_url()
t = Thread(target=self.scrobble_song, args=(just_played_url,))
t.setDaemon(True)
t.start()
except Exception as e:
logger.warn("Error: %s, %s", e.__class__, e)
return True
@log
def _sync_repeat_image(self):
icon = None
if self.repeat == RepeatType.NONE:
icon = 'media-playlist-consecutive-symbolic'
elif self.repeat == RepeatType.SHUFFLE:
icon = 'media-playlist-shuffle-symbolic'
elif self.repeat == RepeatType.ALL:
icon = 'media-playlist-repeat-symbolic'
elif self.repeat == RepeatType.SONG:
icon = 'media-playlist-repeat-song-symbolic'
self.repeatBtnImage.set_from_icon_name(icon, Gtk.IconSize.MENU)
self.emit('repeat-mode-changed')
@log
def on_progress_scale_change_value(self, scroll):
seconds = scroll.get_value() / 60
if seconds != self.duration:
self.player.seek_simple(Gst.Format.TIME, Gst.SeekFlags.FLUSH | Gst.SeekFlags.KEY_UNIT, seconds * 1000000000)
try:
self.emit('seeked', seconds * 1000000)
except TypeError:
# See https://bugzilla.gnome.org/show_bug.cgi?id=733095
pass
else:
duration = self.player.query_duration(Gst.Format.TIME)
if duration:
# Rewind a second back before the track end
self.player.seek_simple(Gst.Format.TIME, Gst.SeekFlags.FLUSH | Gst.SeekFlags.KEY_UNIT, duration[1] - 1000000000)
try:
self.emit('seeked', (duration[1] - 1000000000) / 1000)
except TypeError:
# See https://bugzilla.gnome.org/show_bug.cgi?id=733095
pass
return True
# MPRIS
@log
def Stop(self):
self.progressScale.set_value(0)
self.progressScale.set_sensitive(False)
self.playBtn.set_image(self._playImage)
self.stop()
self.emit('playback-status-changed')
@log
def get_playback_status(self):
ok, state, pending = self.player.get_state(0)
if ok == Gst.StateChangeReturn.ASYNC:
state = pending
elif (ok != Gst.StateChangeReturn.SUCCESS):
return PlaybackStatus.STOPPED
if state == Gst.State.PLAYING:
return PlaybackStatus.PLAYING
elif state == Gst.State.PAUSED:
return PlaybackStatus.PAUSED
else:
return PlaybackStatus.STOPPED
@log
def get_repeat_mode(self):
return self.repeat
@log
def set_repeat_mode(self, mode):
self.repeat = mode
self._sync_repeat_image()
@log
def get_position(self):
return self.player.query_position(Gst.Format.TIME)[1] / 1000
@log
def set_position(self, offset, start_if_ne=False, next_on_overflow=False):
if offset < 0:
if start_if_ne:
offset = 0
else:
return
duration = self.player.query_duration(Gst.Format.TIME)
if duration is None:
return
if duration[1] >= offset * 1000:
self.player.seek_simple(Gst.Format.TIME, Gst.SeekFlags.FLUSH | Gst.SeekFlags.KEY_UNIT, offset * 1000)
self.emit('seeked', offset)
elif next_on_overflow:
self.play_next()
@log
def get_volume(self):
return self.player.get_volume(GstAudio.StreamVolumeFormat.LINEAR)
@log
def set_volume(self, rate):
self.player.set_volume(GstAudio.StreamVolumeFormat.LINEAR, rate)
self.emit('volume-changed')
@log
def get_current_media(self):
if not self.currentTrack or not self.currentTrack.valid():
return None
currentTrack = self.playlist.get_iter(self.currentTrack.get_path())
if self.playlist.get_value(currentTrack, self.discovery_status_field) == DiscoveryStatus.FAILED:
return None
return self.playlist.get_value(currentTrack, self.playlistField)
class MissingCodecsDialog(Gtk.MessageDialog):
def __repr__(self):
return '<MissingCodecsDialog>'
@log
def __init__(self, parent_window, install_helper_name):
Gtk.MessageDialog.__init__(self,
transient_for=parent_window,
modal=True,
destroy_with_parent=True,
message_type=Gtk.MessageType.ERROR,
buttons=Gtk.ButtonsType.CANCEL,
text=_("Unable to play the file"))
# TRANSLATORS: this is a button to launch a codec installer.
# %s will be replaced with the software installer's name, e.g.
# 'Software' in case of gnome-software.
self.find_button = self.add_button(_("_Find in %s") % install_helper_name,
Gtk.ResponseType.ACCEPT)
self.set_default_response(Gtk.ResponseType.ACCEPT)
Gtk.StyleContext.add_class(self.find_button.get_style_context(), 'suggested-action')
@log
def set_codec_names(self, codec_names):
n_codecs = len(codec_names)
if n_codecs == 2:
# TRANSLATORS: separator for a list of codecs
text = _(" and ").join(codec_names)
else:
# TRANSLATORS: separator for a list of codecs
text = _(", ").join(codec_names)
self.format_secondary_text(ngettext("%s is required to play the file, but is not installed.",
"%s are required to play the file, but are not installed.",
n_codecs) % text)
class SelectionToolbar():
def __repr__(self):
return '<SelectionToolbar>'
@log
def __init__(self):
self._ui = Gtk.Builder()
self._ui.add_from_resource('/org/gnome/Music/SelectionToolbar.ui')
self.actionbar = self._ui.get_object('actionbar')
self._add_to_playlist_button = self._ui.get_object('button1')
self._remove_from_playlist_button = self._ui.get_object('button2')
self.actionbar.set_visible(False)
|