inveniostore.py 16.2 KB
Newer Older
1 2 3 4 5
""" invenio_tools.inveniostore

"""
import json
import re
6
import requests
7 8
import time

9
from .exception import CdsException
10 11
from requests.adapters import HTTPAdapter
from requests.exceptions import ConnectionError, HTTPError
12 13


LE GAC Renaud's avatar
LE GAC Renaud committed
14 15 16 17 18 19
CDS_SEARCH_KEYS = ("req", "cc", "c", "ec", "p", "f", "rg", "sf", "so", "sp",
                   "rm", "of", "ot", "as", "p1", "f1", "m1", "op1", "p2", "f2",
                   "m2", "op2", "p3", "f3", "m3", "sc", "jrec", "recid",
                   "recidb", "sysno", "id", "idb", "sysnb", "action", "d1",
                   "d1y", "d1m", "d1d", "d2", "d2y", "d2m", "d2d", "dt",
                   "verbose", "ap", "ln", "ec")
20

21 22 23
MSG_HTTP_ERROR = "HTTP Error"
MSG_NO_IDS = "Invalid list of record identifiers"
MSG_WRONG_KEYWORD = "Invalid keyword argument"
24 25 26 27 28 29 30 31 32

# maximum number of ids to be collected at once.
# The value of 200 is the maximum value authorized using cds.cern.ch
N_IDS = 200

REG_IDS_OK = re.compile("^\[[\d, ]*\]$")


class InvenioStore(object):
33
    """Class to dialogue with `invenio <http://invenio-software.org/>`_ store.
34

35
    The basic ingredients of the dialogue are:
36

37 38 39
        * the *request* which is an URL.
        * the *response* which is an XML string compliant with the
          `MARC <http://www.loc.gov/marc/>`_ standard.
40 41

    """
LE GAC Renaud's avatar
LE GAC Renaud committed
42
    def __init__(self, host="cds.cern.ch"):
43
        """
44 45 46
        Args:
            host (str): possible values are ``cds.cern.ch``
                or ``inspirehep.net``.
47 48 49 50 51

        """
        self._host = host
        self._url = None

52
        # start a session, a persistent connection with the server
53 54 55 56 57
        # let the session handle the number of retry
        session = requests.Session()
        session.mount(f"http://{host}", HTTPAdapter(max_retries=3))

        self._session = session
58 59 60 61 62 63

    def __del__(self):
        # close the session
        self._session.close()

    def interogate(self, url, params=None):
64
        """Interrogate the store using the *URL*.
65

66
        Args:
67
            url (str): URL string
68
            params (dict): parameters to be send with the URL
69

70
        Returns:
71
            str: the HTTP response
72

73
        Raises:
74 75
            CdsException:
                when the server returns connection or HTTP error.
76 77 78 79

        """
        self._url = url

80 81
        try:
            r = self._session.get(url, params=params)
82

83 84
        except ConnectionError as ce:
            raise CdsException(str(ce))
85

86 87
        except HTTPError as he:
            raise CdsException(str(he))
88

89 90 91 92
        r.encoding = "utf-8"
        print()
        print(200, r.text)

93
        return r.text
94 95

    def get_ids(self, **kwargs):
