# Path: via/services/pdf_url.py
# class PDFURLBuilder:
#     request: Request
#     google_drive_api: GoogleDriveAPI
#     jstor_api: JSTORAPI
#     secure_link_service: SecureLinkService
#     route_url: Callable
#     nginx_signer: _NGINXSigner
# 
#     _MS_ONEDRIVE_URL = (
#         re.compile(r"^https://.*\.sharepoint.com/.*download=1"),
#         re.compile(r"^https://api.onedrive.com/v1.0/.*/root/content"),
#     )
# 
#     def get_pdf_url(self, url):
#         """Build a signed URL to the corresponding Via route for proxing the PDF at `url`.
# 
#         By default PDFs will be proxied by Nginx but we'll dispatch based on the URL
#         to other routes responsible of proxing PDFs from Google Drive or MS OneDrive.
#         """
#         if file_details := self.google_drive_api.parse_file_url(url):
#             return self._google_file_url(file_details, url)
# 
#         if self._is_onedrive_url(url):
#             return self._proxy_onedrive_pdf(url)
# 
#         if url.startswith("jstor://"):
#             return self._proxy_jstor_pdf(url)
# 
#         return self.nginx_signer.sign_url(url, nginx_path="/proxy/static/")
# 
#     @classmethod
#     def _is_onedrive_url(cls, url):
#         return any(regexp.match(url) for regexp in cls._MS_ONEDRIVE_URL)
# 
#     def _proxy_onedrive_pdf(self, url):
#         url = self.secure_link_service.sign_url(
#             self.route_url(
#                 "proxy_onedrive_pdf",
#                 _query={"url": url},
#             )
#         )
#         return url
# 
#     def _proxy_jstor_pdf(self, url):
#         return self.secure_link_service.sign_url(
#             self.route_url(
#                 "proxy_jstor_pdf",
#                 _query={"url": url, "jstor.ip": self.request.params.get("jstor.ip")},
#             )
#         )
# 
#     def _google_file_url(self, file_details, url):
#         route = "proxy_google_drive_file"
#         if file_details.get("resource_key"):
#             route += ":resource_key"
# 
#         return self.secure_link_service.sign_url(
#             self.route_url(
#                 route,
#                 # Pass the original URL along so it will show up nicely in
#                 # error messages. This isn't useful for users as they don't
#                 # see this directly, but it's handy for us.
#                 _query={"url": url},
#                 **file_details,
#             )
#         )
# 
# class _NGINXSigner:
#     nginx_server: str
#     secret: str
# 
#     def sign_url(self, url, nginx_path):
#         """Return the URL from which the PDF viewer should load the PDF."""
# 
#         # Compute the expiry time to put into the URL.
#         exp = int(quantized_expiry(max_age=timedelta(hours=25)).timestamp())
# 
#         # The expression to be hashed.
#         #
#         # This matches the hash expression that we tell the NGINX secure link
#         # module to use with the secure_link_md5 setting in our NGINX config file.
#         #
#         # http://nginx.org/en/docs/http/ngx_http_secure_link_module.html#secure_link_md5
#         hash_expression = f"{nginx_path}{exp}/{url} {self.secret}"
# 
#         # Compute the hash value to put into the URL.
#         #
#         # This implements the NGINX secure link module's hashing algorithm:
#         #
#         # http://nginx.org/en/docs/http/ngx_http_secure_link_module.html#secure_link_md5
#         hash_ = hashlib.md5()
#         hash_.update(hash_expression.encode("utf-8"))
#         sec = hash_.digest()
#         sec = b64encode(sec)
#         sec = sec.replace(b"+", b"-")
#         sec = sec.replace(b"/", b"_")
#         sec = sec.replace(b"=", b"")
#         sec = sec.decode()
# 
#         # Construct the URL, inserting sec and exp where our NGINX config file
#         # expects to find them.
#         return f"{self.nginx_server}{nginx_path}{sec}/{exp}/{url}"
# 
# def factory(_context, request):
#     return PDFURLBuilder(
#         request=request,
#         google_drive_api=request.find_service(GoogleDriveAPI),
#         jstor_api=request.find_service(JSTORAPI),
#         secure_link_service=request.find_service(SecureLinkService),
#         route_url=request.route_url,
#         nginx_signer=_NGINXSigner(
#             nginx_server=request.registry.settings["nginx_server"],
#             secret=request.registry.settings["nginx_secure_link_secret"],
#         ),
#     )


from datetime import datetime, timedelta, timezone
from unittest.mock import sentinel
from via.services.pdf_url import PDFURLBuilder, _NGINXSigner, factory
import pytest


class TestFactory:
    def test_it(
        self,
        pyramid_request,
        pyramid_settings,
        PDFURLBuilder,
        PatchedNGINXSigner,
        google_drive_api,
        secure_link_service,
        jstor_api,
    ):
        svc = factory(sentinel.context, pyramid_request)

        PatchedNGINXSigner.assert_called_once_with(
            nginx_server=pyramid_settings["nginx_server"],
            secret=pyramid_settings["nginx_secure_link_secret"],
        )
        PDFURLBuilder.assert_called_once_with(
            request=pyramid_request,
            google_drive_api=google_drive_api,
            jstor_api=jstor_api,
            secure_link_service=secure_link_service,
            route_url=pyramid_request.route_url,
            nginx_signer=PatchedNGINXSigner.return_value,
        )
        assert svc == PDFURLBuilder.return_value

    @pytest.fixture

