summaryrefslogtreecommitdiff
path: root/src/plugins/media-export/rygel-media-export-root-container.vala
blob: 04a286cba9078f4f858b0f97e3806ba35570ee74 (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
/*
 * Copyright (C) 2009,2010 Jens Georg <mail@jensge.org>.
 *
 * This file is part of Rygel.
 *
 * Rygel is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Rygel 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 Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser 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.
 */

using Gee;
using GUPnP;

internal struct Rygel.MediaExport.FolderDefinition {
    string title;
    string definition;
}

const Rygel.MediaExport.FolderDefinition[] virtual_folders_default = {
    { N_("Year"), "dc:date,?" },
    { N_("All"),  "" }
};

const Rygel.MediaExport.FolderDefinition[] virtual_folders_music = {
    { N_("Artist"), "upnp:artist,?,upnp:album,?" },
    { N_("Album"),  "upnp:album,?" },
    { N_("Genre"),  "dc:genre,?" }
};

/**
 * Represents the root container.
 */
public class Rygel.MediaExport.RootContainer : Rygel.MediaExport.DBContainer {
    private DBusService    service;
    private Harvester      harvester;
    private Cancellable    cancellable;
    private MediaContainer filesystem_container;
    private ulong          harvester_signal_id;

    private static MediaContainer instance = null;
    private static Error          creation_error = null;

    internal const string FILESYSTEM_FOLDER_NAME = N_("Files & Folders");
    internal const string FILESYSTEM_FOLDER_ID   = "Filesystem";

    private const string SEARCH_CONTAINER_PREFIX = QueryContainer.PREFIX +
                                                   "upnp:class," +
                                                   Rygel.MusicItem.UPNP_CLASS +
                                                   ",";

    public static MediaContainer get_instance () throws Error {
        if (RootContainer.instance == null) {
            try {
                RootContainer.instance = new RootContainer ();
            } catch (Error error) {
                // cache error for further calls and create Null container
                RootContainer.instance = new NullContainer ();
                RootContainer.creation_error = error;
            }
        } else {
            if (creation_error != null) {
                throw creation_error;
            }
        }

        return RootContainer.instance;
    }

    public MediaContainer get_filesystem_container () {
        return this.filesystem_container;
    }

    public void shutdown () {
        this.cancellable.cancel ();
    }

    // DBus utility methods

    public void add_uri (string uri) {
        var file = File.new_for_commandline_arg (uri);
        this.harvester.schedule (file,
                                 this.filesystem_container,
                                 "DBUS");
    }

    public void remove_uri (string uri) {
        var file = File.new_for_commandline_arg (uri);
        var id = MediaCache.get_id (file);

        this.harvester.cancel (file);
        try {
            this.media_db.remove_by_id (id);
        } catch (Error error) {
            warning (_("Failed to remove URI: %s"), error.message);
        }
    }

    public string[] get_dynamic_uris () {
        try {
            var uris = this.media_db.get_flagged_uris ("DBUS");

            return uris.to_array ();
        } catch (Error error) { }

        return new string[0];
    }

    // MediaContainer overrides

    public override async MediaObject? find_object (string       id,
                                                    Cancellable? cancellable)
                                                    throws Error {
        var object = yield base.find_object (id, cancellable);

        if (object == null && id.has_prefix (QueryContainer.PREFIX)) {
            var factory = QueryContainerFactory.get_default ();
            var container = factory.create_from_id (this.media_db, id);
            if (container != null) {
                container.parent = this;
            }

            return container;
        }

        return object;
    }

    public override async MediaObjects? search (SearchExpression? expression,
                                                uint              offset,
                                                uint              max_count,
                                                out uint          total_matches,
                                                string?           sort_criteria,
                                                Cancellable?      cancellable)
                                                throws GLib.Error {
         if (expression == null) {
            return yield base.search (expression,
                                      offset,
                                      max_count,
                                      out total_matches,
                                      sort_criteria,
                                      cancellable);
        }

        MediaObjects list;
        MediaContainer query_container = null;
        string upnp_class = null;

        if (expression is RelationalExpression) {
            var relational_expression = expression as RelationalExpression;

            query_container = search_to_virtual_container
                                        (relational_expression);
            upnp_class = relational_expression.operand2;
        } else if (is_search_in_virtual_container (expression,
                                                   out query_container)) {
            // do nothing. query_container is filled then
        }

        if (query_container != null) {
            var real_sort_criteria = sort_criteria ?? this.sort_criteria;
            list = yield query_container.get_children (offset,
                                                       max_count,
                                                       real_sort_criteria,
                                                       cancellable);
            total_matches = query_container.child_count;

            if (upnp_class != null) {
                foreach (var object in list) {
                    object.upnp_class = upnp_class;
                }
            }

            return list;
        } else {
            return yield base.search (expression,
                                      offset,
                                      max_count,
                                      out total_matches,
                                      sort_criteria,
                                      cancellable);
        }
    }



    private ArrayList<File> get_shared_uris () {
        ArrayList<string> uris;
        ArrayList<File> actual_uris;

        var config = MetaConfig.get_default ();

        try {
            uris = config.get_string_list ("MediaExport", "uris");
        } catch (Error error) {
            uris = new ArrayList<string> ();
        }

        try {
            uris.add_all (this.media_db.get_flagged_uris ("DBUS"));
        } catch (Error error) {}

        actual_uris = new ArrayList<File> ();

        var home_dir = File.new_for_path (Environment.get_home_dir ());
        unowned string pictures_dir = Environment.get_user_special_dir
                                        (UserDirectory.PICTURES);
        unowned string videos_dir = Environment.get_user_special_dir
                                        (UserDirectory.VIDEOS);
        unowned string music_dir = Environment.get_user_special_dir
                                        (UserDirectory.MUSIC);

        foreach (var uri in uris) {
            var file = File.new_for_commandline_arg (uri);
            if (likely (file != home_dir)) {
                var actual_uri = uri;

                if (likely (pictures_dir != null)) {
                    actual_uri = actual_uri.replace ("@PICTURES@", pictures_dir);
                }
                if (likely (videos_dir != null)) {
                    actual_uri = actual_uri.replace ("@VIDEOS@", videos_dir);
                }
                if (likely (music_dir != null)) {
                    actual_uri = actual_uri.replace ("@MUSIC@", music_dir);
                }

                // protect against special directories expanding to $HOME
                file = File.new_for_commandline_arg (actual_uri);
                if (file == home_dir) {
                    continue;
                }
            }

            actual_uris.add (file);
        }

        return actual_uris;
    }

    private QueryContainer? search_to_virtual_container (
                                       RelationalExpression expression) {
        if (expression.operand1 == "upnp:class" &&
            expression.op == SearchCriteriaOp.EQ) {
            string id = SEARCH_CONTAINER_PREFIX;
            switch (expression.operand2) {
                case "object.container.album.musicAlbum":
                    id += "upnp:album,?";

                    break;
                case "object.container.person.musicArtist":
                    id += "dc:creator,?,upnp:album,?";

                    break;
                case "object.container.genre.musicGenre":
                    id += "dc:genre,?";

                    break;
                default:
                    return null;
            }

            var factory = QueryContainerFactory.get_default ();

            return factory.create_from_description (this.media_db, id);
        }

        return null;
    }

    /**
     * Check if a passed search expression is a simple search in a virtual
     * container.
     *
     * @param expression the expression to check
     * @param new_id contains the id of the virtual container constructed from
     *               the search
     * @param upnp_class contains the class of the container the search was
     *                   looking in
     * @return true if it was a search in virtual container, false otherwise.
     * @note This works single level only. Enough to satisfy Xbox music
     *       browsing, but may need refinement
     */
    private bool is_search_in_virtual_container (SearchExpression   expression,
                                                 out MediaContainer container) {
        RelationalExpression virtual_expression = null;
        QueryContainer query_container;

        container = null;

        if (!(expression is LogicalExpression)) {
            return false;
        }

        var logical_expression = expression as LogicalExpression;

        if (!(logical_expression.operand1 is RelationalExpression &&
            logical_expression.operand2 is RelationalExpression &&
            logical_expression.op == LogicalOperator.AND)) {

            return false;
        }

        var left_expression = logical_expression.operand1 as RelationalExpression;
        var right_expression = logical_expression.operand2 as RelationalExpression;

        query_container = search_to_virtual_container (left_expression);
        if (query_container == null) {
            query_container = search_to_virtual_container (right_expression);
            if (query_container != null) {
                virtual_expression = left_expression;
            } else {
                return false;
            }
        } else {
            virtual_expression = right_expression;
        }

        var factory = QueryContainerFactory.get_default ();
        var plaintext_id = factory.get_virtual_container_definition
                                        (query_container.id);

        var last_argument = plaintext_id.replace (QueryContainer.PREFIX, "");

        var escaped_detail = Uri.escape_string (virtual_expression.operand2,
                                                "",
                                                true);
        var new_id = "%s%s,%s,%s".printf (QueryContainer.PREFIX,
                                          virtual_expression.operand1,
                                          escaped_detail,
                                          last_argument);

        container = factory.create_from_description (this.media_db,
                                                     new_id);

        return true;
    }


    /**
     * Create a new root container.
     */
    private RootContainer () throws Error {
        var db = MediaCache.get_default ();

        base (db, "0", _("@REALNAME@'s media"));

        this.cancellable = new Cancellable ();

        try {
            this.service = new DBusService (this);
        } catch (Error err) {
            warning (_("Failed to create MediaExport D-Bus service: %s"),
                     err.message);
        }

        try {
            this.media_db.save_container (this);
        } catch (Error error) { } // do nothing

        try {
            this.filesystem_container = new DBContainer
                                        (media_db,
                                         FILESYSTEM_FOLDER_ID,
                                         _(FILESYSTEM_FOLDER_NAME));
            this.filesystem_container.parent = this;
            this.media_db.save_container (this.filesystem_container);
        } catch (Error error) { }

        ArrayList<string> ids;
        try {
            ids = media_db.get_child_ids (FILESYSTEM_FOLDER_ID);
        } catch (DatabaseError e) {
            ids = new ArrayList<string> ();
        }

        this.harvester = new Harvester (this.cancellable,
                                        this.get_shared_uris ());
        this.harvester_signal_id = this.harvester.done.connect
                                        (on_initial_harvesting_done);

        foreach (var file in this.harvester.locations) {
            ids.remove (MediaCache.get_id (file));
            this.harvester.schedule (file,
                                     this.filesystem_container);
        }

        foreach (var id in ids) {
            debug ("ID %s no longer in config; deleting...", id);
            try {
                this.media_db.remove_by_id (id);
            } catch (DatabaseError error) {
                warning (_("Failed to remove entry: %s"), error.message);
            }
        }

        this.updated ();
    }

    private void on_initial_harvesting_done () {
        this.harvester.disconnect (this.harvester_signal_id);
        this.media_db.debug_statistics ();
        this.add_default_virtual_folders ();
        this.updated ();

        this.filesystem_container.container_updated.connect( () => {
            this.add_default_virtual_folders ();
            this.updated ();
        });
    }

    private void add_default_virtual_folders () {
        try {
            this.add_virtual_containers_for_class (_("Music"),
                                                   Rygel.MusicItem.UPNP_CLASS,
                                                   virtual_folders_music);
            this.add_virtual_containers_for_class (_("Pictures"),
                                                   PhotoItem.UPNP_CLASS);
            this.add_virtual_containers_for_class (_("Videos"),
                                                   VideoItem.UPNP_CLASS);
        } catch (Error error) {};
    }

    private void add_folder_definition (MediaContainer   container,
                                        string           item_class,
                                        FolderDefinition definition)
                                        throws Error {
        var id = "%supnp:class,%s,%s".printf (QueryContainer.PREFIX,
                                               item_class,
                                               definition.definition);
        if (id.has_suffix (",")) {
            id = id.slice (0,-1);
        }

        var factory = QueryContainerFactory.get_default ();
        var query_container = factory.create_from_description
                                        (this.media_db,
                                         id,
                                         _(definition.title));

        if (query_container.child_count > 0) {
            query_container.parent = container;
            this.media_db.save_container (query_container);
        } else {
            this.media_db.remove_by_id (id);
        }
    }

    private void add_virtual_containers_for_class
                                        (string              parent,
                                         string              item_class,
                                         FolderDefinition[]? definitions = null)
                                         throws Error {
        var container = new NullContainer ();
        container.parent = this;
        container.title = parent;
        container.id = "virtual-parent:" + item_class;
        this.media_db.save_container (container);

        foreach (var definition in virtual_folders_default) {
            this.add_folder_definition (container, item_class, definition);
        }

        if (definitions != null) {
            foreach (var definition in definitions) {
                this.add_folder_definition (container, item_class, definition);
            }
        }

        if (this.media_db.get_child_count (container.id) == 0) {
            this.media_db.remove_by_id (container.id);
        } else {
            container.updated ();
        }
    }
}