96
        """Return a list of *record id* matching search criteria.
97 98 99

        Search criteria are defined by the keywords arguments:

100 101 102
        Keyword Args:
            cc (str): current collection (e.g. "ATLAS Papers").
                The collection the user started to search/browse from.
103

104
            p (str): pattern to search for (e.g. "ellis and muon or kaon").
105

106
            f (str): field to search within (e.g. "author").
107

108 109
            p1 (str): first pattern to search for in the advanced search
                interface.  Much like **p**.
110

111 112
            f1 (str): first field to search within in the advanced search
                interface.  Much like **f**.
113

114 115 116
            m1 (str): first matching type in the advanced search interface.
                ("a" all of the words, "o" any of the words, "e" exact
                phrase, "p" partial phrase, "r" regular expression).
117

118 119
            op1 (str): first operator, to join the first and the second unit
                in the advanced search interface.  ("a" add, "o" or, "n" not).
120

121 122
            p2 (str): second pattern to search for in the advanced search
                interface.  Much like **p**.
123

124 125
            f2 (str): second field to search within in the advanced search
                interface.  Much like **f**.
126

127 128 129
            m2 (str): second matching type in the advanced search interface.
                ("a" all of the words, "o" any of the words, "e" exact
                phrase, "p" partial phrase, "r" regular expression).
130

131 132
            op2 (str): second operator, to join the second and the third unit
                in the advanced search interface.  ("a" add, "o" or,"n" not).
133

134 135
            p3 (str): third pattern to search for in the advanced search
                interface.  Much like **p**.
136

137 138
            f3 (str): third field to search within in the advanced search
                interface.  Much like **f**.
139

140 141 142
            m3 (str): third matching type in the advanced search interface.
                ("a" all of the words, "o" any of the words, "e" exact
                phrase, "p" partial phrase, "r" regular expression).
143 144

        The complete list of  keyword arguments can be found at
145
        http://invenio-demo.cern.ch/help/hacking/search-engine-api.
146

147 148 149
        Returns:
            list: a list of numbers.
                The list is empty when the request failed on the server.
150

151 152 153
        Raises:
            CdsException: when a keyword argument is invalid or
                when the server return an invalid list of ids.
154 155 156 157 158 159 160 161 162 163 164 165 166 167

        """
        for k in kwargs:
            if k not in CDS_SEARCH_KEYS:
                raise CdsException(MSG_WRONG_KEYWORD, k)

        ids = []
        scan = True

        # NOTE: the number of ids which can be collected at once is limited
        # to 10 on cds.cern.ch since the invenio version 1.1.3.1106 (Jun 2014)
        # Therefore to recuperate the complete list of ids we have to get them
        # by block of 200. The later is the maximum value allowed by cds.
        # We use the parameter rg and jrec to steer the scan.
168
        # They have no effect on inspirehep.net.
169

LE GAC Renaud's avatar
LE GAC Renaud committed
170 171 172
        kwargs["of"] = "id"
        kwargs["rg"] = N_IDS
        kwargs["jrec"] = -N_IDS
173 174

        while scan:
LE GAC Renaud's avatar
LE GAC Renaud committed
175
            kwargs["jrec"] += N_IDS
176

177
            url = "http://%s/search" % self._host
178

179
            rep = self.interogate(url, params=kwargs)
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194

            # check that the list of ids is well form
            # [1291068, 1352722, 1376692, 1454870, 1492807] or [1493820] or []
            if REG_IDS_OK.match(rep):
                li = json.loads(rep)
                ids.extend(li)

            else:
                raise CdsException(MSG_NO_IDS)

            if len(li) != N_IDS:
                scan = False

        return ids

195
    def get_record(self, rec_id):
196
        """Retrieve a record defined by its *record id*.
197

198 199
        Args:
            rec_id (int): record identifier in the store.
200

201
        Returns:
202
            str: the XML string is compliant with
203 204
                the `MARC <http://www.loc.gov/marc/>`_ standard.
                Use Marc12.__call__ to decode it.
205

206 207
        Raises:
            CdsException: when the server return an HTTP error.
208 209 210

        """
        self._try = 0
LE GAC Renaud's avatar
LE GAC Renaud committed
211
        url = "http://%s/record/%s/export/xm" % (self._host, rec_id)
212 213 214
        return self.interogate(url)

    def last_search_url(self):
