summaryrefslogtreecommitdiff
path: root/valosoitin/Valosoitin.py
blob: 3951e26bf3f84c86a2e5d03908967c26352d50af (plain)
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
#!/usr/bin/env python2
#
#  Valosoitin - Audio player for EFL
#
#  Copyright 2012-2013 Kai Huuhko <kai.huuhko@gmail.com>
#
#  This program 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 3 of the License, or
#  (at your option) any later version.
#
#  This program 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 this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#

import sys
import os
import time
import urllib
import argparse
import datetime
import cgi
try:
    import ConfigParser
except ImportError:
    from configparser import ConfigParser
try:
    import cPickle
except ImportError:
    import pickle as cPickle

import random
random.seed()

import mimetypes
mimetypes.init()
mimetypes.add_type("audio/opus", ".opus", strict=True)

import logging
logging.basicConfig(level=logging.DEBUG)

import gettext
try:
    gettext.install("valosoitin", unicode=True)
except TypeError:
    gettext.install("valosoitin")

import mutagen
import mutagen.mp3
import mutagen.id3
import mutagen.flac
import mutagen.oggvorbis

import elementary as elm
from ecore import Timer, Idler
from emotion import Emotion

from ValoDBus import ValosoitinDBus
from gui import PlayControls, PlayModes, VolumeControls, PlayList, PlayListControls, SeekControls, AudioInfo

try:
    from gi.repository import Notify
except ImportError:
    def notify(*args):
        pass
else:
    Notify.init("Valosoitin")
    def notify(title, msg, importance):
        n = Notify.Notification.new(title, msg, importance)
        n.set_timeout(3000)
        n.show()

parser = argparse.ArgumentParser(description='Utters sounds.')
parser.add_argument("files", metavar="file", type=str, nargs="*",
                    help="Files to add to the playlist")
clargs = parser.parse_args(sys.argv[1:])

import dbus, e_dbus
ml = e_dbus.DBusEcoreMainLoop()
dbus.set_default_main_loop(ml)
import dbus.service
bus = dbus.SessionBus()

dbo = None
try:
    dbo = bus.get_object("org.mpris.MediaPlayer2.Valosoitin", "/org/mpris/MediaPlayer2")
except dbus.exceptions.DBusException:
    pass

if dbo:
    if clargs.files:
        for f in clargs.files:
            dbo.OpenUri(f, dbus_interface="org.mpris.MediaPlayer2.Player")
    sys.exit()

conf = ConfigParser.SafeConfigParser()
conf_dir = os.path.expanduser(os.path.join("~", ".config", "valosoitin"))
conf_path = os.path.join(conf_dir, "valosoitin.conf")
if not os.path.exists(conf_dir):
    os.mkdir(conf_dir, 0x700)
if not os.path.exists(os.path.join(conf_path)):
    conf.add_section("Settings")
    conf.set("Settings", "audio_backend", "gstreamer")
    conf.set("Settings", "single", "False")
    conf.set("Settings", "random", "False")
    conf.set("Settings", "repeat", "False")
    conf.set("Settings", "volume", "100.0")
    conf.set("Settings", "mute", "False")
    conf.add_section("Last played")
    conf.set("Last played", "filename", "")
    with open(conf_path, 'wb') as configfile:
        conf.write(configfile)
conf.read(conf_path)
for section in ("Settings", "Last played"):
    if not conf.has_section(section):
        conf.add_section(section)

try:
    if not conf.get("Settings", "audio_backend") in ("gstreamer", "xine"):
        logging.error("Invalid audio backend in config file. Set it to either gstreamer or xine.")
        sys.exit()
except:
    logging.error("audio_backend was not found in settings file. Set it to a value or remove the settings file so that a new one will be generated at next start of this program.")

