inveniostore.py 18.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 17 18
CDS = ("cds", "cds.cern.ch")
INS = ("inspirehep", "inspirehep.net")

19
MSG_HTTP_DECODE = "Fail to decode HTTP response"
20 21
MSG_HTTP_ERROR = "HTTP Error"
MSG_NO_IDS = "Invalid list of record identifiers"
22 23
MSG_NO_SHELF = "No shelf %s for store %s"
MSG_NOT_IMPLEMENTED = "Method '%' not implemented for store '%' and shelf '%'<"
24
MSG_WRONG_KEYWORD = "Invalid keyword argument"
25

26 27
# maximum number of identifiers to be collected at once.
# The value of 200 is the maximum value authorised using cds.cern.ch
28 29 30 31
N_IDS = 200


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

34 35 36
    The class provides methods to request:
        * a list of identifier satisfying search criteria.
        * a record identified by its id.
37

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
    Args:
        host (str):
            possible values are ``cds``, ``cds.cern.ch``,``inspirehep``
            or ``inspirehep.net``

        shelf (str):
            section of the store. It depends on the host.
            Possible values are ``None``, ``literature``, ``conferences``
            and ``institutions``

             +----------------+--------------+-----------------------------+
             | host           | shelf        | base API                    |
             +----------------+--------------+-----------------------------+
             | cds.cern.ch    | None         | https://cds.cern.ch/        |
             +----------------+--------------+-----------------------------+
             | inspirehep.net | None         | https://old.inspirehep.net/ |
             | inspirehep.net | literature   | https://old.inspirehep.net/ |
             | inspirehep.net | conferences  | https://inspirehep.net/     |
             | inspirehep.net | institutions | https://old.inspirehep.net/ |
             +----------------+--------------+-----------------------------+

59
    """
60

61
    def __init__(self, host="cds", shelf=None):
62

63
        self._shelf = shelf
64 65
        self._url = None

66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        # base url for the API
        if host in CDS and shelf is None:
            api_search = "https://cds.cern.ch/search"
            api_record = "https://cds.cern.ch/record"
            host = "cds.cern.ch"

        elif host in INS and shelf in (None, "literature", "institutions"):
            api_search = "https://old.inspirehep.net/search"
            api_record = "https://old.inspirehep.net/record"
            host = "old.inspirehep.net"

        elif host in INS and shelf in ("conferences",):
            api_search = None
            api_record = "https://inspirehep.net/api/conferences"
            host = "inspirehep.net"

        else:
            raise CdsException(MSG_NO_SHELF % (shelf, host))

85
        # start a session, a persistent connection with the server
86 87
        # let the session handle the number of retry
        session = requests.Session()
88
        session.mount(f"https://{host}", HTTPAdapter(max_retries=3))
89

90 91 92
        self._api_search = api_search
        self._api_record = api_record
        self._host = host
93
        self._session = session
94 95 96 97 98

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

99
    def interogate(self, url, timeout=10, **kwargs):
100
        """Interrogate the store using the *URL*.
101
        It is retry several time when the service is not available.
102

103
        Args:
104
            url (str):
105 106
                the URL string depends on the store and on the invenio
                version which is ruuning, *e.g.*::
107

108 109
                    * ``https://cds.cern.ch/record/123456/of=recjson``
                    * ``https://cds.cern.ch/search?of=id&....
110

111 112 113
            timeout (float):
                timeout for the HTTP request

114 115 116
        Keyword Args:

            The keyword arguments are those of the invenio web interface.
117 118
            Details are in https://inspirehep.net/help/hacking/search-engine-api

119
            Examples how to use the old invenio API:
120 121 122 123
            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
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

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

334 335 336
            timeout (float):
                timeout for the HTTP request

337
        Returns:
338
            requests.Response:
339

340
        Raises:
341 342
            RequestException:
                something went wrong within the HTTP dialog
343 344 345 346

        """
        self._url = url

347
        r = self._session.get(url, timeout=timeout, params=kwargs)
348
        r.raise_for_status()
349

350
        return r
351 352

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

355 356 357 358 359 360 361 362 363 364
        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
365

366
        Keyword Args:
367 368
            cc (str):
                current collection (e.g. "ATLAS Papers").
369
                The collection the user started to search/browse from.
370

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

374 375
            f (str):
                field to search within (e.g. "author").
376

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

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

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

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

394 395
            p2 (str): s
                econd pattern to search for in the advanced search
396
                interface.  Much like **p**.
397

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

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

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

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

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

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

424
        Returns:
425 426 427
            list:
                * A list of numbers.
                * The list is empty when the request failed on the server.
428

429
        Raises:
LE GAC Renaud's avatar
LE GAC Renaud committed
430 431
            CdsException::

432 433 434 435
                * keyword argument is invalid;
                * the server return an HTTP error;
                * JSON object can't be decoded
                * not well formed list of ids.
436 437

        """
438 439 440 441 442
        host = self._host
        if host != "old.inspirehep.net":
            msg = MSG_NOT_IMPLEMENTED % ("get_ids", host, self._shelf)
            raise CdsException(msg)

443 444 445 446 447 448 449 450 451
        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)
452
        # Therefore to get the complete list of ids we have to scan them
453 454
        # by block of 200. The later is the maximum value allowed by cds.
        # We use the parameter rg and jrec to steer the scan.
455
        # They have no effect on inspirehep.net.
456

LE GAC Renaud's avatar
LE GAC Renaud committed
457 458 459
        kwargs["of"] = "id"
        kwargs["rg"] = N_IDS
        kwargs["jrec"] = -N_IDS
460 461

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

464
            rep = self.interogate(self._api_search, timeout=30, **kwargs)
465

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

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

474 475
                ids.extend(li)

476 477 478
            # trigger when the JSON object cannot be decoded
            except ValueError as e:
                raise CdsException(e)
479 480 481 482 483 484

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

        return ids

485
    def get_record(self, rec_id):
486
        """Retrieve a record defined by its *record id*.
487

488
        Args:
489 490
            rec_id (int):
                record identifier in the store.
491

492
        Returns:
493
            dict:
LE GAC Renaud's avatar
LE GAC Renaud committed
494
                the record data (recjson).
495

496
        Raises:
LE GAC Renaud's avatar
LE GAC Renaud committed
497 498
            CdsException::

499 500
                * the server return an HTTP error.
                * no JSON object could be decoded.
501 502

        """
503 504 505 506 507
        url = "%s/%s" % (self._api_record, rec_id)

        kwargs = {}
        if self._host in ("cds.cern.ch", "old.inspirehep.net"):
            kwargs = {"of": "recjson"}
508

509
        rep = self.interogate(url, timeout=30, **kwargs)
510

511 512
        try:
            li = rep.json()
513

514
        except ValueError:
515
            raise CdsException(MSG_HTTP_DECODE)
516

517
        return li[0]
518

519
    def last_search_url(self):
520
        """
521
        Returns:
522
            str:
523
                the URL used in the last search.
524 525

        """
526
        return self._url