# -*- coding: utf-8 -*-
# (c) 2019 The PatZilla Developers
import logging
import requests

from beaker.cache import cache_region
from patzilla.util.numbers.normalize import normalize_patent
from patzilla.util.network.browser import regular_user_agent
from pyramid.httpexceptions import HTTPNotFound

logger = logging.getLogger(__name__)


@cache_region('static')
def fetch_pdf(document_number):
    """
    Retrieve PDF document from the European publication server.
    https://data.epo.org/publication-server/

    Blueprint address:
    https://data.epo.org/publication-server/pdf-document?cc=EP&pn=nnnnnn&ki=nn
    """

    logger.info('PDF {}: European publication server attempt'.format(document_number))

    patent = normalize_patent(document_number, as_dict=True, provider='espacenet')

    url_tpl = u'https://data.epo.org/publication-server/pdf-document?cc=EP&pn={number}&ki={kind}'

    url = url_tpl.format(**patent)

    logger.info('Accessing EPO publication server: {}'.format(url))
    response = requests.get(url, headers={'User-Agent': regular_user_agent})

    # Debugging
    #print 'response.content:\n', response.content

    if response.status_code == 200:
        payload = response.content
        return payload

    else:
        msg = 'No document found at EPO publication server for "{document_number}"'.format(**locals())
        logger.warn(msg)
        raise HTTPNotFound(msg)


if __name__ == '__main__':
    print fetch_pdf('EP666666A2')

@@ -1174,16 +1174,87 @@
 == 200:%0A
+%0A        if response.headers%5B'Content-Type'%5D == 'application/pdf':%0A    
         
@@ -1288,16 +1288,20 @@
         
+    
 return p
@@ -1308,16 +1308,623 @@
 ayload%0A%0A
+        # Sometimes, an appropriate HTML document is returned,%0A        # pointing to the corresponding WIPO document.%0A        #%0A        # Example: EP2706864A2%0A        # https://data.epo.org/publication-server/pdf-document?cc=EP&pn=2706864&ki=A2%0A        # http://www.wipo.int/patentscope/search/en/WO2012153305%0A        #%0A        # TODO: Unlock this again by leveraging the WIPO URL.%0A        else:%0A            msg = 'No PDF document returned from European ' %5C%0A                  'publication server for %22%7Bdocument_number%7D%22.'.format(**locals())%0A            logger.warn(msg)%0A            raise HTTPNotFound(msg)%0A%0A
     else
@@ -1962,18 +1962,23 @@
 und at E
-PO
+uropean
  publica
@@ -1974,32 +1974,51 @@
 ean publication 
+' %5C%0A              '
 server for %22%7Bdoc

Resolve issue when European publication server returns reference to WIPO as HTML response instead of PDF document