215 216
        """
        Returns:
217
            str: the URL used in the last search.
218 219 220 221 222 223 224

        """
        return self._url

    def search(self, **kwargs):
        """Return records matching the keyword arguments.

225 226 227 228 229 230 231 232 233 234
        Keyword Args:
            req (str): mod_python Request class instance.

            cc (str): current collection (*e.g.* "ATLAS").
                The collection the user started to search/browse from.

            c (str): collection list (*e.g.* ["Theses", "Books"]).
                The collections user may have selected/deselected when
                starting to search from **cc**.

LE GAC Renaud's avatar
LE GAC Renaud committed
235
            ec (str): external collection list (*e.g.* ["CiteSeer", "Google"]).
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
                The external collections may have been selected/deselected
                by the user.

            p (str): pattern to search for (*e.g.* "ellis and muon or kaon").

            f (str): field to search within (*e.g.* "author").

            rg (int): records in groups of (*e.g.* "10").
                Defines how many hits per collection in the search results
                page are displayed.

            sf (str): sort field (*e.g*. "title").

            so (str): sort order ("a"=ascending, "d"=descending).

            sp (str): sort pattern (*e.g.* "CERN-") -- in case there are more
                values in a sort field, this argument tells which one
                to prefer.

            rm (str): ranking method (*e.g.* "jif").
                Defines whether results should be ranked by some known
                ranking method.

            of (str): output format (*e.g.* "hb").
                Usually starting "h" means HTML output (and "hb" for HTML
                brief, "hd" for HTML detailed), "x" means XML output,
                "t" means plain text output, "id" means no output at all but to
                return list of recIDs found. (Suitable for high-level API.).

            ot (str): output only these MARC tags (*e.g.* "100,700,909C0b").
                Useful if only some fields are to be shown in the
                output, e.g. for library to control some fields.

            as (int): advanced search ("0" means no, "1" means yes).
                Whether search was called from within the advanced search
                interface.

            p1 (str): first pattern to search for in the advanced search
                interface.  Much like **p**.

            f1 (str): first field to search within in the advanced search
                interface.  Much like **f**.

            m1 (str): first matching type in the advanced search interface.
                ("a" all of the words, "o" any of the words, "e" exact phrase,
                "p" partial phrase, "r" regular expression).

            op1 (str): first operator, to join the first and the second unit
                in the advanced search interface.  ("a" add, "o" or, "n" not).

            p2 (str): second pattern to search for in the advanced search
                interface.  Much like **p**.

            f2 (str): second field to search within in the advanced search
                interface.  Much like **f**.

            m2 (str): second matching type in the advanced search interface.
                ("a" all of the words, "o" any of the words, "e" exact phrase,
                "p" partial phrase, "r" regular expression).

            op2 (str): second operator, to join the second and the third unit
                in the advanced search interface.  ("a" add, "o" or, "n" not).

            p3 (str): third pattern to search for in the advanced search
                interface.  Much like **p**.

            f3 (str): third field to search within in the advanced search
                interface.  Much like **f**.

            m3 (str): third matching type in the advanced search interface.
                ("a" all of the words, "o" any of the words, "e" exact phrase,
                "p" partial phrase, "r" regular expression).

            sc (int): split by collection ("0" no, "1" yes).
                Governs whether we want to present the results in a single
                huge list, or splitted by collection.

            jrec (int): jump to record (*e.g.* "234").
                Used for navigation inside the search results.

            recid (int): display record ID (*e.g.* "20000").
                Do not search/browse but go straight away to the Detailed
                record page for the given recID.

            recidb (int): display record ID bis (*e.g.* "20010").
LE GAC Renaud's avatar
LE GAC Renaud committed
321
                If greater than "recid", then display records from recid to
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
                recidb. Useful for example for dumping records from the
                database for reformatting.

            sysno (str): display old system SYS number (*e.g.* "").
                If you migrate to Invenio from another system, and store your
                old SYS call numbers, you can use them instead of recid if you
                wish so.

            id (int): the same as recid, in case recid is not set.
                For backwards compatibility.

            idb (int): the same as recid, in case recidb is not set.
                For backwards compatibility.

            sysnb (str): the same as sysno, in case sysno is not set.
                For backwards compatibility.

            action (str): action to do.  "SEARCH" for searching,
                "Browse" for browsing.  Default is to search.

            d1 (str): first datetime in full YYYY-mm-dd HH:MM:DD format
                (*e.g.* "1998-08-23 12:34:56"). Useful for search limits
LE GAC Renaud's avatar
LE GAC Renaud committed
344 345
                on creation/modification date (see "dt" argument below).
                Note that "d1" takes precedence over d1y, d1m, d1d if these
346 347 348 349 350 351 352 353 354 355 356 357 358
                are defined.

            d1y (int): first date's year (*e.g.* "1998").
                Useful for search limits on creation/modification date.

            d1m (int): first date's month (*e.g.* "08").
                Useful for search limits on creation/modification date.

            d1d (int): first date's day (*e.g.* "23").
                Useful for search limits on creation/modification date.

            d2 (str): second datetime in full YYYY-mm-dd HH:MM:DD format
                (*e.g.* "1998-09-02 12:34:56"). Useful for search limits
LE GAC Renaud's avatar
LE GAC Renaud committed
359 360
                on creation/modification date (see "dt" argument below).
                Note that "d2" takes precedence over d2y, d2m, d2d
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
                if these are defined.

            d2y (int): second date's year (*e.g.* "1998").
                Useful for search limits on creation/modification date.

            d2m (int): second date's month (*e.g.* "09").
                Useful for search limits on creation/modification date.

            d2d (int): second date's day (*e.g.* "02").
                Useful for search limits on creation/modification date.

            dt (str): first and second date's type (*e.g.* "c").
                Specifies whether to search in creation dates ("c") or in
                modification dates ("m").  When dt is not set and d1*
                and d2* are set, the default is "c".

            verbose (int): verbose level (0=min, 9=max).
                Useful to print some internal information on the searching
                process in case something goes wrong.

            ap (int): alternative patterns (0=no, 1=yes).
                In case no exact match is found, the search engine can try
                alternative patterns e.g. to replace non-alphanumeric
                characters by a boolean query.  ap defines if this is wanted.

            ln (str): language of the search interface (*e.g.* "en").
                Useful for internationalization.
388 389 390

        The keyword arguments are those of the invenio web interface.
        Details are in
391
        http://invenio-demo.cern.ch/help/hacking/search-engine-api.
392

393
        Returns:
394
            str: the format of the string (HTML, XML) depend on the
395
                keyword **of**. For MARC12 format use **xm**.
396

397 398
        Deprecated: the method get_ids coupled with get_record is
            much more efficient.
399 400 401 402 403 404

        """
        for k in kwargs:
            if k not in CDS_SEARCH_KEYS:
                raise CdsException(MSG_WRONG_KEYWORD, k)