# Path: via/services/pdf_url.py
# class PDFURLBuilder:
#     request: Request
#     google_drive_api: GoogleDriveAPI
#     jstor_api: JSTORAPI
#     secure_link_service: SecureLinkService
#     route_url: Callable
#     nginx_signer: _NGINXSigner
# 
#     _MS_ONEDRIVE_URL = (
#         re.compile(r"^https://.*\.sharepoint.com/.*download=1"),
#         re.compile(r"^https://api.onedrive.com/v1.0/.*/root/content"),
#     )
# 
#     def get_pdf_url(self, url):
#         """Build a signed URL to the corresponding Via route for proxing the PDF at `url`.
# 
#         By default PDFs will be proxied by Nginx but we'll dispatch based on the URL
#         to other routes responsible of proxing PDFs from Google Drive or MS OneDrive.
#         """
#         if file_details := self.google_drive_api.parse_file_url(url):
#             return self._google_file_url(file_details, url)
# 
#         if self._is_onedrive_url(url):
#             return self._proxy_onedrive_pdf(url)
# 
#         if url.startswith("jstor://"):
#             return self._proxy_jstor_pdf(url)
# 
#         return self.nginx_signer.sign_url(url, nginx_path="/proxy/static/")
# 
#     @classmethod
#     def _is_onedrive_url(cls, url):
#         return any(regexp.match(url) for regexp in cls._MS_ONEDRIVE_URL)
# 
#     def _proxy_onedrive_pdf(self, url):
#         url = self.secure_link_service.sign_url(
#             self.route_url(
#                 "proxy_onedrive_pdf",
#                 _query={"url": url},
#             )
#         )
#         return url
# 
#     def _proxy_jstor_pdf(self, url):
#         return self.secure_link_service.sign_url(
#             self.route_url(
#                 "proxy_jstor_pdf",
#                 _query={"url": url, "jstor.ip": self.request.params.get("jstor.ip")},
#             )
#         )
# 
#     def _google_file_url(self, file_details, url):
#         route = "proxy_google_drive_file"
#         if file_details.get("resource_key"):
#             route += ":resource_key"
# 
#         return self.secure_link_service.sign_url(
#             self.route_url(
#                 route,
#                 # Pass the original URL along so it will show up nicely in
#                 # error messages. This isn't useful for users as they don't
#                 # see this directly, but it's handy for us.
#                 _query={"url": url},
#                 **file_details,
#             )
#         )
# 
# class _NGINXSigner:
#     nginx_server: str
#     secret: str
# 
#     def sign_url(self, url, nginx_path):
#         """Return the URL from which the PDF viewer should load the PDF."""
# 
#         # Compute the expiry time to put into the URL.
#         exp = int(quantized_expiry(max_age=timedelta(hours=25)).timestamp())
# 
#         # The expression to be hashed.
#         #
#         # This matches the hash expression that we tell the NGINX secure link
#         # module to use with the secure_link_md5 setting in our NGINX config file.
#         #
#         # http://nginx.org/en/docs/http/ngx_http_secure_link_module.html#secure_link_md5
#         hash_expression = f"{nginx_path}{exp}/{url} {self.secret}"
# 
#         # Compute the hash value to put into the URL.
#         #
#         # This implements the NGINX secure link module's hashing algorithm:
#         #
#         # http://nginx.org/en/docs/http/ngx_http_secure_link_module.html#secure_link_md5
#         hash_ = hashlib.md5()
#         hash_.update(hash_expression.encode("utf-8"))
#         sec = hash_.digest()
#         sec = b64encode(sec)
#         sec = sec.replace(b"+", b"-")
#         sec = sec.replace(b"/", b"_")
#         sec = sec.replace(b"=", b"")
#         sec = sec.decode()
# 
#         # Construct the URL, inserting sec and exp where our NGINX config file
#         # expects to find them.
#         return f"{self.nginx_server}{nginx_path}{sec}/{exp}/{url}"
# 
# def factory(_context, request):
#     return PDFURLBuilder(
#         request=request,
#         google_drive_api=request.find_service(GoogleDriveAPI),
#         jstor_api=request.find_service(JSTORAPI),
#         secure_link_service=request.find_service(SecureLinkService),
#         route_url=request.route_url,
#         nginx_signer=_NGINXSigner(
#             nginx_server=request.registry.settings["nginx_server"],
#             secret=request.registry.settings["nginx_secure_link_secret"],
#         ),
#     )


# Path: tests/unit/via/services/pdf_url_test.py
from datetime import datetime, timedelta, timezone
from unittest.mock import sentinel
from via.services.pdf_url import PDFURLBuilder, _NGINXSigner, factory
import pytest



class TestFactory:
    def test_it(
        self,
        pyramid_request,
        pyramid_settings,
        PDFURLBuilder,
        PatchedNGINXSigner,
        google_drive_api,
        secure_link_service,
        jstor_api,
    ):
        svc = factory(sentinel.context, pyramid_request)

        PatchedNGINXSigner.assert_called_once_with(
            nginx_server=pyramid_settings["nginx_server"],
            secret=pyramid_settings["nginx_secure_link_secret"],
        )
        PDFURLBuilder.assert_called_once_with(
            request=pyramid_request,
            google_drive_api=google_drive_api,
            jstor_api=jstor_api,
            secure_link_service=secure_link_service,
            route_url=pyramid_request.route_url,
            nginx_signer=PatchedNGINXSigner.return_value,
        )
        assert svc == PDFURLBuilder.return_value

    @pytest.fixture

    def PDFURLBuilder(self, patch):