inveniostore.py 15.6 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
from requests.adapters import HTTPAdapter
11 12


LE GAC Renaud's avatar
LE GAC Renaud committed
13 14 15 16 17 18
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")
19

20 21 22
MSG_HTTP_ERROR = "HTTP Error"
MSG_NO_IDS = "Invalid list of record identifiers"
MSG_WRONG_KEYWORD = "Invalid keyword argument"
23

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


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

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

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

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

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

        self._session = session
53 54 55 56 57

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

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

62
        Args:
63
            url (str):
64 65
                URL string, *e.g.*::

66 67
                    * ``https://cds.cern.ch/record/123456/of=recjson``
                    * ``https://cds.cern.ch/search?of=id&....
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

        Keyword Args:

            The keyword arguments are those of the invenio web interface.
            Details are in https://cds.cern.ch/help/hacking/search-engine-api.

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

283 284 285
            timeout (float):
                timeout for the HTTP request

286
        Returns:
287
            requests.Response:
288

289
        Raises:
290 291
            RequestException:
                something went wrong within the HTTP dialog
292 293 294 295

        """
        self._url = url

296 297
        r = self._session.get(url, timeout=timeout, params=params)
        r.raise_for_status()
298

299
        return r
300 301

    def get_ids(self, **kwargs):
302
        """Return a list of *record id* matching search criteria.
303 304 305

        Search criteria are defined by the keywords arguments:

306
        Keyword Args:
307 308
            cc (str):
                current collection (e.g. "ATLAS Papers").
309
                The collection the user started to search/browse from.
310

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

314 315
            f (str):
                field to search within (e.g. "author").
316

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

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

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

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

334 335
            p2 (str): s
                econd pattern to search for in the advanced search
336
                interface.  Much like **p**.
337

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

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

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

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

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

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

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

367
        Returns:
368 369 370
            list:
                * A list of numbers.
                * The list is empty when the request failed on the server.
371

372
        Raises:
LE GAC Renaud's avatar
LE GAC Renaud committed
373 374
            CdsException::

375 376 377 378
                * keyword argument is invalid;
                * the server return an HTTP error;
                * JSON object can't be decoded
                * not well formed list of ids.
379 380 381 382 383 384 385 386 387 388 389

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

LE GAC Renaud's avatar
LE GAC Renaud committed
395 396 397
        kwargs["of"] = "id"
        kwargs["rg"] = N_IDS
        kwargs["jrec"] = -N_IDS
398 399

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

402
            url = "https://%s/search" % self._host
403
            rep = self.interogate(url, **kwargs)
404

405 406 407 408 409
            try:
                li = rep.json()

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

413 414
                ids.extend(li)

415 416 417
            # trigger when the JSON object cannot be decoded
            except ValueError as e:
                raise CdsException(e)
418 419 420 421 422 423

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

        return ids

424
    def get_record(self, rec_id):
425
        """Retrieve a record defined by its *record id*.
426

427
        Args:
428 429
            rec_id (int):
                record identifier in the store.
430

431
        Returns:
432
            dict:
LE GAC Renaud's avatar
LE GAC Renaud committed
433
                the record data (recjson).
434

435
        Raises:
LE GAC Renaud's avatar
LE GAC Renaud committed
436 437
            CdsException::

438 439
                * the server return an HTTP error.
                * no JSON object could be decoded.
440 441 442

        """
        self._try = 0
443

444
        url = "https://%s/record/%s" % (self._host, rec_id)
445
        rep = self.interogate(url, of="recjson")
446

447 448
        try:
            li = rep.json()
449

450 451
        except ValueError as e:
            raise CdsException(e)
452

453
        return li[0]
454

455
    def last_search_url(self):
456
        """
457
        Returns:
458
            str:
459
                the URL used in the last search.
460 461

        """
462
        return self._url