class Valosoitin(object):
    def __init__(self, *args):
        self.conf = conf

        self.duration = datetime.timedelta()
        self.position = datetime.timedelta()

        self.seeking = False
        self.playtimer = None

        self.library = {}
        self.randomorder = []

        self.progress_bar_notify = None

        window = self.window = elm.StandardWindow("valosoitin", "Valosoitin")
        window.callback_delete_request_add(self.quit)
        window.callback_withdrawn_add(lambda x: self.playtimer.freeze())
        window.callback_iconified_add(lambda x: self.playtimer.freeze())
        window.callback_normal_add(self.normal_window)

        # GUI
        self.playcontrols = PlayControls(self)
        self.volumecontrols = VolumeControls(self)
        self.playmodes = PlayModes(self)
        self.seekcontrols = SeekControls(self)
        self.audioinfo = AudioInfo(self)
        self.playlist = PlayList(self)
        self.playlistcontrols = PlayListControls(self)

        # Top left box
        topleftbox = elm.Box(window)
        topleftbox.pack_end(self.playcontrols)
        topleftbox.pack_end(self.volumecontrols)
        topleftbox.pack_end(self.playmodes)
        topleftbox.show()

        # Top right box
        toprightbox = elm.Box(window)
        toprightbox.size_hint_weight_set(1.0, 0.0)
        toprightbox.size_hint_align_set(-1.0, 0.0)
        toprightbox.pack_end(self.seekcontrols)
        toprightbox.pack_end(self.audioinfo)
        toprightbox.show()

        # Top box
        topbox = elm.Box(window)
        topbox.horizontal_set(True)
        topbox.size_hint_weight_set(1.0, 0.0)
        topbox.size_hint_align_set(-1.0, 0.0)
        topbox.pack_end(topleftbox)
        topbox.pack_end(toprightbox)
        topbox.show()

        # Main box
        mainbox = elm.Box(window)
        mainbox.size_hint_weight_set(1.0, 1.0)
        window.resize_object_add(mainbox)
        mainbox.pack_end(topbox)
        mainbox.pack_end(self.playlist)
        mainbox.pack_end(self.playlistcontrols)
        mainbox.show()

        # Setup GUI update timer
        self.playtimer = playtimer = Timer(0.2, self.update)
        playtimer.freeze()

        # Setup Emotion
        try:
            self.player = player = Emotion(window.evas_get(), module_name=conf.get("Settings", "audio_backend"))
        except TypeError:
            self.player = player = Emotion(window.evas_get(), module_filename=conf.get("Settings", "audio_backend"))
        player.video_mute_set(True)
        player.callback_add("playback_started", self.playing)
        player.callback_add("playback_finished", self.finished)

        self.dbusname = dbus.service.BusName("org.mpris.MediaPlayer2.Valosoitin", dbus.SessionBus())
        self.dbo = ValosoitinDBus(self)

        window.resize(480, 480)
        window.show()

        # Restore playlist
        order = []
        try:
            with open(os.path.expanduser(os.path.join("~", ".local", "share", "valosoitin.library")), 'rb') as pkl_file:
                l = cPickle.load(pkl_file)
                if not isinstance(l, list):
                    self.library = l

            with open(os.path.expanduser(os.path.join("~", ".local", "share", "valosoitin.playlist_order")), 'rb') as pkl_file:
                order = cPickle.load(pkl_file)
        except:
            logging.exception("Could not restore playlist")

        paths = []
        for i in order:
            paths.append(self.library[i])

        for m in paths:
            f = m.filename
            if not os.path.exists(f):
                del self.library[f]

            self.playlist.add_item(self, m)

        f = conf.get("Last played", "filename")
        if f:
            if os.path.exists(f) and self.library.has_key(f):
                self.play_file(f, paused=True)

        self.playlist.show()
        self.randomize()

        self.change_volume(conf.getfloat("Settings", "volume"))
        self.mute(conf.getboolean("Settings", "mute"))

        # Add files from command line
        if clargs.files:
            self.add_files_with_idler(clargs.files)

    def raise_window(self):
        self.window.raise_()

    def normal_window(self, *args):
        if self.player.play_get():
            self.playtimer.thaw()
        else:
            self.update()

    def update(self):
        pos = self.player.position_get()
        self.dbo.playerprops["Position"] = pos*1000000

        if not self.seeking:
            self.seekcontrols.seek.value = pos
        pos = datetime.timedelta(seconds=int(pos))
        self.position = pos
        t = "%s / %s" % (pos, self.duration)
        self.seekcontrols.seektime.text_set(t)

        dur = self.player.play_length
        if dur != self.duration:
            self.seekcontrols.seek.min_max_set(0, dur)
            dur = datetime.timedelta(seconds=int(dur))
            self.duration = dur
            self.dbo.playerprops["Metadata"]["mpris:length"] = int(dur.total_seconds()) * 1000000

        return 1

    def add_files_with_idler(self, paths):
        if len(paths) > 200:
            for widget in self.playlistcontrols.children:
                widget.disabled = True
            self.audioinfo.search.disabled = True
            self.pbaru = 1.0/len(paths)
            pbarn = self.progress_bar_notify = elm.Notify(self.window)
            pbarn.orient = elm.ELM_NOTIFY_ORIENT_BOTTOM
            pbar = self.pbar = elm.Progressbar(self.window)
            pbarn.content = pbar
            pbar.span_size = self.window.size[0] - 100
            pbarn.show()

        logging.debug("Adding files")
        self.time1 = time.clock()
        logging.debug(self.time1)

        path_generator = (f for f in paths)
        idler = Idler(self.add_file, path_generator)

    def add_file(self, paths):
        try:
            f = paths.next()
        except StopIteration:
            self.time2 = time.clock()
            logging.debug(self.time2)
            logging.debug(self.time2 - self.time1)
            if self.progress_bar_notify:
                self.progress_bar_notify.delete()
                self.progress_bar_notify = None
                for widget in self.playlistcontrols.children:
                    widget.disabled = False
                self.audioinfo.search.disabled = False
                self.audioinfo.search.focus = True
            self.randomize()
            return False

        if self.progress_bar_notify:
            self.pbar.value = self.pbar.value + self.pbaru

        if not os.path.exists(f):
            logging.info("File doesn't exist")
            return True

        m = self.check_mime_type(f)
        if m is False:
            return True

        # Playlist items are unique by filepath
        if not self.library.has_key(f):
            self.library[f] = m

            self.playlist.add_item(self, m)
        else:
            logging.info("Audio already on playlist")

        return True

    def check_mime_type(self, f):
        mimetype = mimetypes.guess_type(f, strict=False)[0]
        if not mimetype:
            logging.info("Invalid type %s for file %s" % (mimetype, f))
            return False
        elif not mimetype.startswith("audio"):
            logging.info("Invalid type %s for file %s" % (mimetype, f))
            return False

        m = None

        if mimetype == "audio/mpeg":
            try:
                m = EasyID3(f)
            except mutagen.id3.ID3NoHeaderError:
                try:
                    m = mutagen.mp3.MP3(f)
                except mutagen.mp3.HeaderNotFoundError:
                    logging.info("Mpeg audio header not found.")
        elif mimetype == "audio/flac":
            try:
                m = mutagen.flac.FLAC(f)
            except mutagen.flac.FLACNoHeaderError:
                logging.info("Invalid header in FLAC file.")
            except mutagen.flac.FLACVorbisError:
                logging.info("Invalid header in FLAC vorbis file.")
        elif mimetype == "audio/opus":
            try:
                m = mutagen.oggopus.OggOpus(f)
            except mutagen.oggopus.OggOpusHeaderError:
                logging.info("Invalid header in Opus file.")
        elif mimetype == "audio/ogg":
            try:
                m = mutagen.oggvorbis.OggVorbis(f)
            except mutagen.oggvorbis.OggVorbisHeaderError:
                logging.info("Invalid header in Ogg Vorbis file.")
        else:
            logging.info("No known mutagen type for %s." % mimetype)

        if m is None:
            logging.info("Trying generic type for %s" % f)
            try:
                m = mutagen.File(f, easy=True)
            except Exception:
                pass

        if m is None:
            return False

        #~ "audio/basic",
        #~ "audio/mid",
        #~ "audio/mp4",
        #~ "audio/ogg",
        #~ "audio/vorbis",
        #~ "audio/wav",
        #~ "audio/x-wav",

        return m

    def add_dir(self, path):
        if not path:
            return
        paths = []
        for dirpath, dirnames, filenames in os.walk(path):
            for filename in filenames:
                paths.append(os.path.join(dirpath, filename))
        paths.sort()
        self.add_files_with_idler(paths)

    def play_file(self, f, paused=False):
        current_file = self.player.file_get()
        current_item = None
        new_item = None

        if current_file:
            try:
                current_item = self.playlist.items[urllib.unquote(current_file.split("://")[1])]
            except KeyError:
                pass

        try:
            new_item = self.playlist.items[f]
        except KeyError:
            logging.exception("Item for {0} not found".format(f))

        self.player.file_set("file://"+urllib.quote(f))
        if not paused:
            self.play()
        #self.player.position = 0.0

        if current_item:
            current_item.fields_update("elm.swallow.icon", elm.ELM_GENLIST_ITEM_FIELD_CONTENT)
        if new_item:
            new_item.fields_update("elm.swallow.icon", elm.ELM_GENLIST_ITEM_FIELD_CONTENT)

    def play_pause(self, *args):
        if self.player.play_get():
            self.pause()
        else:
            self.play()

    def play(self):
        if self.player.play_get():
            return
        ic = elm.Icon(self.window)
        if not self.player.file_get():
            i = self.playlist.selected_item
            if not i:
                try:
                    f = self.playlist.order[0]
                except:
                    logging.info("No files on the playlist")
                    return
                i = self.playlist.items[f]
            m = i.data_get()
            self.play_file(m.filename)
            return
        self.player.play_set(True)
        ic.standard_set("media-playback-pause")
        self.playcontrols.play.content_set(ic)
        self.playtimer.thaw()
        self.dbo.playerprops["PlaybackStatus"] = "Playing"

    def pause(self, override=False):
        if not self.player.play_get() and not override:
            return
        ic = elm.Icon(self.window)
        self.player.play_set(False)
        ic.standard_set("media-playback-start")
        self.playcontrols.play.content_set(ic)
        self.playcontrols.play.size_hint_min_set(30, 30)
        self.playtimer.freeze()
        self.dbo.playerprops["PlaybackStatus"] = "Paused"

    def nx(self, btn, prev=False):
        f = self.player.file_get()
        if f:
            f = urllib.unquote(f).split("://")[1]
        else:
            return
        c_i = self.playlist.order.index(f)
        if self.playmodes.random.state:
            i = self.randomorder.index(c_i)
            if prev:
                i = i-1
                if i < 0:
                    if self.playmodes.repeat.state:
                        i = len(self.playlist.order)-1
                    else:
                        return
            else:
                i = i+1
                if i > len(self.playlist.order)-1:
                    if self.playmodes.repeat.state:
                        i = 0
                    else:
                        return
            next_i = self.randomorder[i]
        else:
            if prev:
                next_i = c_i - 1
                if next_i < 0:
                    next_i = None
            else:
                next_i = c_i + 1
                if next_i >= len(self.playlist.order):
                    next_i = None
        if not next_i:
            if self.playmodes.repeat.state:
                next_i = 0
            else:
                if not btn:
                    # End of playlist
                    self.pause(True)
                return
        f = self.playlist.order[next_i]
        self.play_file(f)

    def seekstart(self, slider):
        self.seeking = True

    def seektime(self, slider, t=None):
        self.seeking = False
        t = t if t is not None else slider.value
        ft = datetime.timedelta(seconds=int(t))
        d = self.duration
        self.seekcontrols.seektime.text_set("%s / %s" % (ft, d))
        self.player.position_set(t)
        self.dbo.Seeked(t*1000000)

    def seek_by(self, t):
        ct = self.player.position_get()
        t = ct+t
        self.seektime(None, t)

    def change_volume(self, value):
        self.player.audio_volume_set(value/100)
        self.dbo.playerprops["Volume"] = value/100
        self.conf.set("Settings", "volume", str(value))

    def mute(self, state):
        self.volumecontrols.volume.disabled = state
        self.player.audio_mute_set(state)
        self.conf.set("Settings", "mute", str(state))

    def set_single_mode(self, mode):
        if self.playmodes.repeat.state:
            if mode:
                v = "Track"
            else:
                v = "Playlist"
        else:
            v = "None"
        self.dbo.playerprops["LoopStatus"] = mode
        self.conf.set("Settings", "single", str(mode))

    def set_repeat_mode(self, mode):
        if mode:
            if self.playmodes.single.state:
                v = "Track"
            else:
                v = "Playlist"
        else:
            v = "None"
        self.dbo.playerprops["LoopStatus"] = mode
        self.conf.set("Settings", "repeat", str(mode))

    def set_random_mode(self, mode):
        self.dbo.playerprops["Shuffle"] = mode
        self.conf.set("Settings", "random", str(mode))

    def playing(self, player):
        f = urllib.unquote(self.player.file_get()).split("://")[1]
        m = self.library[f]

        titles = cgi.escape(", ".join(m.get("title"))) if m.get("title") else os.path.splitext(os.path.basename(m.filename))[0]
        artists = cgi.escape(", ".join(m.get("artist"))) if m.get("artist") else ""
        albums = cgi.escape(", ".join(m.get("album"))) if m.get("album") else ""

        self.audioinfo.title.text = _("title <b>{0}</b>").format(titles)
        self.audioinfo.artist.text = _("by <i>{0}</i>").format(artists) if artists else ""
        self.audioinfo.album.text = _("from the album <b>{0}</b>").format(albums) if albums else ""

        self.dbo.playerprops["Metadata"]["mpris:trackid"] = f

        self.dbo.playerprops["Metadata"]["xesam:title"] = titles
        self.dbo.playerprops["Metadata"]["xesam:artist"] = artists
        self.dbo.playerprops["Metadata"]["xesam:album"] = albums

        notify(_("You're listening to"), "\n".join(filter(None, (artists, titles, albums))), "notification-information")

    def finished(self, player):
        if self.playmodes.single.state:
            if self.playmodes.repeat.state:
                self.seektime(None, 0)
                self.play()
            else:
                self.pause(True)
        else:
            self.nx(None)

    def randomize(self):
        # Create a list from 0 to length of playlist, then shuffle it
        o = [x for x in range(self.playlist.items_count())]
        random.shuffle(o)
        self.randomorder = o

    def search(self, string, cb):
        logging.debug("Searching")
        time1 = time.clock()
        logging.debug(time1)

        result = {}
        for k, m in self.library.iteritems():
            if not m:
                if string.lower() in k.decode("utf-8").lower():
                    result[k] = m
                continue

            for tag in m.itervalues():
                for v in tag:
                    if string.lower() in v.lower():
                        result[k] = m

        ordered_result = []
        for k in sorted(result.iterkeys()):
            ordered_result.append(result[k])

        time2 = time.clock()
        logging.debug(time2)
        logging.debug(time2 - time1)

        e = ""

        if result:
            cb(string, ordered_result)
        else:
            n = elm.Notify(self.window)
            n.orient = elm.ELM_NOTIFY_ORIENT_TOP
            l = elm.Label(self.window)
            l.text = _("No results for {0}").format(string)
            n.content = l
            n.timeout = 2.0
            n.show()

    def quit(self, *args):

        try:
            with open(os.path.expanduser(os.path.join("~", ".local", "share", "valosoitin.library")), 'wb') as output:
                cPickle.dump(self.library, output, 2)
        except:
            logging.exception("Could not save library")

        try:
            with open(os.path.expanduser(os.path.join("~", ".local", "share", "valosoitin.playlist_order")), 'wb') as output:
                cPickle.dump(self.playlist.order, output, 2)
        except:
            logging.exception("Could not save playlist order")

        try:
            conf.set("Last played", "filename", urllib.unquote(self.player.file_get()).split("://")[1] if self.player.file_get() else "")
            with open(conf_path, 'wb') as configfile:
                conf.write(configfile)
        except:
            logging.exception("Could not save conf")

        elm.exit()

# XXX: Monkey patching mutagen to fix http://code.google.com/p/mutagen/issues/detail?id=102
#      This can be removed once 1.21 becomes common
class EasyID3(mutagen.easyid3.EasyID3):
    def __init__(self, filename=None):
        self.__id3 = mutagen.id3.ID3()
        if filename is not None:
            self.load(filename)

    load = property(lambda s: s.__id3.load,
                    lambda s, v: setattr(s.__id3, 'load', v))

    save = property(lambda s: s.__id3.save,
                    lambda s, v: setattr(s.__id3, 'save', v))

    delete = property(lambda s: s.__id3.delete,
                      lambda s, v: setattr(s.__id3, 'delete', v))

if __name__ == "__main__":
    elm.init()
    valosoitin = Valosoitin(None)
    elm.run()
    elm.shutdown()