1# Copyright 2016 Ryan Dellenbaugh
2#
3# This program is free software; you can redistribute it and/or modify
4# it under the terms of the GNU General Public License as published by
5# the Free Software Foundation; either version 2 of the License, or
6# (at your option) any later version.
7
8import os.path
9
10from quodlibet import _
11from quodlibet.plugins.query import QueryPlugin, QueryPluginError
12from quodlibet.query import Query
13from quodlibet.query._match import error as QueryError
14from quodlibet import get_user_dir
15
16
17class IncludeSavedSearchQuery(QueryPlugin):
18    PLUGIN_ID = "include_saved"
19    PLUGIN_NAME = _("Include Saved Search")
20    PLUGIN_DESC = _("Include the results of a saved search as part of another "
21                  "query. Syntax is '@(saved: search name)'.")
22    key = 'saved'
23
24    def search(self, data, body):
25        return body.search(data)
26
27    def parse_body(self, body, query_path_=None):
28        if body is None:
29            raise QueryPluginError
30        body = body.strip().lower()
31        # Use provided query file for testing
32        if query_path_:
33            query_path = query_path_
34        else:
35            query_path = os.path.join(get_user_dir(), 'lists', 'queries.saved')
36        try:
37            with open(query_path, 'r', encoding="utf-8") as query_file:
38                for query_string in query_file:
39                    name = next(query_file).strip().lower()
40                    if name == body:
41                        try:
42                            return Query(query_string.strip())
43                        except QueryError:
44                            raise QueryPluginError
45            # We've searched the whole file and haven't found a match
46            raise QueryPluginError
47        except IOError:
48            raise QueryPluginError
49        except StopIteration:
50            # The file has an odd number of lines. This shouldn't happen unless
51            # it has been externally modified
52            raise QueryPluginError
53