def parse_service_url(url: str) -> typing.Optional[ServiceItem]: try: google_docs_id = typing.cast( SourceAddress, GoogleDocsSource.parse_address(url, strict=True) ).docs_id return ServiceItem(ServiceId.google_docs, google_docs_id) except ValidationError: pass return None
def test_googledocssource_parse_address(): for url in [ "gdoc://1BW6MubIyDirCGW9Wq-tSqCma8pioxBI6VpeLyXn5mZA", "docs.google.com/document/d/1BW6MubIyDirCGW9Wq-tSqCma8pioxBI6VpeLyXn5mZA", "https://docs.google.com/document/d/1BW6MubIyDirCGW9Wq-tSqCma8pioxBI6VpeLyXn5mZA/", "https://docs.google.com/document/d/1BW6MubIyDirCGW9Wq-tSqCma8pioxBI6VpeLyXn5mZA/edit", ]: sa = GoogleDocsSource.parse_address(url) assert sa.type == GoogleDocsSource assert sa.doc_id == "1BW6MubIyDirCGW9Wq-tSqCma8pioxBI6VpeLyXn5mZA" # Use of naked ids assert ( GoogleDocsSource.parse_address("1BW6MubIyDirCGW9Wq-tSqCma8pioxBI6VpeLyXn5mZA") is None ) assert ( GoogleDocsSource.parse_address( "1BW6MubIyDirCGW9Wq-tSqCma8pioxBI6VpeLyXn5mZA", naked=True ).doc_id == "1BW6MubIyDirCGW9Wq-tSqCma8pioxBI6VpeLyXn5mZA" ) # Use of strict assert GoogleDocsSource.parse_address("foo") is None with pytest.raises(ValidationError, match="Invalid Google Doc identifier"): GoogleDocsSource.parse_address("foo", strict=True)
def link_google_doc(self, user: User, request_body: dict, directory: str) -> None: token = user_social_token(user, "google") if token is None: raise LinkException( "Can't link as no Google account is connected to Stencila Hub." ) doc_id = request_body["document_id"] if not doc_id: raise LinkException("A document ID or URL was not provided.") doc_id = GoogleDocsSource.parse_address(doc_id, naked=True, strict=True).doc_id gdf = GoogleDocsFacade(token) try: document = gdf.get_document(doc_id) except HttpAccessTokenRefreshError: raise LinkException( "Could not refresh your Google authentication token. Please contact support for more information." ) except HttpError: raise LinkException( "Could not retrieve the document, please check the ID/URL." ) title = document["title"] source = GoogleDocsSource( doc_id=doc_id, project=self.project, path=utf8_path_join(directory, title.replace("/", "-")), ) source.save() messages.success( self.request, "Google Doc <em>{}</em> was linked.".format(escape(title)), extra_tags="safe", )