inveniostore.py 16.5 KB
Newer Older
1 2 3
""" invenio_tools.inveniostore

"""
4
import requests
5

6
from .exception import CdsException
7
from requests.adapters import HTTPAdapter
8

LE GAC Renaud's avatar
LE GAC Renaud committed
9 10 11 12 13 14
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")
15

16
MSG_HTTP_DECODE = "Fail to decode HTTP response"
17 18 19
MSG_HTTP_ERROR = "HTTP Error"
MSG_NO_IDS = "Invalid list of record identifiers"
MSG_WRONG_KEYWORD = "Invalid keyword argument"
20

21 22
# maximum number of identifiers to be collected at once.
# The value of 200 is the maximum value authorised using cds.cern.ch
23 24 25 26
N_IDS = 200


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

29 30 31
    The class provides methods to request:
        * a list of identifier satisfying search criteria.
        * a record identified by its id.
32 33

    """
34

LE GAC Renaud's avatar
LE GAC Renaud committed
35
    def __init__(self, host="cds.cern.ch"):
36
        """
37
        Args:
38 39
            host (str):
                possible values are ``cds.cern.ch`` or ``inspirehep.net``.
40 41 42 43 44

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

45
        # start a session, a persistent connection with the server
46 47 48 49 50
        # let the session handle the number of retry
        session = requests.Session()
        session.mount(f"http://{host}", HTTPAdapter(max_retries=3))

        self._session = session
51 52 53 54 55

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

56
    def interogate(self, url, timeout=10, **kwargs):
57
        """Interrogate the store using the *URL*.
58
        It is retry several time when the service is not available.
59

60
        Args:
61
            url (str):
62 63
                URL string, *e.g.*::

64 65
                    * ``https://cds.cern.ch/record/123456/of=recjson``
                    * ``https://cds.cern.ch/search?of=id&....
66

67 68 69
            timeout (float):
                timeout for the HTTP request

70 71 72
        Keyword Args:

            The keyword arguments are those of the invenio web interface.
73 74 75 76 77 78 79
            Details are in https://inspirehep.net/help/hacking/search-engine-api

            Examples how to use the invenio API:
            https://inspirehep.net/info/hep/api?ln=fr#json_fnames

            List of keyword in the JSON record:
            https://github.com/inspirehep/invenio/blob/prod/modules/bibfield/etc/atlantis.cfg
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

            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**.

            ec (str):
                external collection list (*e.g.* ["CiteSeer", "Google"]).
                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").
                If greater than "recid", then display records from recid to
                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
                on creation/modification date (see "dt" argument below).
                Note that "d1" takes precedence over d1y, d1m, d1d if these
                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
                on creation/modification date (see "dt" argument below).
                Note that "d2" takes precedence over d2y, d2m, d2d
                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.
289

290 291 292
            timeout (float):
                timeout for the HTTP request

293
        Returns:
294
            requests.Response:
295

296
        Raises:
297 298
            RequestException:
                something went wrong within the HTTP dialog
299 300 301 302

        """
        self._url = url

303 304 305 306 307 308
        # FIXME March 30, 2020:
        #   * new version of inspirehep.net
        #   * API not yet ready
        #   * recommend to use old.inspirehep.net
        url = url.replace("//inspirehep.net", "//old.inspirehep.net")

309
        r = self._session.get(url, timeout=timeout, params=kwargs)
310
        r.raise_for_status()
311

312
        return r
313 314

    def get_ids(self, **kwargs):
315
        """Return a list of *record id* matching search criteria.
316

317 318 319 320 321 322 323 324 325 326
        Search criteria are defined by the keywords arguments.

        The complete list of  keyword arguments can be found at
        https://inspirehep.net/help/hacking/search-engine-api

        Examples how to use the invenio API:
        https://inspirehep.net/info/hep/api?ln=fr#json_fnames

        List of keyword in the JSON record:
        https://github.com/inspirehep/invenio/blob/prod/modules/bibfield/etc/atlantis.cfg
327

328
        Keyword Args:
329 330
            cc (str):
                current collection (e.g. "ATLAS Papers").
331
                The collection the user started to search/browse from.
332

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

336 337
            f (str):
                field to search within (e.g. "author").
338

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

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

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

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

356 357
            p2 (str): s
                econd pattern to search for in the advanced search
358
                interface.  Much like **p**.
359

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

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

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

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

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

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

386
        Returns:
387 388 389
            list:
                * A list of numbers.
                * The list is empty when the request failed on the server.
390

391
        Raises:
LE GAC Renaud's avatar
LE GAC Renaud committed
392 393
            CdsException::

394 395 396 397
                * keyword argument is invalid;
                * the server return an HTTP error;
                * JSON object can't be decoded
                * not well formed list of ids.
398 399 400 401 402 403 404 405 406 407 408

        """
        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)
409
        # Therefore to get the complete list of ids we have to scan them
410 411
        # by block of 200. The later is the maximum value allowed by cds.
        # We use the parameter rg and jrec to steer the scan.
412
        # They have no effect on inspirehep.net.
413

LE GAC Renaud's avatar
LE GAC Renaud committed
414 415 416
        kwargs["of"] = "id"
        kwargs["rg"] = N_IDS
        kwargs["jrec"] = -N_IDS
417 418

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

421
            url = "https://%s/search" % self._host
422
            rep = self.interogate(url, timeout=30, **kwargs)
423

424 425 426 427 428
            try:
                li = rep.json()

                # check that the list of identifier is well form
                # [1291068, 1352722, 1376692] or [1493820] or []
429
                if len(list(filter(lambda x: not isinstance(x, int), li))) > 0:
430 431
                    raise CdsException(MSG_NO_IDS)

432 433
                ids.extend(li)

434 435 436
            # trigger when the JSON object cannot be decoded
            except ValueError as e:
                raise CdsException(e)
437 438 439 440 441 442

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

        return ids

443
    def get_record(self, rec_id):
444
        """Retrieve a record defined by its *record id*.
445

446
        Args:
447 448
            rec_id (int):
                record identifier in the store.
449

450
        Returns:
451
            dict:
LE GAC Renaud's avatar
LE GAC Renaud committed
452
                the record data (recjson).
453

454
        Raises:
LE GAC Renaud's avatar
LE GAC Renaud committed
455 456
            CdsException::

457 458
                * the server return an HTTP error.
                * no JSON object could be decoded.
459 460 461

        """
        self._try = 0
462

463
        url = "https://%s/record/%s" % (self._host, rec_id)
464
        rep = self.interogate(url, timeout=30, of="recjson")
465

466 467
        try:
            li = rep.json()
468

469
        except ValueError:
470
            raise CdsException(MSG_HTTP_DECODE)
471

472
        return li[0]
473

474
    def last_search_url(self):
475
        """
476
        Returns:
477
            str:
478
                the URL used in the last search.
479 480

        """
481
        return self._url