LE GAC Renaud's avatar
LE GAC Renaud committed
405
        kwargs["action_search"] = "Search"
406

407
        url = "http://%s/search" % self._host
408

409
        return self.interogate(url, params=kwargs)
410

LE GAC Renaud's avatar
LE GAC Renaud committed
411
    def search_year(self, collection, year, of="xm", rg=10, so="d"):
412
        """Search records for given *collection* and for a given *year*.
413

414 415
        Args:
            collection (str):
416

417
            year (int):
418

419 420 421 422 423 424
            of (str): output format (e.g. "hb").
                Usually starting "h" means HTML output (and "hb" for HTML
                brief, "hd" for HTML detailed), "x" means XML output,
                "xm" means MARC XML format, "t" means plain text output,
                "id" means no output at all but to return list of recIDs found.
                (Suitable for high-level API.)
425

426
            rg (int): limit on the number of output records.
427

428
            so (str): sort order ("a"=ascending, "d"=descending).
429

430
        Returns:
431 432
            str:
                the format of the string HTML, XML depends on the
433
                keyword **of**. Use **xm** for MARC XML.
434 435 436

        """
        return self.search(c=collection,
LE GAC Renaud's avatar
LE GAC Renaud committed
437 438
                           f="year",
                           ln="en",
439 440 441
                           of=of,
                           p=year,
                           rg=rg,
LE GAC Renaud's avatar
LE GAC Renaud committed
442
                           sf="year",
443
                           so=so)