summaryrefslogtreecommitdiff
path: root/lib/mpris/player.vala
blob: ed146f6b5e42e389ae08ef70e9e314ae8f0b03df (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
namespace AstalMpris {
public class Player : Object {
    private static string COVER_CACHE = Environment.get_user_cache_dir() + "/astal/mpris";

    private IPlayer proxy;

    public signal void appeared () { available = true; }
    public signal void closed () { available = false; }

    // identifiers
    public string bus_name { owned get; construct set; }
    public bool available { get; private set; }

    // periodically notify position
    private uint pollid;

    // mpris
    public void raise() {
        try { proxy.raise(); } catch (Error error) { critical(error.message); }
    }

    public void quit() {
        try { proxy.quit(); } catch (Error error) { critical(error.message); }
    }

    public bool can_quit { get; private set; }
    public bool fullscreen { get; private set; }
    public bool can_set_fullscreen { get; private set; }
    public bool can_raise { get; private set; }
    public bool has_track_list { get; private set; }
    public string identity { owned get; private set; }
    public string entry { owned get; private set; }
    public string[] supported_uri_schemas { owned get; private set; }
    public string[] supported_mime_types { owned get; private set; }

    public void toggle_fullscreen() {
        if (!can_set_fullscreen)
            critical("can not set fullscreen on " + bus_name);

        proxy.fullscreen = !fullscreen;
    }

    // player
    public void next() {
        try { proxy.next(); } catch (Error error) { critical(error.message); }
    }

    public void previous() {
        try { proxy.previous(); } catch (Error error) { critical(error.message); }
    }

    public void pause() {
        try { proxy.pause(); } catch (Error error) { critical(error.message); }
    }

    public void play_pause() {
        try { proxy.play_pause(); } catch (Error error) { critical(error.message); }
    }

    public void stop() {
        try { proxy.stop(); } catch (Error error) { critical(error.message); }
    }

    public void play() {
        try { proxy.play(); } catch (Error error) { critical(error.message); }
    }

    public void open_uri(string uri) {
        try { proxy.open_uri(uri); } catch (Error error) { critical(error.message); }
    }

    public void loop() {
        switch (loop_status) {
            case Loop.NONE:
                loop_status = Loop.TRACK;
                break;
            case Loop.TRACK:
                loop_status = Loop.PLAYLIST;
                break;
            case Loop.PLAYLIST:
                loop_status = Loop.NONE;
                break;
            default:
                break;
        }
    }

    public void shuffle() {
        shuffle_status = shuffle_status == Shuffle.ON
            ? Shuffle.OFF
            : Shuffle.ON;
    }

    public signal void seeked (int64 position);

    public double _get_position() {
        try {
            var reply = proxy.call_sync(
                "org.freedesktop.DBus.Properties.Get",
                new Variant("(ss)",
                    "org.mpris.MediaPlayer2.Player",
                    "Position"
                ),
                DBusCallFlags.NONE,
                -1,
                null
            );

            var body = reply.get_child_value(0);
            if (body.classify() == Variant.Class.STRING) {
                return -1; // Position not supported
            }

            return (double)body.get_variant().get_int64() / 1000000;
        } catch (Error err) {
            return -1;
        }
    }

    private void _set_position(double pos) {
        try {
            proxy.set_position((ObjectPath)trackid, (int64)(pos * 1000000));
        } catch (Error error) {
            critical(error.message);
        }
    }

    private Loop _loop_status = Loop.UNSUPPORTED;
    private double _rate;
    private Shuffle _shuffle_status = Shuffle.UNSUPPORTED;
    private double _volume = -1;

    public Loop loop_status {
        get { return _loop_status; }
        set { proxy.loop_status = value.to_string(); }
    }

    public double rate {
        get { return _rate; }
        set { proxy.rate = value; }
    }

    public Shuffle shuffle_status {
        get { return _shuffle_status; }
        set { proxy.shuffle = value == Shuffle.ON; }
    }

    public double volume {
        get { return _volume; }
        set { proxy.volume = value; }
    }

    public double position {
        get { return _get_position(); }
        set { _set_position(value); }
    }

    public PlaybackStatus playback_status { get; private set; }
    public double minimum_rate { get; private set; }
    public double maximum_rate { get; private set; }
    public bool can_go_next { get; private set; }
    public bool can_go_previous { get; private set; }
    public bool can_play { get; private set; }
    public bool can_pause { get; private set; }
    public bool can_seek { get; private set; }
    public bool can_control { get; private set; }

    // metadata
    [CCode (notify = false)]
    public HashTable<string,Variant> metadata { owned get; private set; }

    public string trackid { owned get; private set; }
    public double length { get; private set; }
    public string art_url { owned get; private set; }

    public string album { owned get; private set; }
    public string album_artist { owned get; private set; }
    public string artist { owned get; private set; }
    public string lyrics { owned get; private set; }
    public string title { owned get; private set; }
    public string composer { owned get; private set; }
    public string comments { owned get; private set; }

    // cached cover art
    public string cover_art { owned get; private set; }

    public Player(string name) {
        Object(bus_name: name.has_prefix("org.mpris.MediaPlayer2.")
            ? name : "org.mpris.MediaPlayer2." + name);
    }

    private void sync() {
        // mpris
        can_quit = proxy.can_quit;
        fullscreen = proxy.fullscreen;
        can_set_fullscreen = proxy.can_set_fullscreen;
        can_raise = proxy.can_raise;
        has_track_list = proxy.has_track_list;
        identity = proxy.identity;
        entry = proxy.desktop_entry;
        supported_uri_schemas = proxy.supported_uri_schemas;
        supported_mime_types = proxy.supported_mime_types;

        if (position >= 0)
            notify_property("position");

        // LoopStatus and Shuffle are optional props
        var props = proxy.get_all("org.mpris.MediaPlayer2.Player");

        // player
        if (props != null && props.get("LoopStatus") != null) {
            if (loop_status != Loop.from_string(proxy.loop_status)) {
                _loop_status = Loop.from_string(proxy.loop_status);
                notify_property("loop-status");
            }
        }

        if (rate != proxy.rate) {
            _rate = proxy.rate;
            notify_property("rate");
        }

        if (props != null && props.get("Shuffle") != null) {
            if (shuffle_status != Shuffle.from_bool(proxy.shuffle)) {
                _shuffle_status = Shuffle.from_bool(proxy.shuffle);
                notify_property("shuffle-status");
            }
        }

        if (volume != proxy.volume) {
            _volume = proxy.volume;
            notify_property("volume");
        }

        playback_status = PlaybackStatus.from_string(proxy.playback_status);
        minimum_rate = proxy.minimum_rate;
        maximum_rate = proxy.maximum_rate;
        can_go_next = proxy.can_go_next;
        can_go_previous = proxy.can_go_previous;
        can_play = proxy.can_play;
        can_pause = proxy.can_pause;
        can_seek = proxy.can_seek;
        can_control = proxy.can_control;

        // metadata
        metadata = proxy.metadata;
        if (metadata != null) {
            if (metadata.get("mpris:length") != null)
                length = (double)metadata.get("mpris:length").get_uint64() / 1000000;
            else
                length = -1;

            trackid = get_str("mpris:trackid");
            art_url = get_str("mpris:artUrl");
            album = get_str("xesam:album");
            lyrics = get_str("xesam:asText");
            title = get_str("xesam:title");
            album_artist = join_strv("xesam:albumArtist", ", ");
            artist = join_strv("xesam:artist", ", ");
            comments = join_strv("xesam:comments", "\n");
            composer = join_strv("xesam:composer", ", ");
            cache_cover.begin((_, res) => cache_cover.end(res));
            notify_property("metadata");
        }
    }

    private async void cache_cover() {
        if (art_url == null || art_url == "")
            return;

        var file = File.new_for_uri(art_url);
        if (file.get_path() != null) {
            cover_art = file.get_path();
            return;
        }

        var path = COVER_CACHE + "/" + Checksum.compute_for_string(ChecksumType.SHA1, art_url, -1);
        if (FileUtils.test(path, FileTest.EXISTS)) {
            cover_art = path;
            return;
        }

        try {
            if (!FileUtils.test(COVER_CACHE, FileTest.IS_DIR))
                File.new_for_path(COVER_CACHE).make_directory_with_parents(null);

            file.copy_async.begin(
                File.new_for_path(path),
                FileCopyFlags.OVERWRITE,
                Priority.DEFAULT,
                null,
                null,
                (_, res) => {
                    try {
                        file.copy_async.end(res);
                        cover_art = path;
                    } catch (Error err) {
                        critical("Failed to cache cover art with url \"%s\": %s", art_url, err.message);
                    }
                }
            );
        } catch (Error err) {
            critical(err.message);
        }
    }

    public Variant? get_meta(string key) {
        return metadata.lookup(key);
    }

    private string get_str(string key) {
        if (metadata.get(key) == null)
            return "";

        var str = metadata.get(key).get_string(null);
        return str == null ? "" : str;
    }

    private string? join_strv(string key, string sep) {
        if (metadata.get(key) == null)
            return null;

        var arr = metadata.get(key).get_strv();
        if (arr.length == 0)
            return null;

        var builder = new StringBuilder();
        for (var i = 0; i < arr.length; ++i) {
            builder.append(arr[i]);
            if (i + 1 < arr.length)
                builder.append(sep);
        }

        return builder.str;
    }

    construct {
        try {
            try_proxy();
            sync();
        } catch (Error error) {
            critical(error.message);
        }
    }

    public void try_proxy() throws Error {
        if (proxy != null)
            return;

        proxy = Bus.get_proxy_sync(
            BusType.SESSION,
            bus_name,
            "/org/mpris/MediaPlayer2"
        );

        if (proxy.g_name_owner != null)
            appeared();

        proxy.notify["g-name-owner"].connect(() => {
            if (proxy.g_name_owner != null)
                appeared();
            else
                closed();
        });

        proxy.g_properties_changed.connect(sync);

        pollid = Timeout.add_seconds(1, () => {
            if (!available)
                return Source.CONTINUE;

            if (position >= 0) {
                notify_property("position");
            }
            return Source.CONTINUE;
        }, Priority.DEFAULT);
    }

    ~Player() {
        Source.remove(pollid);
    }
}

public enum PlaybackStatus {
    PLAYING,
    PAUSED,
    STOPPED;

    public static PlaybackStatus from_string(string? str) {
        switch (str) {
            case "Playing":
                return PLAYING;
            case "Paused":
                return PAUSED;
            case "Stopped":
            default:
                return STOPPED;
        }
    }

    public string to_string() {
        switch (this) {
            case PLAYING:
                return "Playing";
            case PAUSED:
                return "Paused";
            case STOPPED:
            default:
                return "Stopped";
        }
    }
}

public enum Loop {
    UNSUPPORTED,
    NONE,
    TRACK,
    PLAYLIST;

    public static Loop from_string(string? str) {
        switch (str) {
            case "None":
                return NONE;
            case "Track":
                return TRACK;
            case "Playlist":
                return PLAYLIST;
            default:
                return UNSUPPORTED;
        }
    }

    public string? to_string() {
        switch (this) {
            case NONE:
                return "None";
            case TRACK:
                return "Track";
            case PLAYLIST:
                return "Playlist";
            default:
                return "Unsupported";
        }
    }
}

public enum Shuffle {
    UNSUPPORTED,
    ON,
    OFF;

    public static Shuffle from_bool(bool b) {
        return b ? Shuffle.ON : Shuffle.OFF;
    }

    public string? to_string() {
        switch (this) {
            case OFF:
                return "Off";
            case ON:
                return "On";
            default:
                return "Unsupported";
        }
    }
}
}