Skip to content

Wiki

v5.0.0 uses the object-oriented models

The legacy synapseclient.wiki.Wiki class is documented below for reference. New code should use the object-oriented Wiki model.

synapseclient.wiki

Wiki

A Wiki page requires a title, markdown and an owner object and can also include images.

Creating a Wiki

import synapseclient
from synapseclient import Wiki

## Initialize a Synapse object & authenticate
syn = synapseclient.Synapse()
syn.login()

entity = syn.get('syn123456')

content = """
# My Wiki Page

Here is a description of my **fantastic** project!

An attached image:
${image?fileName=logo.png&align=none}
"""

wiki = Wiki(title='My Wiki Page',
            owner=entity,
            markdown=content,
            attachments=['/path/to/logo.png'])

wiki = syn.store(wiki)

Embedding images

Note that in the above example, we've attached a logo graphic and embedded it in the web page.

Figures that are more than just decoration can be stored as Synapse entities allowing versioning and provenance information to be recorded. This is a better choice for figures with data behind them.

Updating a Wiki

import synapseclient

## Initialize a Synapse object & authenticate
syn = synapseclient.Synapse()
syn.login()

entity = syn.get('syn123456')
wiki = syn.getWiki(entity)

wiki.markdown = """
# My Wiki Page

Here is a description of my **fantastic** project! Let's
*emphasize* the important stuff.

An embedded image that is also a Synapse entity:
${image?synapseId=syn1824434&align=None&scale=66}

Now we can track it's provenance and keep multiple versions.
"""

wiki = syn.store(wiki)

Classes

Wiki

Bases: DictObject

Represents a wiki page in Synapse with content specified in markdown.

WARNING - This class is deprecated and will no longer be maintained. Please use the WikiPage model from synapseclient.models.wiki instead.

PARAMETER DESCRIPTION
title

Title of the Wiki

owner

Parent Entity that the Wiki will belong to

markdown

Content of the Wiki (cannot be defined if markdownFile is defined)

markdownFile

Path to file which contains the Content of Wiki (cannot be defined if markdown is defined)

attachments

List of paths to files to attach

fileHandles

List of file handle IDs representing files to be attached

parentWikiId

(optional) For sub-pages, specify parent wiki page

Migration to the object-oriented model

 

# Old approach (DEPRECATED)
# from synapseclient import Wiki
# wiki = Wiki(owner=project, title="Home", markdown="# Welcome")
# wiki = syn.store(wiki)

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import WikiPage

syn = Synapse()
syn.login()

wiki_page = WikiPage(
    owner_id="syn123",
    title="Home",
    markdown="# Welcome",
).store()
Source code in synapseclient/wiki.py
 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
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use the WikiPage model from synapseclient.models.wiki instead.",
)
class Wiki(DictObject):
    """
    Represents a wiki page in Synapse with content specified in markdown.

    WARNING - This class is deprecated and will no longer be maintained. Please use the WikiPage model from synapseclient.models.wiki instead.

    Arguments:
        title: Title of the Wiki
        owner: Parent Entity that the Wiki will belong to
        markdown: Content of the Wiki (cannot be defined if markdownFile is defined)
        markdownFile: Path to file which contains the Content of Wiki (cannot be defined if markdown is defined)
        attachments: List of paths to files to attach
        fileHandles: List of file handle IDs representing files to be attached
        parentWikiId: (optional) For sub-pages, specify parent wiki page

    Example: Migration to the object-oriented model
         

        ```python
        # Old approach (DEPRECATED)
        # from synapseclient import Wiki
        # wiki = Wiki(owner=project, title="Home", markdown="# Welcome")
        # wiki = syn.store(wiki)

        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import WikiPage

        syn = Synapse()
        syn.login()

        wiki_page = WikiPage(
            owner_id="syn123",
            title="Home",
            markdown="# Welcome",
        ).store()
        ```
    """

    __PROPERTIES = (
        "title",
        "markdown",
        "attachmentFileHandleIds",
        "id",
        "etag",
        "createdBy",
        "createdOn",
        "modifiedBy",
        "modifiedOn",
        "parentWikiId",
    )

    def __init__(self, **kwargs):
        # Verify that the parameters are correct
        if "owner" not in kwargs:
            raise ValueError("Wiki constructor must have an owner specified")

        # Initialize the file handle list to be an empty list
        if "attachmentFileHandleIds" not in kwargs:
            kwargs["attachmentFileHandleIds"] = []

        # update the markdown
        self.update_markdown(
            kwargs.pop("markdown", None), kwargs.pop("markdownFile", None)
        )

        # Move the 'fileHandles' into the proper (wordier) bucket
        if "fileHandles" in kwargs:
            for handle in kwargs["fileHandles"]:
                kwargs["attachmentFileHandleIds"].append(handle)
            del kwargs["fileHandles"]

        # if parentWikiId is a falsey value (empty string, None, etc),
        # standardize it to None
        if "parentWikiId" in kwargs and not kwargs["parentWikiId"]:
            kwargs["parentWikiId"] = None

        super(Wiki, self).__init__(kwargs)
        self.ownerId = id_of(self.owner)
        del self["owner"]

    def json(self):
        """Returns the JSON representation of the Wiki object."""
        return json.dumps({k: v for k, v in self.items() if k in self.__PROPERTIES})

    def getURI(self):
        """For internal use."""

        return "/entity/%s/wiki/%s" % (self.ownerId, self.id)

    def postURI(self):
        """For internal use."""

        return "/entity/%s/wiki" % self.ownerId

    def putURI(self):
        """For internal use."""

        return "/entity/%s/wiki/%s" % (self.ownerId, self.id)

    def deleteURI(self):
        """For internal use."""

        return "/entity/%s/wiki/%s" % (self.ownerId, self.id)

    def update_markdown(self, markdown=None, markdown_file=None):
        """
        Updates the wiki's markdown. Specify only one of markdown or markdown_file

        Arguments:
            markdown: text that will become the markdown
            markdown_file: path to a file. Its contents will be the markdown
        """
        if markdown and markdown_file:
            raise ValueError("Please use only one argument: markdown or markdownFile")

        if markdown_file:
            # pop the 'markdownFile' kwargs because we don't actually need it in the dictionary to upload to synapse
            markdown_path = os.path.expandvars(os.path.expanduser(markdown_file))
            if not os.path.isfile(markdown_path):
                raise ValueError(markdown_file + "is not a valid file")
            with open(markdown_path, "r") as opened_markdown_file:
                markdown = opened_markdown_file.read()

        self["markdown"] = markdown
Methods:
json
json()

Returns the JSON representation of the Wiki object.

Source code in synapseclient/wiki.py
166
167
168
def json(self):
    """Returns the JSON representation of the Wiki object."""
    return json.dumps({k: v for k, v in self.items() if k in self.__PROPERTIES})
getURI
getURI()

For internal use.

Source code in synapseclient/wiki.py
170
171
172
173
def getURI(self):
    """For internal use."""

    return "/entity/%s/wiki/%s" % (self.ownerId, self.id)
postURI
postURI()

For internal use.

Source code in synapseclient/wiki.py
175
176
177
178
def postURI(self):
    """For internal use."""

    return "/entity/%s/wiki" % self.ownerId
putURI
putURI()

For internal use.

Source code in synapseclient/wiki.py
180
181
182
183
def putURI(self):
    """For internal use."""

    return "/entity/%s/wiki/%s" % (self.ownerId, self.id)
deleteURI
deleteURI()

For internal use.

Source code in synapseclient/wiki.py
185
186
187
188
def deleteURI(self):
    """For internal use."""

    return "/entity/%s/wiki/%s" % (self.ownerId, self.id)
update_markdown
update_markdown(markdown=None, markdown_file=None)

Updates the wiki's markdown. Specify only one of markdown or markdown_file

PARAMETER DESCRIPTION
markdown

text that will become the markdown

DEFAULT: None

markdown_file

path to a file. Its contents will be the markdown

DEFAULT: None

Source code in synapseclient/wiki.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def update_markdown(self, markdown=None, markdown_file=None):
    """
    Updates the wiki's markdown. Specify only one of markdown or markdown_file

    Arguments:
        markdown: text that will become the markdown
        markdown_file: path to a file. Its contents will be the markdown
    """
    if markdown and markdown_file:
        raise ValueError("Please use only one argument: markdown or markdownFile")

    if markdown_file:
        # pop the 'markdownFile' kwargs because we don't actually need it in the dictionary to upload to synapse
        markdown_path = os.path.expandvars(os.path.expanduser(markdown_file))
        if not os.path.isfile(markdown_path):
            raise ValueError(markdown_file + "is not a valid file")
        with open(markdown_path, "r") as opened_markdown_file:
            markdown = opened_markdown_file.read()

    self["markdown"] = markdown

WikiAttachment

Bases: DictObject

Represents a wiki page attachment.

Migration to the object-oriented model

 

Attachments are managed directly on the WikiPage model. Provide local file paths through the attachments field when storing a page, and retrieve the attachment file handles with get_attachment_handles on the WikiPage model.

# New approach (RECOMMENDED)
from synapseclient import Synapse
from synapseclient.models import WikiPage

syn = Synapse()
syn.login()

wiki_page = WikiPage(
    owner_id="syn123",
    title="Home",
    markdown="# Welcome",
    attachments=["/path/to/attachment.txt"],
).store()

attachment_handles = WikiPage(
    owner_id="syn123", id=wiki_page.id
).get_attachment_handles()

Source code in synapseclient/wiki.py
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
@deprecated(
    version="4.14.0",
    reason="To be removed in 5.0.0. "
    "Use synapseclient.models.WikiPage.get_attachment_handles() instead, "
    "which returns the attachment file handles directly.",
)
class WikiAttachment(DictObject):
    """Represents a wiki page attachment.

    Example: Migration to the object-oriented model
         

        Attachments are managed directly on the WikiPage model. Provide local file
        paths through the attachments field when storing a page, and retrieve the
        attachment file handles with get_attachment_handles on the WikiPage model.
        ```python
        # New approach (RECOMMENDED)
        from synapseclient import Synapse
        from synapseclient.models import WikiPage

        syn = Synapse()
        syn.login()

        wiki_page = WikiPage(
            owner_id="syn123",
            title="Home",
            markdown="# Welcome",
            attachments=["/path/to/attachment.txt"],
        ).store()

        attachment_handles = WikiPage(
            owner_id="syn123", id=wiki_page.id
        ).get_attachment_handles()
        ```
    """

    __PROPERTIES = ("contentType", "fileName", "contentMd5", "contentSize")

    def __init__(self, **kwargs):
        super(WikiAttachment, self).__init__(**kwargs)

Functions:

synapseclient.models.wiki

Script to work with Synapse wiki pages.

Classes

WikiOrderHint dataclass

Bases: WikiOrderHintSynchronousProtocol

A WikiOrderHint contains the order hint for the root wiki that corresponds to the given owner ID and type.

ATTRIBUTE DESCRIPTION
owner_id

The Synapse ID of the owner object (e.g., entity, evaluation, etc.).

TYPE: Optional[str]

owner_object_type

The type of the owner object.

TYPE: Optional[str]

id_list

The list of sub wiki ids that in the order that they should be placed relative to their siblings.

TYPE: List[str]

etag

The etag of this object.

TYPE: Optional[str]

Source code in synapseclient/models/wiki.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 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
@dataclass
@async_to_sync
class WikiOrderHint(WikiOrderHintSynchronousProtocol):
    """
    A WikiOrderHint contains the order hint for the root wiki that corresponds to the given owner ID and type.

    Attributes:
        owner_id: The Synapse ID of the owner object (e.g., entity, evaluation, etc.).
        owner_object_type: The type of the owner object.
        id_list: The list of sub wiki ids that in the order that they should be placed relative to their siblings.
        etag: The etag of this object.
    """

    owner_id: Optional[str] = None
    """The Synapse ID of the owner object (e.g., entity, evaluation, etc.)."""

    owner_object_type: Optional[str] = None
    """The type of the owner object."""

    id_list: List[str] = field(default_factory=list)
    """The list of sub wiki ids that in the order that they should be placed relative to their siblings."""

    etag: Optional[str] = field(default=None, compare=False)
    """The etag of this object."""

    def fill_from_dict(
        self,
        wiki_order_hint: Dict[str, Union[str, List[str]]],
    ) -> "WikiOrderHint":
        """
        Converts a response from the REST API into this dataclass.

        Arguments:
            wiki_order_hint: The response from the REST API.

        Returns:
            The WikiOrderHint object.
        """
        self.owner_id = wiki_order_hint.get("ownerId", None)
        self.owner_object_type = wiki_order_hint.get("ownerObjectType", None)
        self.id_list = wiki_order_hint.get("idList", [])
        self.etag = wiki_order_hint.get("etag", None)
        return self

    def to_synapse_request(self) -> Dict[str, List[str]]:
        """
        Convert the WikiOrderHint object to a request for the REST API.
        """
        result = {
            "ownerId": self.owner_id,
            "ownerObjectType": self.owner_object_type,
            "idList": self.id_list,
            "etag": self.etag,
        }
        delete_none_keys(result)
        return result

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Store_Wiki_Order_Hint: {self.owner_id}"
    )
    async def store_async(
        self,
        *,
        synapse_client: Optional["Synapse"] = None,
    ) -> "WikiOrderHint":
        """
        Store the order hint of a wiki page tree.

        Arguments:
            synapse_client: Optionally provide a Synapse client.
        Returns:
            The updated WikiOrderHint object for the entity.
        Raises:
            ValueError: If owner_id or request is not provided.

        Example: Set the WikiOrderHint for a project
            This example shows how to set a WikiOrderHint for existing wiki pages in a project.
            The WikiOrderHint is not set by default, so you need to set it explicitly.
            ```python
            from synapseclient import Synapse
            from synapseclient.models import (
                Project,
                WikiOrderHint,
            )
            syn = Synapse()
            syn.login()
            project = await Project(name="My uniquely named project about Alzheimer's Disease").get_async()
            wiki_order_hint = await WikiOrderHint(owner_id=project.id).get_async()

            wiki_order_hint.id_list = [
                root_wiki_page.id,
                wiki_page_1.id,
                wiki_page_3.id,
                wiki_page_2.id,
                wiki_page_4.id,
            ]
            await wiki_order_hint.store_async()
            print(wiki_order_hint)
            ```
        Example: Update the WikiOrderHint for a project
            This example shows how to update a WikiOrderHint for existing wiki pages in a project.
            ```python
            wiki_order_hint.id_list = [
                root_wiki_page.id,
                wiki_page_1.id,
                wiki_page_2.id,
                wiki_page_3.id,
                wiki_page_4.id,
            ]
            await wiki_order_hint.store_async()
            print(wiki_order_hint)
            ```
        """
        if not self.owner_id:
            raise ValueError("Must provide owner_id to store wiki order hint.")

        order_hint_dict = await put_wiki_order_hint(
            owner_id=self.owner_id,
            request=self.to_synapse_request(),
            synapse_client=synapse_client,
        )
        self.fill_from_dict(order_hint_dict)
        return self

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Get_Wiki_Order_Hint: {self.owner_id}"
    )
    async def get_async(
        self,
        *,
        synapse_client: Optional["Synapse"] = None,
    ) -> "WikiOrderHint":
        """
        Get the order hint of a wiki page tree.

        Arguments:
            synapse_client: Optionally provide a Synapse client.
        Returns:
            A WikiOrderHint object for the entity.
        Raises:
            ValueError: If owner_id is not provided.

        Example: Get the WikiOrderHint for a project
            This example shows how to get a WikiOrderHint for existing wiki pages in a project.
            ```python
            from synapseclient import Synapse
            from synapseclient.models import (
                Project,
                WikiOrderHint,
            )
            syn = Synapse()
            syn.login()
            project = await Project(name="My uniquely named project about Alzheimer's Disease").get_async()
            wiki_order_hint = await WikiOrderHint(owner_id=project.id).get_async()
            print(wiki_order_hint)
            ```
        """
        if not self.owner_id:
            raise ValueError("Must provide owner_id to get wiki order hint.")

        order_hint_dict = await get_wiki_order_hint(
            owner_id=self.owner_id,
            synapse_client=synapse_client,
        )
        return self.fill_from_dict(order_hint_dict)
Attributes
owner_id class-attribute instance-attribute
owner_id: Optional[str] = None

The Synapse ID of the owner object (e.g., entity, evaluation, etc.).

owner_object_type class-attribute instance-attribute
owner_object_type: Optional[str] = None

The type of the owner object.

id_list class-attribute instance-attribute
id_list: List[str] = field(default_factory=list)

The list of sub wiki ids that in the order that they should be placed relative to their siblings.

etag class-attribute instance-attribute
etag: Optional[str] = field(default=None, compare=False)

The etag of this object.

Methods:
store_async async
store_async(*, synapse_client: Optional[Synapse] = None) -> WikiOrderHint

Store the order hint of a wiki page tree.

PARAMETER DESCRIPTION
synapse_client

Optionally provide a Synapse client.

TYPE: Optional[Synapse] DEFAULT: None

Returns: The updated WikiOrderHint object for the entity. Raises: ValueError: If owner_id or request is not provided.

Set the WikiOrderHint for a project

This example shows how to set a WikiOrderHint for existing wiki pages in a project. The WikiOrderHint is not set by default, so you need to set it explicitly.

from synapseclient import Synapse
from synapseclient.models import (
    Project,
    WikiOrderHint,
)
syn = Synapse()
syn.login()
project = await Project(name="My uniquely named project about Alzheimer's Disease").get_async()
wiki_order_hint = await WikiOrderHint(owner_id=project.id).get_async()

wiki_order_hint.id_list = [
    root_wiki_page.id,
    wiki_page_1.id,
    wiki_page_3.id,
    wiki_page_2.id,
    wiki_page_4.id,
]
await wiki_order_hint.store_async()
print(wiki_order_hint)

Example: Update the WikiOrderHint for a project This example shows how to update a WikiOrderHint for existing wiki pages in a project.

wiki_order_hint.id_list = [
    root_wiki_page.id,
    wiki_page_1.id,
    wiki_page_2.id,
    wiki_page_3.id,
    wiki_page_4.id,
]
await wiki_order_hint.store_async()
print(wiki_order_hint)

Source code in synapseclient/models/wiki.py
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
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"Store_Wiki_Order_Hint: {self.owner_id}"
)
async def store_async(
    self,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> "WikiOrderHint":
    """
    Store the order hint of a wiki page tree.

    Arguments:
        synapse_client: Optionally provide a Synapse client.
    Returns:
        The updated WikiOrderHint object for the entity.
    Raises:
        ValueError: If owner_id or request is not provided.

    Example: Set the WikiOrderHint for a project
        This example shows how to set a WikiOrderHint for existing wiki pages in a project.
        The WikiOrderHint is not set by default, so you need to set it explicitly.
        ```python
        from synapseclient import Synapse
        from synapseclient.models import (
            Project,
            WikiOrderHint,
        )
        syn = Synapse()
        syn.login()
        project = await Project(name="My uniquely named project about Alzheimer's Disease").get_async()
        wiki_order_hint = await WikiOrderHint(owner_id=project.id).get_async()

        wiki_order_hint.id_list = [
            root_wiki_page.id,
            wiki_page_1.id,
            wiki_page_3.id,
            wiki_page_2.id,
            wiki_page_4.id,
        ]
        await wiki_order_hint.store_async()
        print(wiki_order_hint)
        ```
    Example: Update the WikiOrderHint for a project
        This example shows how to update a WikiOrderHint for existing wiki pages in a project.
        ```python
        wiki_order_hint.id_list = [
            root_wiki_page.id,
            wiki_page_1.id,
            wiki_page_2.id,
            wiki_page_3.id,
            wiki_page_4.id,
        ]
        await wiki_order_hint.store_async()
        print(wiki_order_hint)
        ```
    """
    if not self.owner_id:
        raise ValueError("Must provide owner_id to store wiki order hint.")

    order_hint_dict = await put_wiki_order_hint(
        owner_id=self.owner_id,
        request=self.to_synapse_request(),
        synapse_client=synapse_client,
    )
    self.fill_from_dict(order_hint_dict)
    return self
get_async async
get_async(*, synapse_client: Optional[Synapse] = None) -> WikiOrderHint

Get the order hint of a wiki page tree.

PARAMETER DESCRIPTION
synapse_client

Optionally provide a Synapse client.

TYPE: Optional[Synapse] DEFAULT: None

Returns: A WikiOrderHint object for the entity. Raises: ValueError: If owner_id is not provided.

Get the WikiOrderHint for a project

This example shows how to get a WikiOrderHint for existing wiki pages in a project.

from synapseclient import Synapse
from synapseclient.models import (
    Project,
    WikiOrderHint,
)
syn = Synapse()
syn.login()
project = await Project(name="My uniquely named project about Alzheimer's Disease").get_async()
wiki_order_hint = await WikiOrderHint(owner_id=project.id).get_async()
print(wiki_order_hint)

Source code in synapseclient/models/wiki.py
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
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"Get_Wiki_Order_Hint: {self.owner_id}"
)
async def get_async(
    self,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> "WikiOrderHint":
    """
    Get the order hint of a wiki page tree.

    Arguments:
        synapse_client: Optionally provide a Synapse client.
    Returns:
        A WikiOrderHint object for the entity.
    Raises:
        ValueError: If owner_id is not provided.

    Example: Get the WikiOrderHint for a project
        This example shows how to get a WikiOrderHint for existing wiki pages in a project.
        ```python
        from synapseclient import Synapse
        from synapseclient.models import (
            Project,
            WikiOrderHint,
        )
        syn = Synapse()
        syn.login()
        project = await Project(name="My uniquely named project about Alzheimer's Disease").get_async()
        wiki_order_hint = await WikiOrderHint(owner_id=project.id).get_async()
        print(wiki_order_hint)
        ```
    """
    if not self.owner_id:
        raise ValueError("Must provide owner_id to get wiki order hint.")

    order_hint_dict = await get_wiki_order_hint(
        owner_id=self.owner_id,
        synapse_client=synapse_client,
    )
    return self.fill_from_dict(order_hint_dict)

WikiHistorySnapshot dataclass

Bases: WikiHistorySnapshotSynchronousProtocol

A WikiHistorySnapshot contains basic information about an update to a WikiPage.

ATTRIBUTE DESCRIPTION
version

The version number of the wiki page.

TYPE: Optional[str]

modified_on

The timestamp when this version was created. modified_by: The ID of the user that created this version.

TYPE: Optional[str]

Source code in synapseclient/models/wiki.py
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
333
334
335
336
337
338
339
340
341
342
343
344
@dataclass
@async_to_sync
class WikiHistorySnapshot(WikiHistorySnapshotSynchronousProtocol):
    """
    A WikiHistorySnapshot contains basic information about an update to a WikiPage.

    Attributes:
        version: The version number of the wiki page.
        modified_on: The timestamp when this version was created.
            modified_by: The ID of the user that created this version.
    """

    version: Optional[str] = None
    """The version number of the wiki page."""

    modified_on: Optional[str] = None
    """The timestamp when this version was created."""

    modified_by: Optional[str] = None
    """The ID of the user that created this version."""

    def fill_from_dict(
        self,
        wiki_history: Dict[str, str],
    ) -> "WikiHistorySnapshot":
        """
        Converts a response from the REST API into this dataclass.

        Arguments:
            wiki_history: The response from the REST API.

        Returns:
            The WikiHistorySnapshot object.
        """
        self.version = wiki_history.get("version", None)
        self.modified_on = wiki_history.get("modifiedOn", None)
        self.modified_by = wiki_history.get("modifiedBy", None)
        return self

    @skip_async_to_sync
    @classmethod
    async def get_async(
        cls,
        owner_id: str = None,
        id: str = None,
        *,
        offset: int = 0,
        limit: int = 20,
        synapse_client: Optional["Synapse"] = None,
    ) -> AsyncGenerator["WikiHistorySnapshot", None]:
        """
        Get the history of a wiki page as a list of WikiHistorySnapshot objects.

        Arguments:
            owner_id: The Synapse ID of the owner entity.
            id: The ID of the wiki page.
            offset: The index of the pagination offset.
            limit: Limits the size of the page returned.
            synapse_client: Optionally provide a Synapse client.
        Yields:
            Individual WikiHistorySnapshot objects from each page of the response.

        Example: Get the history of a wiki page
            ```python
            async def main():
                async for item in WikiHistorySnapshot.get_async(owner_id=project.id, id=wiki_page.id):
                    print(f"History: {item}")
            asyncio.run(main())
            ```
        """
        if not owner_id:
            raise ValueError("Must provide owner_id to get wiki history.")
        if not id:
            raise ValueError("Must provide id to get wiki history.")
        async for item in get_wiki_history(
            owner_id=owner_id,
            wiki_id=id,  # use id instead of wiki_id to match other classes
            offset=offset,
            limit=limit,
            synapse_client=synapse_client,
        ):
            item = cls().fill_from_dict(wiki_history=item)
            yield item

    @classmethod
    def get(
        cls,
        owner_id: str = None,
        id: str = None,
        *,
        offset: int = 0,
        limit: int = 20,
        synapse_client: Optional["Synapse"] = None,
    ) -> Generator["WikiHistorySnapshot", None, None]:
        """
        Get the history of a wiki page as a list of WikiHistorySnapshot objects.

        Arguments:
            owner_id: The Synapse ID of the owner entity.
            id: The ID of the wiki page.
            offset: The index of the pagination offset.
            limit: Limits the size of the page returned.
            synapse_client: Optionally provide a Synapse client.
        Yields:
            Individual WikiHistorySnapshot objects from each page of the response.

        Example: Get the history of a wiki page
            ```python
            for history in WikiHistorySnapshot.get(owner_id=project.id, id=wiki_page.id):
                print(f"History: {history}")
            ```
        """
        return wrap_async_generator_to_sync_generator(
            async_gen_func=cls().get_async,
            owner_id=owner_id,
            id=id,
            offset=offset,
            limit=limit,
            synapse_client=synapse_client,
        )
Attributes
version class-attribute instance-attribute
version: Optional[str] = None

The version number of the wiki page.

modified_on class-attribute instance-attribute
modified_on: Optional[str] = None

The timestamp when this version was created.

modified_by class-attribute instance-attribute
modified_by: Optional[str] = None

The ID of the user that created this version.

Methods:
get_async async classmethod
get_async(owner_id: str = None, id: str = None, *, offset: int = 0, limit: int = 20, synapse_client: Optional[Synapse] = None) -> AsyncGenerator[WikiHistorySnapshot, None]

Get the history of a wiki page as a list of WikiHistorySnapshot objects.

PARAMETER DESCRIPTION
owner_id

The Synapse ID of the owner entity.

TYPE: str DEFAULT: None

id

The ID of the wiki page.

TYPE: str DEFAULT: None

offset

The index of the pagination offset.

TYPE: int DEFAULT: 0

limit

Limits the size of the page returned.

TYPE: int DEFAULT: 20

synapse_client

Optionally provide a Synapse client.

TYPE: Optional[Synapse] DEFAULT: None

Yields: Individual WikiHistorySnapshot objects from each page of the response.

Get the history of a wiki page
async def main():
    async for item in WikiHistorySnapshot.get_async(owner_id=project.id, id=wiki_page.id):
        print(f"History: {item}")
asyncio.run(main())
Source code in synapseclient/models/wiki.py
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
@skip_async_to_sync
@classmethod
async def get_async(
    cls,
    owner_id: str = None,
    id: str = None,
    *,
    offset: int = 0,
    limit: int = 20,
    synapse_client: Optional["Synapse"] = None,
) -> AsyncGenerator["WikiHistorySnapshot", None]:
    """
    Get the history of a wiki page as a list of WikiHistorySnapshot objects.

    Arguments:
        owner_id: The Synapse ID of the owner entity.
        id: The ID of the wiki page.
        offset: The index of the pagination offset.
        limit: Limits the size of the page returned.
        synapse_client: Optionally provide a Synapse client.
    Yields:
        Individual WikiHistorySnapshot objects from each page of the response.

    Example: Get the history of a wiki page
        ```python
        async def main():
            async for item in WikiHistorySnapshot.get_async(owner_id=project.id, id=wiki_page.id):
                print(f"History: {item}")
        asyncio.run(main())
        ```
    """
    if not owner_id:
        raise ValueError("Must provide owner_id to get wiki history.")
    if not id:
        raise ValueError("Must provide id to get wiki history.")
    async for item in get_wiki_history(
        owner_id=owner_id,
        wiki_id=id,  # use id instead of wiki_id to match other classes
        offset=offset,
        limit=limit,
        synapse_client=synapse_client,
    ):
        item = cls().fill_from_dict(wiki_history=item)
        yield item
get classmethod
get(owner_id: str = None, id: str = None, *, offset: int = 0, limit: int = 20, synapse_client: Optional[Synapse] = None) -> Generator[WikiHistorySnapshot, None, None]

Get the history of a wiki page as a list of WikiHistorySnapshot objects.

PARAMETER DESCRIPTION
owner_id

The Synapse ID of the owner entity.

TYPE: str DEFAULT: None

id

The ID of the wiki page.

TYPE: str DEFAULT: None

offset

The index of the pagination offset.

TYPE: int DEFAULT: 0

limit

Limits the size of the page returned.

TYPE: int DEFAULT: 20

synapse_client

Optionally provide a Synapse client.

TYPE: Optional[Synapse] DEFAULT: None

Yields: Individual WikiHistorySnapshot objects from each page of the response.

Get the history of a wiki page
for history in WikiHistorySnapshot.get(owner_id=project.id, id=wiki_page.id):
    print(f"History: {history}")
Source code in synapseclient/models/wiki.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
@classmethod
def get(
    cls,
    owner_id: str = None,
    id: str = None,
    *,
    offset: int = 0,
    limit: int = 20,
    synapse_client: Optional["Synapse"] = None,
) -> Generator["WikiHistorySnapshot", None, None]:
    """
    Get the history of a wiki page as a list of WikiHistorySnapshot objects.

    Arguments:
        owner_id: The Synapse ID of the owner entity.
        id: The ID of the wiki page.
        offset: The index of the pagination offset.
        limit: Limits the size of the page returned.
        synapse_client: Optionally provide a Synapse client.
    Yields:
        Individual WikiHistorySnapshot objects from each page of the response.

    Example: Get the history of a wiki page
        ```python
        for history in WikiHistorySnapshot.get(owner_id=project.id, id=wiki_page.id):
            print(f"History: {history}")
        ```
    """
    return wrap_async_generator_to_sync_generator(
        async_gen_func=cls().get_async,
        owner_id=owner_id,
        id=id,
        offset=offset,
        limit=limit,
        synapse_client=synapse_client,
    )

WikiHeader dataclass

Bases: WikiHeaderSynchronousProtocol

A WikiHeader contains basic metadata about a WikiPage.

ATTRIBUTE DESCRIPTION
id

The unique identifier for this wiki page.

TYPE: Optional[str]

title

The title of this page.

TYPE: Optional[str]

parent_id

When set, the WikiPage is a sub-page of the indicated parent WikiPage.

TYPE: Optional[str]

Source code in synapseclient/models/wiki.py
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
@dataclass
@async_to_sync
class WikiHeader(WikiHeaderSynchronousProtocol):
    """
    A WikiHeader contains basic metadata about a WikiPage.

    Attributes:
        id: The unique identifier for this wiki page.
        title: The title of this page.
        parent_id: When set, the WikiPage is a sub-page of the indicated parent WikiPage.
    """

    id: Optional[str] = None
    """The unique identifier for this wiki page."""

    title: Optional[str] = None
    """The title of this page."""

    parent_id: Optional[str] = None
    """When set, the WikiPage is a sub-page of the indicated parent WikiPage."""

    def fill_from_dict(
        self,
        wiki_header: Dict[str, str],
    ) -> "WikiHeader":
        """
        Converts a response from the REST API into this dataclass.

        Arguments:
            wiki_header: The response from the REST API.

        Returns:
            The WikiHeader object.
        """
        self.id = wiki_header.get("id", None)
        self.title = wiki_header.get("title", None)
        self.parent_id = wiki_header.get("parentId", None)
        return self

    @skip_async_to_sync
    @classmethod
    async def get_async(
        cls,
        owner_id: str = None,
        *,
        offset: int = 0,
        limit: int = 20,
        synapse_client: Optional["Synapse"] = None,
    ) -> AsyncGenerator["WikiHeader", None]:
        """
        Get the header tree (hierarchy) of wiki pages for an entity.

        Arguments:
            owner_id: The Synapse ID of the owner entity.
            offset: The index of the pagination offset.
            limit: Limits the size of the page returned.
            synapse_client: Optionally provide a Synapse client.
        Yields:
            Individual WikiHeader objects for the entity.

        Example: Get the header tree (hierarchy) of wiki pages for an entity
            ```python
            async def main():
                async for item in WikiHeader.get_async(owner_id=project.id):
                    print(f"Header: {item}")
            asyncio.run(main())
            ```
        """
        if not owner_id:
            raise ValueError("Must provide owner_id to get wiki header tree.")
        async for item in get_wiki_header_tree(
            owner_id=owner_id,
            offset=offset,
            limit=limit,
            synapse_client=synapse_client,
        ):
            item = cls().fill_from_dict(wiki_header=item)
            yield item

    @classmethod
    def get(
        cls,
        owner_id: str,
        *,
        offset: int = 0,
        limit: int = 20,
        synapse_client: Optional["Synapse"] = None,
    ) -> Generator["WikiHeader", None, None]:
        """
        Get the header tree (hierarchy) of wiki pages for an entity.

        Arguments:
            owner_id: The ID of the owner entity.
            offset: The index of the pagination offset.
            limit: Limits the size of the page returned.
            synapse_client: Optionally provide a Synapse client.
        Yields:
            Individual WikiHeader objects for the entity.

        Example: Get the header tree (hierarchy) of wiki pages for an entity
            ```python
            for header in WikiHeader.get(owner_id=project.id):
                print(f"Header: {header}")
            ```
        """
        return wrap_async_generator_to_sync_generator(
            async_gen_func=cls().get_async,
            owner_id=owner_id,
            offset=offset,
            limit=limit,
            synapse_client=synapse_client,
        )
Attributes
id class-attribute instance-attribute
id: Optional[str] = None

The unique identifier for this wiki page.

title class-attribute instance-attribute
title: Optional[str] = None

The title of this page.

parent_id class-attribute instance-attribute
parent_id: Optional[str] = None

When set, the WikiPage is a sub-page of the indicated parent WikiPage.

Methods:
get_async async classmethod
get_async(owner_id: str = None, *, offset: int = 0, limit: int = 20, synapse_client: Optional[Synapse] = None) -> AsyncGenerator[WikiHeader, None]

Get the header tree (hierarchy) of wiki pages for an entity.

PARAMETER DESCRIPTION
owner_id

The Synapse ID of the owner entity.

TYPE: str DEFAULT: None

offset

The index of the pagination offset.

TYPE: int DEFAULT: 0

limit

Limits the size of the page returned.

TYPE: int DEFAULT: 20

synapse_client

Optionally provide a Synapse client.

TYPE: Optional[Synapse] DEFAULT: None

Yields: Individual WikiHeader objects for the entity.

Get the header tree (hierarchy) of wiki pages for an entity
async def main():
    async for item in WikiHeader.get_async(owner_id=project.id):
        print(f"Header: {item}")
asyncio.run(main())
Source code in synapseclient/models/wiki.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
@skip_async_to_sync
@classmethod
async def get_async(
    cls,
    owner_id: str = None,
    *,
    offset: int = 0,
    limit: int = 20,
    synapse_client: Optional["Synapse"] = None,
) -> AsyncGenerator["WikiHeader", None]:
    """
    Get the header tree (hierarchy) of wiki pages for an entity.

    Arguments:
        owner_id: The Synapse ID of the owner entity.
        offset: The index of the pagination offset.
        limit: Limits the size of the page returned.
        synapse_client: Optionally provide a Synapse client.
    Yields:
        Individual WikiHeader objects for the entity.

    Example: Get the header tree (hierarchy) of wiki pages for an entity
        ```python
        async def main():
            async for item in WikiHeader.get_async(owner_id=project.id):
                print(f"Header: {item}")
        asyncio.run(main())
        ```
    """
    if not owner_id:
        raise ValueError("Must provide owner_id to get wiki header tree.")
    async for item in get_wiki_header_tree(
        owner_id=owner_id,
        offset=offset,
        limit=limit,
        synapse_client=synapse_client,
    ):
        item = cls().fill_from_dict(wiki_header=item)
        yield item
get classmethod
get(owner_id: str, *, offset: int = 0, limit: int = 20, synapse_client: Optional[Synapse] = None) -> Generator[WikiHeader, None, None]

Get the header tree (hierarchy) of wiki pages for an entity.

PARAMETER DESCRIPTION
owner_id

The ID of the owner entity.

TYPE: str

offset

The index of the pagination offset.

TYPE: int DEFAULT: 0

limit

Limits the size of the page returned.

TYPE: int DEFAULT: 20

synapse_client

Optionally provide a Synapse client.

TYPE: Optional[Synapse] DEFAULT: None

Yields: Individual WikiHeader objects for the entity.

Get the header tree (hierarchy) of wiki pages for an entity
for header in WikiHeader.get(owner_id=project.id):
    print(f"Header: {header}")
Source code in synapseclient/models/wiki.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
@classmethod
def get(
    cls,
    owner_id: str,
    *,
    offset: int = 0,
    limit: int = 20,
    synapse_client: Optional["Synapse"] = None,
) -> Generator["WikiHeader", None, None]:
    """
    Get the header tree (hierarchy) of wiki pages for an entity.

    Arguments:
        owner_id: The ID of the owner entity.
        offset: The index of the pagination offset.
        limit: Limits the size of the page returned.
        synapse_client: Optionally provide a Synapse client.
    Yields:
        Individual WikiHeader objects for the entity.

    Example: Get the header tree (hierarchy) of wiki pages for an entity
        ```python
        for header in WikiHeader.get(owner_id=project.id):
            print(f"Header: {header}")
        ```
    """
    return wrap_async_generator_to_sync_generator(
        async_gen_func=cls().get_async,
        owner_id=owner_id,
        offset=offset,
        limit=limit,
        synapse_client=synapse_client,
    )

WikiPage dataclass

Bases: WikiPageSynchronousProtocol

Represents a Wiki Page.

ATTRIBUTE DESCRIPTION
id

The unique identifier for this wiki page.

TYPE: Optional[str]

etag

The etag of this object. Synapse employs an Optimistic Concurrency Control (OCC) scheme to handle concurrent updates. Since the E-Tag changes every time an entity is updated it is used to detect when a client's current representation of an entity is out-of-date.

TYPE: Optional[str]

title

The title of this page.

TYPE: Optional[str]

parent_id

When set, the WikiPage is a sub-page of the indicated parent WikiPage.

TYPE: Optional[str]

markdown

The markdown content of the wiki page.

TYPE: Optional[str]

attachments

A list of file attachments associated with the wiki page.

TYPE: List[Dict[str, Any]]

owner_id

The Synapse ID of the owning object (e.g., entity, evaluation, etc.).

TYPE: Optional[str]

created_on

The timestamp when this page was created.

TYPE: Optional[str]

created_by

The ID of the user that created this page.

TYPE: Optional[str]

modified_on

The timestamp when this page was last modified.

TYPE: Optional[str]

modified_by

The ID of the user that last modified this page.

TYPE: Optional[str]

wiki_version

The version number of this wiki page.

TYPE: Optional[str]

markdown_file_handle_id

The ID of the file handle containing the markdown content.

TYPE: Optional[str]

attachment_file_handle_ids

The list of attachment file handle ids of this page.

TYPE: List[str]

Source code in synapseclient/models/wiki.py
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
@dataclass
@async_to_sync
class WikiPage(WikiPageSynchronousProtocol):
    """
    Represents a [Wiki Page](https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/model/v2/wiki/V2WikiPage.html).

    Attributes:
        id: The unique identifier for this wiki page.
        etag: The etag of this object. Synapse employs an Optimistic Concurrency Control (OCC) scheme to handle
            concurrent updates. Since the E-Tag changes every time an entity is updated it is
            used to detect when a client's current representation of an entity is out-of-date.
        title: The title of this page.
        parent_id: When set, the WikiPage is a sub-page of the indicated parent WikiPage.
        markdown: The markdown content of the wiki page.
        attachments: A list of file attachments associated with the wiki page.
        owner_id: The Synapse ID of the owning object (e.g., entity, evaluation, etc.).
        created_on: The timestamp when this page was created.
        created_by: The ID of the user that created this page.
        modified_on: The timestamp when this page was last modified.
        modified_by: The ID of the user that last modified this page.
        wiki_version: The version number of this wiki page.
        markdown_file_handle_id: The ID of the file handle containing the markdown content.
        attachment_file_handle_ids: The list of attachment file handle ids of this page.
    """

    id: Optional[str] = None
    """The unique identifier for this wiki page."""

    etag: Optional[str] = field(default=None, compare=False)
    """The etag of this object. Synapse employs an Optimistic Concurrency Control (OCC) scheme to handle concurrent
    updates. Since the E-Tag changes every time an entity is updated it is used to detect
    when a client's current representation of an entity is out-of-date."""

    title: Optional[str] = None
    """The title of this page."""

    parent_id: Optional[str] = None
    """When set, the WikiPage is a sub-page of the indicated parent WikiPage."""

    markdown: Optional[str] = None
    """The markdown content of this page."""

    attachments: List[Dict[str, Any]] = field(default_factory=list)
    """A list of file paths sassociated with this page."""

    owner_id: Optional[str] = None
    """The Synapse ID of the owning object (e.g., entity, evaluation, etc.)."""

    created_on: Optional[str] = field(default=None, compare=False)
    """The timestamp when this page was created."""

    created_by: Optional[str] = field(default=None, compare=False)
    """The ID of the user that created this page."""

    modified_on: Optional[str] = field(default=None, compare=False)
    """The timestamp when this page was last modified."""

    modified_by: Optional[str] = field(default=None, compare=False)
    """The ID of the user that last modified this page."""

    wiki_version: Optional[str] = None
    """The version number of this wiki page."""

    markdown_file_handle_id: Optional[str] = None
    """The ID of the file handle containing the markdown content."""

    attachment_file_handle_ids: List[str] = field(default_factory=list)
    """The list of attachment file handle ids of this page."""

    def fill_from_dict(
        self,
        synapse_wiki: Dict[str, Union[str, List[str], List[Dict[str, Any]]]],
    ) -> "WikiPage":
        """
        Converts a response from the REST API into this dataclass.

        Arguments:
            synapse_wiki: The response from the REST API.

        Returns:
            The WikiPage object.
        """
        self.id = synapse_wiki.get("id", None)
        self.etag = synapse_wiki.get("etag", None)
        self.title = synapse_wiki.get("title", None)
        self.parent_id = synapse_wiki.get("parentWikiId", None)
        self.markdown = self.markdown
        self.attachments = self.attachments
        self.created_on = synapse_wiki.get("createdOn", None)
        self.created_by = synapse_wiki.get("createdBy", None)
        self.modified_on = synapse_wiki.get("modifiedOn", None)
        self.modified_by = synapse_wiki.get("modifiedBy", None)
        self.wiki_version = self.wiki_version
        self.markdown_file_handle_id = synapse_wiki.get("markdownFileHandleId", None)
        self.attachment_file_handle_ids = synapse_wiki.get(
            "attachmentFileHandleIds", []
        )
        return self

    def to_synapse_request(
        self,
    ) -> Dict[str, Union[str, List[str], List[Dict[str, Any]]]]:
        """Convert the wiki page object into a format suitable for the Synapse API."""
        result = {
            "id": self.id,
            "etag": self.etag,
            "title": self.title,
            "parentWikiId": self.parent_id,
            "markdown": self.markdown,
            "attachments": self.attachments,
            "createdOn": self.created_on,
            "createdBy": self.created_by,
            "modifiedOn": self.modified_on,
            "modifiedBy": self.modified_by,
            "wikiVersion": self.wiki_version,
            "markdownFileHandleId": self.markdown_file_handle_id,
            "attachmentFileHandleIds": self.attachment_file_handle_ids,
        }
        delete_none_keys(result)
        return result

    def _to_gzip_file(
        self,
        wiki_content: str,
        synapse_client: Optional[Synapse] = None,
    ) -> str:
        """Convert markdown or attachment to a gzipped file and save it in the synapse cache to get a file handle id later.

        Arguments:
            wiki_content: The markdown or attachment content as plain text, basic HTML, or Markdown, or a file path to such content.
            synapse_client: The Synapse client to use for cache access.

        Returns:
            The path to the gzipped file and the cache directory.
        """
        if not isinstance(wiki_content, str):
            raise SyntaxError(f"Expected a string, got {type(wiki_content).__name__}")
        # Get the cache directory path to save the newly created gzipped file
        cache_dir = os.path.join(synapse_client.cache.cache_root_dir, "wiki_content")
        if not os.path.exists(cache_dir):
            os.makedirs(cache_dir)

        if os.path.isfile(wiki_content):
            if wiki_content.endswith(".gz"):
                file_path = wiki_content
            else:
                # If it's a regular html or markdown file, compress it
                with open(wiki_content, "rb") as f_in:
                    file_path = os.path.join(
                        cache_dir, os.path.basename(wiki_content) + ".gz"
                    )
                    with gzip.open(file_path, "wb") as f_out:
                        f_out.writelines(f_in)

        else:
            # If it's a plain text, write it to a gzipped file and save it in the synapse cache
            file_path = os.path.join(cache_dir, f"wiki_markdown_{self.title}.md.gz")
            with gzip.open(file_path, "wt", encoding="utf-8") as f_out:
                f_out.write(wiki_content)

        return file_path

    @staticmethod
    def unzip_gzipped_file(file_path: str) -> str:
        """Unzip the gzipped file and return the file path to the unzipped file.
        If the file is a markdown file, the content will be printed.

        Arguments:
            file_path: The path to the gzipped file.
        Returns:
            The file path to the unzipped file.

        Example: Unzip a gzipped file
            ```python
            file_path = "path/to/file.md.gz"
            unzipped_file_path = WikiPage.unzip_gzipped_file(file_path)
            ```
        """
        with gzip.open(file_path, "rb") as f_in:
            unzipped_content_bytes = f_in.read()

            is_text_file = False
            unzipped_content_text = None
            try:
                unzipped_content_text = unzipped_content_bytes.decode("utf-8")
                is_text_file = True
                if file_path.endswith(".md.gz"):
                    pprint.pp(unzipped_content_text)
            except UnicodeDecodeError:
                # It's a binary file, keep as bytes
                pass

            unzipped_file_path = os.path.join(
                os.path.dirname(file_path),
                os.path.basename(file_path).replace(".gz", ""),
            )
            if is_text_file:
                with open(unzipped_file_path, "wt", encoding="utf-8") as f_out:
                    f_out.write(unzipped_content_text)
            else:
                with open(unzipped_file_path, "wb") as f_out:
                    f_out.write(unzipped_content_bytes)

            return unzipped_file_path

    @staticmethod
    def _get_file_size(filehandle_dict: dict, file_name: str) -> str:
        """Get the file name from the response headers.
        Arguments:
            response: The response from the REST API.
        Returns:
            The file name.
        """
        filehandle_dict = filehandle_dict["list"]
        available_files = [filehandle["fileName"] for filehandle in filehandle_dict]
        # locate the contentSize for given file_name
        for filehandle in filehandle_dict:
            if filehandle["fileName"] == file_name:
                return filehandle["contentSize"]
        raise ValueError(
            f"File {file_name} not found in filehandle_dict. Available files: {available_files}"
        )

    @staticmethod
    def reformat_attachment_file_name(attachment_file_name: str) -> str:
        """Reformat the attachment file name to be a valid attachment path.

        Arguments:
            attachment_file_name: The name of the attachment file.
        Returns:
            The reformatted attachment file name.

        Example: Reformat the attachment file name
            ```python
            attachment_file_name = "file.txt"
            attachment_file_name_reformatted = WikiPage.reformat_attachment_file_name(attachment_file_name)
            print(f"Reformatted attachment file name: {attachment_file_name_reformatted}")
            ```
        """
        attachment_file_name_reformatted = attachment_file_name.replace(".", "%2E")
        attachment_file_name_reformatted = attachment_file_name_reformatted.replace(
            "_", "%5F"
        )
        return attachment_file_name_reformatted

    @staticmethod
    def _should_gzip_file(file_path: str) -> bool:
        """Check if a file should be gzipped.

        Files that are already gzipped or are image files (png, jpg, jpeg) should not be gzipped.

        Arguments:
            file_path: The path or name of the file to check.
        Returns:
            True if the file should be gzipped, False otherwise.
        """
        return (
            not file_path.endswith(".gz")
            and not file_path.endswith(".png")
            and not file_path.endswith(".jpg")
            and not file_path.endswith(".jpeg")
        )

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Get the markdown file handle: {self.owner_id}"
    )
    async def _get_markdown_file_handle(self, synapse_client: Synapse) -> "WikiPage":
        """Get the markdown file handle from the synapse client.
        Arguments:
            synapse_client: The Synapse client to use for cache access.
        Returns:
            A WikiPage with the updated markdown file handle id.
        """
        if not self.markdown:
            return self
        else:
            file_path = self._to_gzip_file(
                wiki_content=self.markdown, synapse_client=synapse_client
            )
            try:
                async with synapse_client._get_parallel_file_transfer_semaphore(
                    asyncio_event_loop=asyncio.get_running_loop()
                ):
                    file_handle = await upload_file_handle(
                        syn=synapse_client,
                        parent_entity_id=self.owner_id,
                        path=file_path,
                    )
                    synapse_client.logger.info(
                        f"[{self.owner_id}:{self.id}]: Uploaded file handle "
                        f"{file_handle.get('id')} for wiki page markdown."
                    )
                    self.markdown_file_handle_id = file_handle.get("id")
            finally:
                if os.path.exists(file_path):
                    os.remove(file_path)
                    synapse_client.logger.debug(
                        f"[{self.owner_id}:{self.id}]: Deleted temp directory {file_path}"
                    )
            return self

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Get the attachment file handles for wiki page: {self.owner_id}"
    )
    async def _get_attachment_file_handles(self, synapse_client: Synapse) -> "WikiPage":
        """Get the attachment file handles from the synapse client.
        Arguments:
            synapse_client: The Synapse client to use for cache access.
        Returns:
            A WikiPage with the updated attachment file handle ids.
        """
        if not self.attachments:
            return self
        else:

            async def task_of_uploading_attachment(attachment: str) -> tuple[str, str]:
                """Process a single attachment and return its file handle ID and cache directory."""
                if WikiPage._should_gzip_file(attachment):
                    file_path = self._to_gzip_file(
                        wiki_content=attachment, synapse_client=synapse_client
                    )
                else:
                    file_path = attachment
                try:
                    async with synapse_client._get_parallel_file_transfer_semaphore(
                        asyncio_event_loop=asyncio.get_running_loop()
                    ):
                        file_handle = await upload_file_handle(
                            syn=synapse_client,
                            parent_entity_id=self.owner_id,
                            path=file_path,
                        )
                        synapse_client.logger.info(
                            f"[{self.owner_id}:{self.id}]: Uploaded file handle "
                            f"{file_handle.get('id')} for wiki page attachment."
                        )
                        return file_handle.get("id")
                finally:
                    if os.path.exists(file_path):
                        os.remove(file_path)
                        synapse_client.logger.debug(
                            f"[{self.owner_id}:{self.id}]: Deleted temp directory "
                            f"{file_path}"
                        )

            tasks = [
                asyncio.create_task(task_of_uploading_attachment(attachment))
                for attachment in self.attachments
            ]
            results = await asyncio.gather(*tasks)
            self.attachment_file_handle_ids = results
            return self

    async def _determine_wiki_action(
        self,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> Literal[
        "create_root_wiki_page", "update_existing_wiki_page", "create_sub_wiki_page"
    ]:
        """Determine the wiki action to perform.
        Returns:
            The wiki action to perform.
        Raises:
            ValueError: If required fields are missing.
        """
        if not self.owner_id:
            raise ValueError("Must provide owner_id to modify a wiki page.")

        if self.parent_id:
            return "create_sub_wiki_page"

        try:
            headers = WikiHeader.get_async(
                owner_id=self.owner_id,
                synapse_client=synapse_client,
            )
            await anext(headers)
        except SynapseHTTPError as e:
            if e.response.status_code == 404:
                return "create_root_wiki_page"
            else:
                raise
        else:
            if not self.id:
                raise ValueError("Must provide id to update existing wiki page.")
            return "update_existing_wiki_page"

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Store the wiki page: {self.owner_id}"
    )
    async def store_async(
        self,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> "WikiPage":
        """Store the wiki page. If there is no wiki page, a new wiki page will be created.
        If the wiki page already exists, it will be updated.
        Subwiki pages are created by passing in a parent_id.
        If a parent_id is provided, the wiki page will be created as a subwiki page.

        Arguments:
            synapse_client: If not passed in and caching was not disabled by
                    `Synapse.allow_client_caching(False)` this will use the last created
                    instance from the Synapse class constructor.

        Returns:
            The created/updated wiki page.

        Raises:
            ValueError: If owner_id is not provided or if required fields are missing.

        Example: Store a wiki page
            This example shows how to store a wiki page.
            ```python
            from synapseclient import Synapse
            from synapseclient.models import (
                Project,
                WikiPage,
            )
            syn = Synapse()
            syn.login()
            project = await Project(name="My uniquely named project about Alzheimer's Disease").get_async()
            wiki_page = await WikiPage(owner_id=project.id, title="My wiki page").store_async()
            print(wiki_page)
            ```
        """
        client = Synapse.get_client(synapse_client=synapse_client)

        wiki_action = await self._determine_wiki_action(synapse_client=client)
        # get the markdown file handle and attachment file handles if the wiki action is valid
        if wiki_action:
            # Update self with the returned WikiPage objects that have file handle IDs set
            self = await self._get_markdown_file_handle(synapse_client=client)
            self = await self._get_attachment_file_handles(synapse_client=client)

        if wiki_action == "create_root_wiki_page":
            client.logger.info(
                f"[{self.owner_id}]: No wiki page exists within the owner. "
                "Create a new wiki page."
            )
            wiki_data = await post_wiki_page(
                owner_id=self.owner_id,
                request=self.to_synapse_request(),
                synapse_client=client,
            )
            client.logger.info(
                f"[{self.owner_id}]: Created wiki page: {wiki_data.get('title')} "
                f"with ID: {wiki_data.get('id')}."
            )
        elif wiki_action == "update_existing_wiki_page":
            client.logger.info(
                f"[{self.owner_id}:{self.id}]: A wiki page already exists within the "
                "owner. Update the existing wiki page."
            )
            existing_wiki_dict = await get_wiki_page(
                owner_id=self.owner_id,
                wiki_id=self.id,
                wiki_version=self.wiki_version,
                synapse_client=client,
            )
            existing_wiki = WikiPage()
            existing_wiki = existing_wiki.fill_from_dict(
                synapse_wiki=existing_wiki_dict
            )
            # Update existing_wiki with current object's attributes if they are not None
            updated_wiki = merge_dataclass_entities(
                source=existing_wiki,
                destination=self,
                fields_to_ignore=[
                    "modified_on",
                    "modified_by",
                ],
            )
            wiki_data = await put_wiki_page(
                owner_id=self.owner_id,
                wiki_id=self.id,
                request=updated_wiki.to_synapse_request(),
                synapse_client=client,
            )
            client.logger.info(
                f"[{self.owner_id}]: Updated wiki page: {wiki_data.get('title')} "
                f"with ID: {wiki_data.get('id')}."
            )

        else:
            client.logger.info(
                f"[{self.owner_id}]: Creating sub-wiki page under parent ID: "
                f"{self.parent_id}"
            )
            wiki_data = await post_wiki_page(
                owner_id=self.owner_id,
                request=self.to_synapse_request(),
                synapse_client=client,
            )
            client.logger.info(
                f"[{self.owner_id}]: Created sub-wiki page: {wiki_data.get('title')} "
                f"with ID: {wiki_data.get('id')} under parent: {self.parent_id}"
            )
        self.fill_from_dict(wiki_data)
        return self

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Restore version: {self.wiki_version} for wiki page: {self.id}"
    )
    async def restore_async(
        self,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> "WikiPage":
        """Restore a specific version of a wiki page.

        Arguments:
            synapse_client: If not passed in and caching was not disabled by
                    `Synapse.allow_client_caching(False)` this will use the last created
                    instance from the Synapse class constructor.

        Returns:
            The restored wiki page.

        Example: Restore a specific version of a wiki page
            This example shows how to restore a specific version of a wiki page.
            ```python
            wiki_page_restored = await WikiPage(owner_id=project.id, id=wiki_page.id, wiki_version="0").restore_async()
            print(wiki_page_restored)
            ```
        """
        if not self.owner_id:
            raise ValueError("Must provide owner_id to restore a wiki page.")
        if not self.id:
            raise ValueError("Must provide id to restore a wiki page.")
        if not self.wiki_version:
            raise ValueError("Must provide wiki_version to restore a wiki page.")

        wiki_data = await put_wiki_version(
            owner_id=self.owner_id,
            wiki_id=self.id,
            wiki_version=self.wiki_version,
            request=self.to_synapse_request(),
            synapse_client=synapse_client,
        )
        self.fill_from_dict(wiki_data)
        return self

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Get_Wiki_Page: {self.owner_id}"
    )
    async def get_async(
        self,
        *,
        synapse_client: Optional[Synapse] = None,
    ) -> "WikiPage":
        """Get a wiki page from Synapse.

        Arguments:
            synapse_client: If not passed in and caching was not disabled by
                    `Synapse.allow_client_caching(False)` this will use the last created
                    instance from the Synapse class constructor.

        Returns:
            The wiki page.

        Raises:
            ValueError: If owner_id is not provided.

        Example: Get a wiki page from Synapse
            This example shows how to get a wiki page from Synapse.
            ```python
            wiki_page = await WikiPage(owner_id=project.id, id=wiki_page.id).get_async()
            print(wiki_page)
            ```
        """
        if not self.owner_id:
            raise ValueError("Must provide owner_id to get a wiki page.")
        if not self.id and not self.title:
            raise ValueError("Must provide id or title to get a wiki page.")

        if self.id is None:
            async for result in get_wiki_header_tree(
                owner_id=self.owner_id,
                synapse_client=synapse_client,
            ):
                if result.get("title") == self.title:
                    matching_header = result
                    break
                else:
                    matching_header = None

            if not matching_header:
                raise ValueError(f"No wiki page found with title: {self.title}")
            self.id = matching_header["id"]

        wiki_data = await get_wiki_page(
            owner_id=self.owner_id,
            wiki_id=self.id,
            wiki_version=self.wiki_version,
            synapse_client=synapse_client,
        )
        self.fill_from_dict(wiki_data)
        return self

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Delete_Wiki_Page: Owner ID {self.owner_id}, Wiki ID {self.id}"
    )
    async def delete_async(
        self,
        *,
        synapse_client: Optional["Synapse"] = None,
    ) -> None:
        """
        Delete this wiki page.

        Arguments:
            synapse_client: Optionally provide a Synapse client.
        Raises:
            ValueError: If required fields are missing.

        Example: Delete a wiki page
            This example shows how to delete a wiki page.
            ```python
            wiki_page = await WikiPage(owner_id=project.id, id=wiki_page.id).delete_async()
            print(f"Wiki page {wiki_page.title} deleted successfully.")
            ```
        """
        if not self.owner_id:
            raise ValueError("Must provide owner_id to delete a wiki page.")
        if not self.id:
            raise ValueError("Must provide id to delete a wiki page.")

        await delete_wiki_page(
            owner_id=self.owner_id,
            wiki_id=self.id,
            synapse_client=synapse_client,
        )

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Get_Attachment_Handles: Owner ID {self.owner_id}, Wiki ID {self.id}, Wiki Version {self.wiki_version}"
    )
    async def get_attachment_handles_async(
        self,
        *,
        synapse_client: Optional["Synapse"] = None,
    ) -> List[Dict[str, Any]]:
        """
        Get the file handles of all attachments on this wiki page.

        Arguments:
            synapse_client: Optionally provide a Synapse client.
        Returns:
            The list of FileHandles for all file attachments of this WikiPage.
        Raises:
            ValueError: If owner_id or id is not provided.

        Example: Get the file handles of all attachments on a wiki page
            This example shows how to get the file handles of all attachments on a wiki page.
            ```python
            attachment_handles = await WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_handles_async()
            print(f"Attachment handles: {attachment_handles['list']}")
            ```
        """
        if not self.owner_id:
            raise ValueError("Must provide owner_id to get attachment handles.")
        if not self.id:
            raise ValueError("Must provide id to get attachment handles.")

        return await get_attachment_handles(
            owner_id=self.owner_id,
            wiki_id=self.id,
            wiki_version=self.wiki_version,
            synapse_client=synapse_client,
        )

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Get_Attachment_URL: Owner ID {self.owner_id}, Wiki ID {self.id}, File Name {kwargs['file_name']}"
    )
    async def get_attachment_async(
        self,
        *,
        file_name: str,
        download_file: bool = True,
        download_location: Optional[str] = None,
        synapse_client: Optional["Synapse"] = None,
    ) -> Union[str, None]:
        """
        Download the wiki page attachment to a local file or return the URL.

        Arguments:
            file_name: The name of the file to get. The file name can be in either non-gzipped or gzipped format.
            download_file: Whether associated files should be downloaded. Default is True.
            download_location: The directory to download the file to. Required if download_file is True.
            synapse_client: Optionally provide a Synapse client.
        Returns:
            If download_file is True, the attachment file will be downloaded to the download_location. Otherwise, the URL will be returned.
        Raises:
            ValueError: If owner_id or id is not provided.

        Example: Get the attachment URL for a wiki page
            This example shows how to get the attachment file or URL for a wiki page.
            ```python
            attachment_file_or_url = await WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_async(file_name="attachment.txt", download_file=False)
            print(f"Attachment URL: {attachment_file_or_url}")
            ```
        Example: Download the attachment file for a wiki page
            This example shows how to download the attachment file for a wiki page.
            ```python
            attachment_file_path = await WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_async(file_name="attachment.txt", download_file=True, download_location="~/temp")
            print(f"Attachment file path: {attachment_file_path}")
            ```
        """
        if not self.owner_id:
            raise ValueError("Must provide owner_id to get attachment URL.")
        if not self.id:
            raise ValueError("Must provide id to get attachment URL.")
        if not file_name:
            raise ValueError("Must provide file_name to get attachment URL.")

        client = Synapse.get_client(synapse_client=synapse_client)

        if WikiPage._should_gzip_file(file_name):
            file_name = f"{file_name}.gz"
        attachment_url = await get_attachment_url(
            owner_id=self.owner_id,
            wiki_id=self.id,
            file_name=file_name,
            wiki_version=self.wiki_version,
            synapse_client=client,
        )

        if download_file:
            if not download_location:
                raise ValueError("Must provide download_location to download a file.")

            presigned_url_info = PresignedUrlInfo(
                url=attachment_url,
                file_name=file_name,
                expiration_utc=_pre_signed_url_expiration_time(attachment_url),
            )
            filehandle_dict = await get_attachment_handles(
                owner_id=self.owner_id,
                wiki_id=self.id,
                wiki_version=self.wiki_version,
                synapse_client=client,
            )
            file_size = int(WikiPage._get_file_size(filehandle_dict, file_name))
            if file_size < SINGLE_THREAD_DOWNLOAD_SIZE_LIMIT:
                # download_from_url is synchronous, run it in a worker thread so that
                # the blocking HTTP request does not stall the asyncio event loop
                # TODO: SYNPY-1903 - replace with the async download_from_url once
                # it is available and drop the worker thread
                loop = asyncio.get_running_loop()
                downloaded_file_path = await loop.run_in_executor(
                    client._get_thread_pool_executor(asyncio_event_loop=loop),
                    lambda: download_from_url(
                        url=presigned_url_info.url,
                        destination=download_location,
                        url_is_presigned=True,
                        synapse_client=client,
                    ),
                )
            else:
                downloaded_file_path = await download_from_url_multi_threaded(
                    presigned_url=presigned_url_info,
                    destination=download_location,
                    synapse_client=client,
                )
            unzipped_file_path = WikiPage.unzip_gzipped_file(downloaded_file_path)
            client.logger.info(
                f"[{self.owner_id}:{self.id}]: Downloaded file "
                f"{presigned_url_info.file_name.replace('.gz', '')} to "
                f"{unzipped_file_path}."
            )
            os.remove(downloaded_file_path)
            client.logger.debug(
                f"[{self.owner_id}:{self.id}]: Removed the gzipped file "
                f"{downloaded_file_path}."
            )
            return unzipped_file_path
        else:
            return attachment_url

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Get_Attachment_Preview_URL: Owner ID {self.owner_id}, Wiki ID {self.id}, File Name {kwargs['file_name']}"
    )
    async def get_attachment_preview_async(
        self,
        file_name: str,
        *,
        download_file: bool = True,
        download_location: Optional[str] = None,
        synapse_client: Optional["Synapse"] = None,
    ) -> Union[str, None]:
        """
        Download the wiki page attachment preview to a local file or return the URL.

        Arguments:
            file_name: The name of the file to get. The file name can be in either non-gzipped or gzipped format.
            download_file: Whether associated files should be downloaded. Default is True.
            download_location: The directory to download the file to. Required if download_file is True.
            synapse_client: Optionally provide a Synapse client.
        Returns:
            If download_file is True, the attachment preview file will be downloaded to the download_location. Otherwise, the URL will be returned.
        Raises:
            ValueError: If owner_id or id is not provided.

        Example: Get the attachment preview URL for a wiki page
            This example shows how to get the attachment preview URL for a wiki page.
            Instead of using the file_name from the attachmenthandle response when isPreview=True, you should use the original file name in the get_attachment_preview request.
            The downloaded file will still be named according to the file_name provided in the response when isPreview=True.
            ```python
            attachment_preview_url = await WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_preview_async(file_name="attachment.txt.gz", download_file=False)
            print(f"Attachment preview URL: {attachment_preview_url}")
            ```
        Example: Download the attachment preview file for a wiki page
            This example shows how to download the attachment preview file for a wiki page.
            ```python
            attachment_preview_file_path = WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_preview(file_name="attachment.txt.gz", download_file=True, download_location="~/temp")
            print(f"Attachment preview file path: {attachment_preview_file_path}")
            ```
        """
        if not self.owner_id:
            raise ValueError("Must provide owner_id to get attachment preview URL.")
        if not self.id:
            raise ValueError("Must provide id to get attachment preview URL.")
        if not file_name:
            raise ValueError("Must provide file_name to get attachment preview URL.")

        client = Synapse.get_client(synapse_client=synapse_client)
        # check if the file_name is in gzip format or image format
        if not file_name.endswith(".gz"):
            file_name = f"{file_name}.gz"
        attachment_preview_url = await get_attachment_preview_url(
            owner_id=self.owner_id,
            wiki_id=self.id,
            file_name=file_name,
            wiki_version=self.wiki_version,
            synapse_client=client,
        )
        if download_file:
            if not download_location:
                raise ValueError("Must provide download_location to download a file.")

            presigned_url_info = PresignedUrlInfo(
                url=attachment_preview_url,
                file_name=file_name,
                expiration_utc=_pre_signed_url_expiration_time(attachment_preview_url),
            )

            filehandle_dict = await get_attachment_handles(
                owner_id=self.owner_id,
                wiki_id=self.id,
                wiki_version=self.wiki_version,
                synapse_client=client,
            )
            file_size = int(WikiPage._get_file_size(filehandle_dict, file_name))
            if file_size < SINGLE_THREAD_DOWNLOAD_SIZE_LIMIT:
                # download_from_url is synchronous, run it in a worker thread so that
                # the blocking HTTP request does not stall the asyncio event loop
                # TODO: SYNPY-1903 - replace with the async download_from_url once
                # it is available and drop the worker thread
                loop = asyncio.get_running_loop()
                downloaded_file_path = await loop.run_in_executor(
                    client._get_thread_pool_executor(asyncio_event_loop=loop),
                    lambda: download_from_url(
                        url=presigned_url_info.url,
                        destination=download_location,
                        url_is_presigned=True,
                        synapse_client=client,
                    ),
                )
            else:
                downloaded_file_path = await download_from_url_multi_threaded(
                    presigned_url=presigned_url_info,
                    destination=download_location,
                    synapse_client=client,
                )
            client.logger.info(
                f"[{self.owner_id}:{self.id}]: Downloaded the preview file "
                f"{presigned_url_info.file_name.replace('.gz', '')} to "
                f"{downloaded_file_path}."
            )
            return downloaded_file_path
        else:
            return attachment_preview_url

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Get_Markdown_URL: Owner ID {self.owner_id}, Wiki ID {self.id}, Wiki Version {self.wiki_version}"
    )
    async def get_markdown_file_async(
        self,
        *,
        download_file: bool = True,
        download_location: Optional[str] = None,
        synapse_client: Optional["Synapse"] = None,
    ) -> Union[str, None]:
        """
        Get the markdown URL of this wiki page. --> modify this to print the markdown file

        Arguments:
            download_file: Whether associated files should be downloaded. Default is True.
            download_location: The directory to download the file to. Required if download_file is True.
            synapse_client: Optionally provide a Synapse client.
        Returns:
            If download_file is True, the markdown file will be downloaded to the download_location. Otherwise, the URL will be returned.
        Raises:
            ValueError: If owner_id or id is not provided.

        Example: Get the markdown URL for a wiki page
            This example shows how to get the markdown URL for a wiki page.
            ```python
            markdown_url = await WikiPage(owner_id=project.id, id=wiki_page.id).get_markdown_file_async(download_file=False)
            print(f"Markdown URL: {markdown_url}")
            ```
        Example: Download the markdown file for a wiki page
            This example shows how to download the markdown file for a wiki page.
            ```python
            markdown_file_path = await WikiPage(owner_id=project.id, id=wiki_page.id).get_markdown_file_async(download_file=True, download_location="~/temp")
            print(f"Markdown file path: {markdown_file_path}")
            ```
        """
        if not self.owner_id:
            raise ValueError("Must provide owner_id to get markdown URL.")
        if not self.id:
            raise ValueError("Must provide id to get markdown URL.")

        client = Synapse.get_client(synapse_client=synapse_client)
        markdown_url = await get_markdown_url(
            owner_id=self.owner_id,
            wiki_id=self.id,
            wiki_version=self.wiki_version,
            synapse_client=client,
        )
        if download_file:
            if not download_location:
                raise ValueError("Must provide download_location to download a file.")

            # download_from_url is synchronous, run it in a worker thread so that the
            # blocking HTTP request does not stall the asyncio event loop
            # TODO: SYNPY-1903 - replace with the async download_from_url once it is
            # available and drop the worker thread
            loop = asyncio.get_running_loop()
            downloaded_file_path = await loop.run_in_executor(
                client._get_thread_pool_executor(asyncio_event_loop=loop),
                lambda: download_from_url(
                    url=markdown_url,
                    destination=download_location,
                    url_is_presigned=True,
                    synapse_client=client,
                ),
            )
            unzipped_file_path = WikiPage.unzip_gzipped_file(downloaded_file_path)
            client.logger.info(
                f"[{self.owner_id}:{self.id}]: Downloaded and unzipped the markdown "
                f"file to {unzipped_file_path}."
            )
            os.remove(downloaded_file_path)
            client.logger.debug(
                f"[{self.owner_id}:{self.id}]: Removed the gzipped file "
                f"{downloaded_file_path}."
            )
            return unzipped_file_path
        else:
            return markdown_url

    async def _get_markdown_text(self, synapse_client: Synapse) -> str:
        """Download the markdown of this wiki page and return it as text.

        Arguments:
            synapse_client: The Synapse client to use for the download.

        Returns:
            The markdown content of this wiki page as a string.
        """
        markdown_url = await get_markdown_url(
            owner_id=self.owner_id,
            wiki_id=self.id,
            wiki_version=self.wiki_version,
            synapse_client=synapse_client,
        )
        cache_dir = os.path.join(synapse_client.cache.cache_root_dir, "wiki_content")
        if not os.path.exists(cache_dir):
            os.makedirs(cache_dir)
        # download_from_url is synchronous, run it in a worker thread so that the
        # blocking HTTP request does not stall the asyncio event loop
        # TODO: SYNPY-1903 - replace with the async download_from_url once it is
        # available and drop the worker thread
        loop = asyncio.get_running_loop()
        downloaded_file_path = await loop.run_in_executor(
            synapse_client._get_thread_pool_executor(asyncio_event_loop=loop),
            lambda: download_from_url(
                url=markdown_url,
                destination=cache_dir,
                url_is_presigned=True,
                synapse_client=synapse_client,
            ),
        )
        try:
            with gzip.open(downloaded_file_path, "rt", encoding="utf-8") as f_in:
                return f_in.read()
        finally:
            os.remove(downloaded_file_path)

    async def _copy_attachment_file_handles(self, synapse_client: Synapse) -> list[str]:
        """Copy the attachment file handles of this wiki page.

        Arguments:
            synapse_client: The Synapse client to use for the copy.

        Returns:
            The IDs of the newly copied file handles.

        Raises:
            ValueError: If any file handle copy fails.
        """
        if not self.attachment_file_handle_ids:
            return []

        attachment_handles = await self.get_attachment_handles_async(
            synapse_client=synapse_client
        )
        # Get rid of the previews
        no_previews = [
            file_handle
            for file_handle in attachment_handles.get("list", [])
            if not file_handle.get("isPreview")
        ]
        if not no_previews:
            return []

        copy_requests = [
            {
                "originalFile": {
                    "fileHandleId": file_handle["id"],
                    "associateObjectId": self.id,
                    "associateObjectType": "WikiAttachment",
                },
                "newContentType": file_handle.get("contentType"),
                "newFileName": file_handle.get("fileName"),
            }
            for file_handle in no_previews
        ]
        copy_results = await post_file_handles_copy(
            copy_requests=copy_requests,
            synapse_client=synapse_client,
        )
        for copy_result in copy_results:
            if copy_result.get("failureCode") is not None:
                raise ValueError(
                    f"{copy_result['failureCode']} dataFileHandleId: "
                    f"{copy_result['originalFileHandleId']}"
                )
        return [copy_result["newFileHandle"]["id"] for copy_result in copy_results]

    @otel_trace_method(
        method_to_trace_name=lambda self, **kwargs: f"Copy_Wiki: Owner ID {self.owner_id}, Wiki ID {self.id}"
    )
    async def copy_async(
        self,
        destination_owner_id: str,
        destination_sub_page_id: str | None = None,
        update_links: bool = True,
        entity_map: dict[str, str] | None = None,
        *,
        synapse_client: Synapse | None = None,
    ) -> list["WikiHeader"]:
        """Copy the wiki page tree of the owner entity to another entity and
        update internal links.

        If id is set on this WikiPage, only the sub-tree rooted at that wiki page
        is copied. Otherwise the entire wiki of the owner entity is copied.

        Arguments:
            destination_owner_id: The Synapse ID of the entity that the wiki
                will be copied to.
            destination_sub_page_id: Optional ID of a wiki page that already
                exists in the destination. The root of the copied tree is written
                into that page, replacing its title, markdown, and attachments,
                and the rest of the copied pages are created beneath it.
                Required when the destination entity already has a root wiki
                page.
            update_links: Update all the internal links so that they point at the
                copied wiki pages. For example, syn1234/wiki/34345 becomes
                syn3345/wiki/49508. Defaults to True.
            entity_map: A mapping of old Synapse IDs to new Synapse IDs, for
                example {"syn1234": "syn2345"}. If provided, the Synapse IDs
                referenced in the markdown of the copied wiki pages are updated,
                for example syn1234 becomes syn2345. If omitted, Synapse IDs
                are left unchanged.
            synapse_client: If not passed in and caching was not disabled by
                    Synapse.allow_client_caching(False) this will use the last created
                    instance from the Synapse class constructor.

        Returns:
            A list of WikiHeader objects for the destination entity.

        Raises:
            ValueError: If owner_id is not provided or is not a Synapse ID,
                if destination_owner_id is not a Synapse ID, if a key or
                value of entity_map is not
                a Synapse ID, if id is set but no wiki page with that ID
                exists in the owner entity, if destination_sub_page_id does
                not exist in the destination entity, if the destination
                entity already has a root wiki page and
                destination_sub_page_id is not provided, or if copying an
                attachment file handle fails.

        Example: Copy the entire wiki of an entity to another entity
            This example shows how to copy all wiki pages from one project to another.
            ```python
            from synapseclient import Synapse
            from synapseclient.models import WikiPage

            syn = Synapse()
            syn.login()

            new_wiki_headers = await WikiPage(owner_id="syn123").copy_async(
                destination_owner_id="syn456"
            )
            print(new_wiki_headers)
            ```
        Example: Copy a wiki sub-tree and update Synapse ID references
            This example shows how to copy a specific wiki page and its sub-pages,
            rewriting references to syn1234 so they point at syn2345.
            ```python
            new_wiki_headers = await WikiPage(owner_id="syn123", id="34345").copy_async(
                destination_owner_id="syn456",
                entity_map={"syn1234": "syn2345"},
            )
            print(new_wiki_headers)
            ```
        """
        entity_sub_page_id, destination_sub_page_id = _validate_and_format_copy_inputs(
            owner_id=self.owner_id,
            destination_owner_id=destination_owner_id,
            entity_sub_page_id=self.id,
            destination_sub_page_id=destination_sub_page_id,
            entity_map=entity_map,
        )

        client = Synapse.get_client(synapse_client=synapse_client)

        # Getting the wiki header tree fails when there is no wiki
        old_wiki_headers = []
        try:
            async for item in get_wiki_header_tree(
                owner_id=self.owner_id,
                synapse_client=client,
            ):
                old_wiki_headers.append(item)
        except SynapseHTTPError as e:
            if e.response.status_code == 404:
                if entity_sub_page_id:
                    raise ValueError(
                        f"The wiki page {entity_sub_page_id} does not exist "
                        f"in the owner entity {self.owner_id}."
                    ) from e
                return []
            raise

        if destination_sub_page_id:
            destination_wiki_page = await _get_existing_destination_wiki_page(
                destination_owner_id=destination_owner_id,
                destination_sub_page_id=destination_sub_page_id,
                synapse_client=client,
            )
        else:
            await _ensure_destination_has_no_root_wiki(
                destination_owner_id=destination_owner_id,
                synapse_client=client,
            )
            destination_wiki_page = None

        if entity_sub_page_id:
            all_wiki_headers = old_wiki_headers
            old_wiki_headers = _collect_wiki_sub_tree_headers(
                wiki_headers=all_wiki_headers,
                sub_page_id=entity_sub_page_id,
            )
            if not old_wiki_headers:
                raise ValueError(
                    f"The wiki page {entity_sub_page_id} does not exist "
                    f"in the owner entity {self.owner_id}."
                )
            collected_ids = {header["id"] for header in old_wiki_headers}
            ignored_ids = [
                header["id"]
                for header in all_wiki_headers
                if header["id"] not in collected_ids
            ]
            if ignored_ids:
                client.logger.debug(
                    f"[{self.owner_id}]: Not copying {len(ignored_ids)} wiki page(s) "
                    f"outside the sub-tree rooted at {entity_sub_page_id}: "
                    f"{ignored_ids}"
                )

        if not old_wiki_headers:
            return []

        new_wikis, wiki_id_map = await _copy_wiki_pages(
            old_wiki_headers=old_wiki_headers,
            source_owner_id=self.owner_id,
            destination_owner_id=destination_owner_id,
            destination_wiki_page=destination_wiki_page,
            destination_sub_page_id=destination_sub_page_id,
            synapse_client=client,
        )

        if update_links:
            client.logger.debug(
                f"[{self.owner_id} -> {destination_owner_id}]: Updating internal links"
            )
            new_wikis = _update_internal_links(
                new_wikis=new_wikis,
                wiki_id_map=wiki_id_map,
                source_owner_id=self.owner_id,
                destination_owner_id=destination_owner_id,
            )
            client.logger.debug(
                f"[{self.owner_id} -> {destination_owner_id}]: Done updating internal "
                "links."
            )

        if entity_map:
            client.logger.debug(
                f"[{self.owner_id} -> {destination_owner_id}]: Updating Synapse "
                "references"
            )
            new_wikis = _update_synapse_id_references(
                new_wikis=new_wikis,
                wiki_id_map=wiki_id_map,
                entity_map=entity_map,
            )
            client.logger.debug(
                f"[{self.owner_id} -> {destination_owner_id}]: Done updating Synapse "
                "IDs."
            )

        if update_links or entity_map:
            client.logger.debug(
                f"[{self.owner_id} -> {destination_owner_id}]: Storing new wiki pages"
            )
            for new_wiki_id in wiki_id_map.values():
                new_wiki = new_wikis[new_wiki_id]
                new_wiki = await new_wiki._get_markdown_file_handle(
                    synapse_client=client
                )
                wiki_data = await put_wiki_page(
                    owner_id=destination_owner_id,
                    wiki_id=new_wiki_id,
                    request=new_wiki.to_synapse_request(),
                    synapse_client=client,
                )
                new_wikis[new_wiki_id] = new_wiki.fill_from_dict(synapse_wiki=wiki_data)
                client.logger.debug(
                    f"[{destination_owner_id}:{new_wiki_id}]: Stored wiki page"
                )

        new_wiki_headers = []
        async for item in get_wiki_header_tree(
            owner_id=destination_owner_id,
            synapse_client=client,
        ):
            new_wiki_headers.append(WikiHeader().fill_from_dict(wiki_header=item))
        return new_wiki_headers
Attributes
id class-attribute instance-attribute
id: Optional[str] = None

The unique identifier for this wiki page.

etag class-attribute instance-attribute
etag: Optional[str] = field(default=None, compare=False)

The etag of this object. Synapse employs an Optimistic Concurrency Control (OCC) scheme to handle concurrent updates. Since the E-Tag changes every time an entity is updated it is used to detect when a client's current representation of an entity is out-of-date.

title class-attribute instance-attribute
title: Optional[str] = None

The title of this page.

parent_id class-attribute instance-attribute
parent_id: Optional[str] = None

When set, the WikiPage is a sub-page of the indicated parent WikiPage.

markdown class-attribute instance-attribute
markdown: Optional[str] = None

The markdown content of this page.

attachments class-attribute instance-attribute
attachments: List[Dict[str, Any]] = field(default_factory=list)

A list of file paths sassociated with this page.

owner_id class-attribute instance-attribute
owner_id: Optional[str] = None

The Synapse ID of the owning object (e.g., entity, evaluation, etc.).

created_on class-attribute instance-attribute
created_on: Optional[str] = field(default=None, compare=False)

The timestamp when this page was created.

created_by class-attribute instance-attribute
created_by: Optional[str] = field(default=None, compare=False)

The ID of the user that created this page.

modified_on class-attribute instance-attribute
modified_on: Optional[str] = field(default=None, compare=False)

The timestamp when this page was last modified.

modified_by class-attribute instance-attribute
modified_by: Optional[str] = field(default=None, compare=False)

The ID of the user that last modified this page.

wiki_version class-attribute instance-attribute
wiki_version: Optional[str] = None

The version number of this wiki page.

markdown_file_handle_id class-attribute instance-attribute
markdown_file_handle_id: Optional[str] = None

The ID of the file handle containing the markdown content.

attachment_file_handle_ids class-attribute instance-attribute
attachment_file_handle_ids: List[str] = field(default_factory=list)

The list of attachment file handle ids of this page.

Methods:
unzip_gzipped_file staticmethod
unzip_gzipped_file(file_path: str) -> str

Unzip the gzipped file and return the file path to the unzipped file. If the file is a markdown file, the content will be printed.

PARAMETER DESCRIPTION
file_path

The path to the gzipped file.

TYPE: str

Returns: The file path to the unzipped file.

Unzip a gzipped file
file_path = "path/to/file.md.gz"
unzipped_file_path = WikiPage.unzip_gzipped_file(file_path)
Source code in synapseclient/models/wiki.py
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
@staticmethod
def unzip_gzipped_file(file_path: str) -> str:
    """Unzip the gzipped file and return the file path to the unzipped file.
    If the file is a markdown file, the content will be printed.

    Arguments:
        file_path: The path to the gzipped file.
    Returns:
        The file path to the unzipped file.

    Example: Unzip a gzipped file
        ```python
        file_path = "path/to/file.md.gz"
        unzipped_file_path = WikiPage.unzip_gzipped_file(file_path)
        ```
    """
    with gzip.open(file_path, "rb") as f_in:
        unzipped_content_bytes = f_in.read()

        is_text_file = False
        unzipped_content_text = None
        try:
            unzipped_content_text = unzipped_content_bytes.decode("utf-8")
            is_text_file = True
            if file_path.endswith(".md.gz"):
                pprint.pp(unzipped_content_text)
        except UnicodeDecodeError:
            # It's a binary file, keep as bytes
            pass

        unzipped_file_path = os.path.join(
            os.path.dirname(file_path),
            os.path.basename(file_path).replace(".gz", ""),
        )
        if is_text_file:
            with open(unzipped_file_path, "wt", encoding="utf-8") as f_out:
                f_out.write(unzipped_content_text)
        else:
            with open(unzipped_file_path, "wb") as f_out:
                f_out.write(unzipped_content_bytes)

        return unzipped_file_path
reformat_attachment_file_name staticmethod
reformat_attachment_file_name(attachment_file_name: str) -> str

Reformat the attachment file name to be a valid attachment path.

PARAMETER DESCRIPTION
attachment_file_name

The name of the attachment file.

TYPE: str

Returns: The reformatted attachment file name.

Reformat the attachment file name
attachment_file_name = "file.txt"
attachment_file_name_reformatted = WikiPage.reformat_attachment_file_name(attachment_file_name)
print(f"Reformatted attachment file name: {attachment_file_name_reformatted}")
Source code in synapseclient/models/wiki.py
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
@staticmethod
def reformat_attachment_file_name(attachment_file_name: str) -> str:
    """Reformat the attachment file name to be a valid attachment path.

    Arguments:
        attachment_file_name: The name of the attachment file.
    Returns:
        The reformatted attachment file name.

    Example: Reformat the attachment file name
        ```python
        attachment_file_name = "file.txt"
        attachment_file_name_reformatted = WikiPage.reformat_attachment_file_name(attachment_file_name)
        print(f"Reformatted attachment file name: {attachment_file_name_reformatted}")
        ```
    """
    attachment_file_name_reformatted = attachment_file_name.replace(".", "%2E")
    attachment_file_name_reformatted = attachment_file_name_reformatted.replace(
        "_", "%5F"
    )
    return attachment_file_name_reformatted
store_async async
store_async(*, synapse_client: Optional[Synapse] = None) -> WikiPage

Store the wiki page. If there is no wiki page, a new wiki page will be created. If the wiki page already exists, it will be updated. Subwiki pages are created by passing in a parent_id. If a parent_id is provided, the wiki page will be created as a subwiki page.

PARAMETER DESCRIPTION
synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
WikiPage

The created/updated wiki page.

RAISES DESCRIPTION
ValueError

If owner_id is not provided or if required fields are missing.

Store a wiki page

This example shows how to store a wiki page.

from synapseclient import Synapse
from synapseclient.models import (
    Project,
    WikiPage,
)
syn = Synapse()
syn.login()
project = await Project(name="My uniquely named project about Alzheimer's Disease").get_async()
wiki_page = await WikiPage(owner_id=project.id, title="My wiki page").store_async()
print(wiki_page)

Source code in synapseclient/models/wiki.py
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"Store the wiki page: {self.owner_id}"
)
async def store_async(
    self,
    *,
    synapse_client: Optional[Synapse] = None,
) -> "WikiPage":
    """Store the wiki page. If there is no wiki page, a new wiki page will be created.
    If the wiki page already exists, it will be updated.
    Subwiki pages are created by passing in a parent_id.
    If a parent_id is provided, the wiki page will be created as a subwiki page.

    Arguments:
        synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

    Returns:
        The created/updated wiki page.

    Raises:
        ValueError: If owner_id is not provided or if required fields are missing.

    Example: Store a wiki page
        This example shows how to store a wiki page.
        ```python
        from synapseclient import Synapse
        from synapseclient.models import (
            Project,
            WikiPage,
        )
        syn = Synapse()
        syn.login()
        project = await Project(name="My uniquely named project about Alzheimer's Disease").get_async()
        wiki_page = await WikiPage(owner_id=project.id, title="My wiki page").store_async()
        print(wiki_page)
        ```
    """
    client = Synapse.get_client(synapse_client=synapse_client)

    wiki_action = await self._determine_wiki_action(synapse_client=client)
    # get the markdown file handle and attachment file handles if the wiki action is valid
    if wiki_action:
        # Update self with the returned WikiPage objects that have file handle IDs set
        self = await self._get_markdown_file_handle(synapse_client=client)
        self = await self._get_attachment_file_handles(synapse_client=client)

    if wiki_action == "create_root_wiki_page":
        client.logger.info(
            f"[{self.owner_id}]: No wiki page exists within the owner. "
            "Create a new wiki page."
        )
        wiki_data = await post_wiki_page(
            owner_id=self.owner_id,
            request=self.to_synapse_request(),
            synapse_client=client,
        )
        client.logger.info(
            f"[{self.owner_id}]: Created wiki page: {wiki_data.get('title')} "
            f"with ID: {wiki_data.get('id')}."
        )
    elif wiki_action == "update_existing_wiki_page":
        client.logger.info(
            f"[{self.owner_id}:{self.id}]: A wiki page already exists within the "
            "owner. Update the existing wiki page."
        )
        existing_wiki_dict = await get_wiki_page(
            owner_id=self.owner_id,
            wiki_id=self.id,
            wiki_version=self.wiki_version,
            synapse_client=client,
        )
        existing_wiki = WikiPage()
        existing_wiki = existing_wiki.fill_from_dict(
            synapse_wiki=existing_wiki_dict
        )
        # Update existing_wiki with current object's attributes if they are not None
        updated_wiki = merge_dataclass_entities(
            source=existing_wiki,
            destination=self,
            fields_to_ignore=[
                "modified_on",
                "modified_by",
            ],
        )
        wiki_data = await put_wiki_page(
            owner_id=self.owner_id,
            wiki_id=self.id,
            request=updated_wiki.to_synapse_request(),
            synapse_client=client,
        )
        client.logger.info(
            f"[{self.owner_id}]: Updated wiki page: {wiki_data.get('title')} "
            f"with ID: {wiki_data.get('id')}."
        )

    else:
        client.logger.info(
            f"[{self.owner_id}]: Creating sub-wiki page under parent ID: "
            f"{self.parent_id}"
        )
        wiki_data = await post_wiki_page(
            owner_id=self.owner_id,
            request=self.to_synapse_request(),
            synapse_client=client,
        )
        client.logger.info(
            f"[{self.owner_id}]: Created sub-wiki page: {wiki_data.get('title')} "
            f"with ID: {wiki_data.get('id')} under parent: {self.parent_id}"
        )
    self.fill_from_dict(wiki_data)
    return self
restore_async async
restore_async(*, synapse_client: Optional[Synapse] = None) -> WikiPage

Restore a specific version of a wiki page.

PARAMETER DESCRIPTION
synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
WikiPage

The restored wiki page.

Restore a specific version of a wiki page

This example shows how to restore a specific version of a wiki page.

wiki_page_restored = await WikiPage(owner_id=project.id, id=wiki_page.id, wiki_version="0").restore_async()
print(wiki_page_restored)

Source code in synapseclient/models/wiki.py
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"Restore version: {self.wiki_version} for wiki page: {self.id}"
)
async def restore_async(
    self,
    *,
    synapse_client: Optional[Synapse] = None,
) -> "WikiPage":
    """Restore a specific version of a wiki page.

    Arguments:
        synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

    Returns:
        The restored wiki page.

    Example: Restore a specific version of a wiki page
        This example shows how to restore a specific version of a wiki page.
        ```python
        wiki_page_restored = await WikiPage(owner_id=project.id, id=wiki_page.id, wiki_version="0").restore_async()
        print(wiki_page_restored)
        ```
    """
    if not self.owner_id:
        raise ValueError("Must provide owner_id to restore a wiki page.")
    if not self.id:
        raise ValueError("Must provide id to restore a wiki page.")
    if not self.wiki_version:
        raise ValueError("Must provide wiki_version to restore a wiki page.")

    wiki_data = await put_wiki_version(
        owner_id=self.owner_id,
        wiki_id=self.id,
        wiki_version=self.wiki_version,
        request=self.to_synapse_request(),
        synapse_client=synapse_client,
    )
    self.fill_from_dict(wiki_data)
    return self
get_async async
get_async(*, synapse_client: Optional[Synapse] = None) -> WikiPage

Get a wiki page from Synapse.

PARAMETER DESCRIPTION
synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Optional[Synapse] DEFAULT: None

RETURNS DESCRIPTION
WikiPage

The wiki page.

RAISES DESCRIPTION
ValueError

If owner_id is not provided.

Get a wiki page from Synapse

This example shows how to get a wiki page from Synapse.

wiki_page = await WikiPage(owner_id=project.id, id=wiki_page.id).get_async()
print(wiki_page)

Source code in synapseclient/models/wiki.py
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"Get_Wiki_Page: {self.owner_id}"
)
async def get_async(
    self,
    *,
    synapse_client: Optional[Synapse] = None,
) -> "WikiPage":
    """Get a wiki page from Synapse.

    Arguments:
        synapse_client: If not passed in and caching was not disabled by
                `Synapse.allow_client_caching(False)` this will use the last created
                instance from the Synapse class constructor.

    Returns:
        The wiki page.

    Raises:
        ValueError: If owner_id is not provided.

    Example: Get a wiki page from Synapse
        This example shows how to get a wiki page from Synapse.
        ```python
        wiki_page = await WikiPage(owner_id=project.id, id=wiki_page.id).get_async()
        print(wiki_page)
        ```
    """
    if not self.owner_id:
        raise ValueError("Must provide owner_id to get a wiki page.")
    if not self.id and not self.title:
        raise ValueError("Must provide id or title to get a wiki page.")

    if self.id is None:
        async for result in get_wiki_header_tree(
            owner_id=self.owner_id,
            synapse_client=synapse_client,
        ):
            if result.get("title") == self.title:
                matching_header = result
                break
            else:
                matching_header = None

        if not matching_header:
            raise ValueError(f"No wiki page found with title: {self.title}")
        self.id = matching_header["id"]

    wiki_data = await get_wiki_page(
        owner_id=self.owner_id,
        wiki_id=self.id,
        wiki_version=self.wiki_version,
        synapse_client=synapse_client,
    )
    self.fill_from_dict(wiki_data)
    return self
delete_async async
delete_async(*, synapse_client: Optional[Synapse] = None) -> None

Delete this wiki page.

PARAMETER DESCRIPTION
synapse_client

Optionally provide a Synapse client.

TYPE: Optional[Synapse] DEFAULT: None

Raises: ValueError: If required fields are missing.

Delete a wiki page

This example shows how to delete a wiki page.

wiki_page = await WikiPage(owner_id=project.id, id=wiki_page.id).delete_async()
print(f"Wiki page {wiki_page.title} deleted successfully.")

Source code in synapseclient/models/wiki.py
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"Delete_Wiki_Page: Owner ID {self.owner_id}, Wiki ID {self.id}"
)
async def delete_async(
    self,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> None:
    """
    Delete this wiki page.

    Arguments:
        synapse_client: Optionally provide a Synapse client.
    Raises:
        ValueError: If required fields are missing.

    Example: Delete a wiki page
        This example shows how to delete a wiki page.
        ```python
        wiki_page = await WikiPage(owner_id=project.id, id=wiki_page.id).delete_async()
        print(f"Wiki page {wiki_page.title} deleted successfully.")
        ```
    """
    if not self.owner_id:
        raise ValueError("Must provide owner_id to delete a wiki page.")
    if not self.id:
        raise ValueError("Must provide id to delete a wiki page.")

    await delete_wiki_page(
        owner_id=self.owner_id,
        wiki_id=self.id,
        synapse_client=synapse_client,
    )
get_attachment_handles_async async
get_attachment_handles_async(*, synapse_client: Optional[Synapse] = None) -> List[Dict[str, Any]]

Get the file handles of all attachments on this wiki page.

PARAMETER DESCRIPTION
synapse_client

Optionally provide a Synapse client.

TYPE: Optional[Synapse] DEFAULT: None

Returns: The list of FileHandles for all file attachments of this WikiPage. Raises: ValueError: If owner_id or id is not provided.

Get the file handles of all attachments on a wiki page

This example shows how to get the file handles of all attachments on a wiki page.

attachment_handles = await WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_handles_async()
print(f"Attachment handles: {attachment_handles['list']}")

Source code in synapseclient/models/wiki.py
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"Get_Attachment_Handles: Owner ID {self.owner_id}, Wiki ID {self.id}, Wiki Version {self.wiki_version}"
)
async def get_attachment_handles_async(
    self,
    *,
    synapse_client: Optional["Synapse"] = None,
) -> List[Dict[str, Any]]:
    """
    Get the file handles of all attachments on this wiki page.

    Arguments:
        synapse_client: Optionally provide a Synapse client.
    Returns:
        The list of FileHandles for all file attachments of this WikiPage.
    Raises:
        ValueError: If owner_id or id is not provided.

    Example: Get the file handles of all attachments on a wiki page
        This example shows how to get the file handles of all attachments on a wiki page.
        ```python
        attachment_handles = await WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_handles_async()
        print(f"Attachment handles: {attachment_handles['list']}")
        ```
    """
    if not self.owner_id:
        raise ValueError("Must provide owner_id to get attachment handles.")
    if not self.id:
        raise ValueError("Must provide id to get attachment handles.")

    return await get_attachment_handles(
        owner_id=self.owner_id,
        wiki_id=self.id,
        wiki_version=self.wiki_version,
        synapse_client=synapse_client,
    )
get_attachment_async async
get_attachment_async(*, file_name: str, download_file: bool = True, download_location: Optional[str] = None, synapse_client: Optional[Synapse] = None) -> Union[str, None]

Download the wiki page attachment to a local file or return the URL.

PARAMETER DESCRIPTION
file_name

The name of the file to get. The file name can be in either non-gzipped or gzipped format.

TYPE: str

download_file

Whether associated files should be downloaded. Default is True.

TYPE: bool DEFAULT: True

download_location

The directory to download the file to. Required if download_file is True.

TYPE: Optional[str] DEFAULT: None

synapse_client

Optionally provide a Synapse client.

TYPE: Optional[Synapse] DEFAULT: None

Returns: If download_file is True, the attachment file will be downloaded to the download_location. Otherwise, the URL will be returned. Raises: ValueError: If owner_id or id is not provided.

Get the attachment URL for a wiki page

This example shows how to get the attachment file or URL for a wiki page.

attachment_file_or_url = await WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_async(file_name="attachment.txt", download_file=False)
print(f"Attachment URL: {attachment_file_or_url}")

Example: Download the attachment file for a wiki page This example shows how to download the attachment file for a wiki page.

attachment_file_path = await WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_async(file_name="attachment.txt", download_file=True, download_location="~/temp")
print(f"Attachment file path: {attachment_file_path}")

Source code in synapseclient/models/wiki.py
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"Get_Attachment_URL: Owner ID {self.owner_id}, Wiki ID {self.id}, File Name {kwargs['file_name']}"
)
async def get_attachment_async(
    self,
    *,
    file_name: str,
    download_file: bool = True,
    download_location: Optional[str] = None,
    synapse_client: Optional["Synapse"] = None,
) -> Union[str, None]:
    """
    Download the wiki page attachment to a local file or return the URL.

    Arguments:
        file_name: The name of the file to get. The file name can be in either non-gzipped or gzipped format.
        download_file: Whether associated files should be downloaded. Default is True.
        download_location: The directory to download the file to. Required if download_file is True.
        synapse_client: Optionally provide a Synapse client.
    Returns:
        If download_file is True, the attachment file will be downloaded to the download_location. Otherwise, the URL will be returned.
    Raises:
        ValueError: If owner_id or id is not provided.

    Example: Get the attachment URL for a wiki page
        This example shows how to get the attachment file or URL for a wiki page.
        ```python
        attachment_file_or_url = await WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_async(file_name="attachment.txt", download_file=False)
        print(f"Attachment URL: {attachment_file_or_url}")
        ```
    Example: Download the attachment file for a wiki page
        This example shows how to download the attachment file for a wiki page.
        ```python
        attachment_file_path = await WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_async(file_name="attachment.txt", download_file=True, download_location="~/temp")
        print(f"Attachment file path: {attachment_file_path}")
        ```
    """
    if not self.owner_id:
        raise ValueError("Must provide owner_id to get attachment URL.")
    if not self.id:
        raise ValueError("Must provide id to get attachment URL.")
    if not file_name:
        raise ValueError("Must provide file_name to get attachment URL.")

    client = Synapse.get_client(synapse_client=synapse_client)

    if WikiPage._should_gzip_file(file_name):
        file_name = f"{file_name}.gz"
    attachment_url = await get_attachment_url(
        owner_id=self.owner_id,
        wiki_id=self.id,
        file_name=file_name,
        wiki_version=self.wiki_version,
        synapse_client=client,
    )

    if download_file:
        if not download_location:
            raise ValueError("Must provide download_location to download a file.")

        presigned_url_info = PresignedUrlInfo(
            url=attachment_url,
            file_name=file_name,
            expiration_utc=_pre_signed_url_expiration_time(attachment_url),
        )
        filehandle_dict = await get_attachment_handles(
            owner_id=self.owner_id,
            wiki_id=self.id,
            wiki_version=self.wiki_version,
            synapse_client=client,
        )
        file_size = int(WikiPage._get_file_size(filehandle_dict, file_name))
        if file_size < SINGLE_THREAD_DOWNLOAD_SIZE_LIMIT:
            # download_from_url is synchronous, run it in a worker thread so that
            # the blocking HTTP request does not stall the asyncio event loop
            # TODO: SYNPY-1903 - replace with the async download_from_url once
            # it is available and drop the worker thread
            loop = asyncio.get_running_loop()
            downloaded_file_path = await loop.run_in_executor(
                client._get_thread_pool_executor(asyncio_event_loop=loop),
                lambda: download_from_url(
                    url=presigned_url_info.url,
                    destination=download_location,
                    url_is_presigned=True,
                    synapse_client=client,
                ),
            )
        else:
            downloaded_file_path = await download_from_url_multi_threaded(
                presigned_url=presigned_url_info,
                destination=download_location,
                synapse_client=client,
            )
        unzipped_file_path = WikiPage.unzip_gzipped_file(downloaded_file_path)
        client.logger.info(
            f"[{self.owner_id}:{self.id}]: Downloaded file "
            f"{presigned_url_info.file_name.replace('.gz', '')} to "
            f"{unzipped_file_path}."
        )
        os.remove(downloaded_file_path)
        client.logger.debug(
            f"[{self.owner_id}:{self.id}]: Removed the gzipped file "
            f"{downloaded_file_path}."
        )
        return unzipped_file_path
    else:
        return attachment_url
get_attachment_preview_async async
get_attachment_preview_async(file_name: str, *, download_file: bool = True, download_location: Optional[str] = None, synapse_client: Optional[Synapse] = None) -> Union[str, None]

Download the wiki page attachment preview to a local file or return the URL.

PARAMETER DESCRIPTION
file_name

The name of the file to get. The file name can be in either non-gzipped or gzipped format.

TYPE: str

download_file

Whether associated files should be downloaded. Default is True.

TYPE: bool DEFAULT: True

download_location

The directory to download the file to. Required if download_file is True.

TYPE: Optional[str] DEFAULT: None

synapse_client

Optionally provide a Synapse client.

TYPE: Optional[Synapse] DEFAULT: None

Returns: If download_file is True, the attachment preview file will be downloaded to the download_location. Otherwise, the URL will be returned. Raises: ValueError: If owner_id or id is not provided.

Get the attachment preview URL for a wiki page

This example shows how to get the attachment preview URL for a wiki page. Instead of using the file_name from the attachmenthandle response when isPreview=True, you should use the original file name in the get_attachment_preview request. The downloaded file will still be named according to the file_name provided in the response when isPreview=True.

attachment_preview_url = await WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_preview_async(file_name="attachment.txt.gz", download_file=False)
print(f"Attachment preview URL: {attachment_preview_url}")

Example: Download the attachment preview file for a wiki page This example shows how to download the attachment preview file for a wiki page.

attachment_preview_file_path = WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_preview(file_name="attachment.txt.gz", download_file=True, download_location="~/temp")
print(f"Attachment preview file path: {attachment_preview_file_path}")

Source code in synapseclient/models/wiki.py
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"Get_Attachment_Preview_URL: Owner ID {self.owner_id}, Wiki ID {self.id}, File Name {kwargs['file_name']}"
)
async def get_attachment_preview_async(
    self,
    file_name: str,
    *,
    download_file: bool = True,
    download_location: Optional[str] = None,
    synapse_client: Optional["Synapse"] = None,
) -> Union[str, None]:
    """
    Download the wiki page attachment preview to a local file or return the URL.

    Arguments:
        file_name: The name of the file to get. The file name can be in either non-gzipped or gzipped format.
        download_file: Whether associated files should be downloaded. Default is True.
        download_location: The directory to download the file to. Required if download_file is True.
        synapse_client: Optionally provide a Synapse client.
    Returns:
        If download_file is True, the attachment preview file will be downloaded to the download_location. Otherwise, the URL will be returned.
    Raises:
        ValueError: If owner_id or id is not provided.

    Example: Get the attachment preview URL for a wiki page
        This example shows how to get the attachment preview URL for a wiki page.
        Instead of using the file_name from the attachmenthandle response when isPreview=True, you should use the original file name in the get_attachment_preview request.
        The downloaded file will still be named according to the file_name provided in the response when isPreview=True.
        ```python
        attachment_preview_url = await WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_preview_async(file_name="attachment.txt.gz", download_file=False)
        print(f"Attachment preview URL: {attachment_preview_url}")
        ```
    Example: Download the attachment preview file for a wiki page
        This example shows how to download the attachment preview file for a wiki page.
        ```python
        attachment_preview_file_path = WikiPage(owner_id=project.id, id=wiki_page.id).get_attachment_preview(file_name="attachment.txt.gz", download_file=True, download_location="~/temp")
        print(f"Attachment preview file path: {attachment_preview_file_path}")
        ```
    """
    if not self.owner_id:
        raise ValueError("Must provide owner_id to get attachment preview URL.")
    if not self.id:
        raise ValueError("Must provide id to get attachment preview URL.")
    if not file_name:
        raise ValueError("Must provide file_name to get attachment preview URL.")

    client = Synapse.get_client(synapse_client=synapse_client)
    # check if the file_name is in gzip format or image format
    if not file_name.endswith(".gz"):
        file_name = f"{file_name}.gz"
    attachment_preview_url = await get_attachment_preview_url(
        owner_id=self.owner_id,
        wiki_id=self.id,
        file_name=file_name,
        wiki_version=self.wiki_version,
        synapse_client=client,
    )
    if download_file:
        if not download_location:
            raise ValueError("Must provide download_location to download a file.")

        presigned_url_info = PresignedUrlInfo(
            url=attachment_preview_url,
            file_name=file_name,
            expiration_utc=_pre_signed_url_expiration_time(attachment_preview_url),
        )

        filehandle_dict = await get_attachment_handles(
            owner_id=self.owner_id,
            wiki_id=self.id,
            wiki_version=self.wiki_version,
            synapse_client=client,
        )
        file_size = int(WikiPage._get_file_size(filehandle_dict, file_name))
        if file_size < SINGLE_THREAD_DOWNLOAD_SIZE_LIMIT:
            # download_from_url is synchronous, run it in a worker thread so that
            # the blocking HTTP request does not stall the asyncio event loop
            # TODO: SYNPY-1903 - replace with the async download_from_url once
            # it is available and drop the worker thread
            loop = asyncio.get_running_loop()
            downloaded_file_path = await loop.run_in_executor(
                client._get_thread_pool_executor(asyncio_event_loop=loop),
                lambda: download_from_url(
                    url=presigned_url_info.url,
                    destination=download_location,
                    url_is_presigned=True,
                    synapse_client=client,
                ),
            )
        else:
            downloaded_file_path = await download_from_url_multi_threaded(
                presigned_url=presigned_url_info,
                destination=download_location,
                synapse_client=client,
            )
        client.logger.info(
            f"[{self.owner_id}:{self.id}]: Downloaded the preview file "
            f"{presigned_url_info.file_name.replace('.gz', '')} to "
            f"{downloaded_file_path}."
        )
        return downloaded_file_path
    else:
        return attachment_preview_url
get_markdown_file_async async
get_markdown_file_async(*, download_file: bool = True, download_location: Optional[str] = None, synapse_client: Optional[Synapse] = None) -> Union[str, None]

Get the markdown URL of this wiki page. --> modify this to print the markdown file

PARAMETER DESCRIPTION
download_file

Whether associated files should be downloaded. Default is True.

TYPE: bool DEFAULT: True

download_location

The directory to download the file to. Required if download_file is True.

TYPE: Optional[str] DEFAULT: None

synapse_client

Optionally provide a Synapse client.

TYPE: Optional[Synapse] DEFAULT: None

Returns: If download_file is True, the markdown file will be downloaded to the download_location. Otherwise, the URL will be returned. Raises: ValueError: If owner_id or id is not provided.

Get the markdown URL for a wiki page

This example shows how to get the markdown URL for a wiki page.

markdown_url = await WikiPage(owner_id=project.id, id=wiki_page.id).get_markdown_file_async(download_file=False)
print(f"Markdown URL: {markdown_url}")

Example: Download the markdown file for a wiki page This example shows how to download the markdown file for a wiki page.

markdown_file_path = await WikiPage(owner_id=project.id, id=wiki_page.id).get_markdown_file_async(download_file=True, download_location="~/temp")
print(f"Markdown file path: {markdown_file_path}")

Source code in synapseclient/models/wiki.py
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"Get_Markdown_URL: Owner ID {self.owner_id}, Wiki ID {self.id}, Wiki Version {self.wiki_version}"
)
async def get_markdown_file_async(
    self,
    *,
    download_file: bool = True,
    download_location: Optional[str] = None,
    synapse_client: Optional["Synapse"] = None,
) -> Union[str, None]:
    """
    Get the markdown URL of this wiki page. --> modify this to print the markdown file

    Arguments:
        download_file: Whether associated files should be downloaded. Default is True.
        download_location: The directory to download the file to. Required if download_file is True.
        synapse_client: Optionally provide a Synapse client.
    Returns:
        If download_file is True, the markdown file will be downloaded to the download_location. Otherwise, the URL will be returned.
    Raises:
        ValueError: If owner_id or id is not provided.

    Example: Get the markdown URL for a wiki page
        This example shows how to get the markdown URL for a wiki page.
        ```python
        markdown_url = await WikiPage(owner_id=project.id, id=wiki_page.id).get_markdown_file_async(download_file=False)
        print(f"Markdown URL: {markdown_url}")
        ```
    Example: Download the markdown file for a wiki page
        This example shows how to download the markdown file for a wiki page.
        ```python
        markdown_file_path = await WikiPage(owner_id=project.id, id=wiki_page.id).get_markdown_file_async(download_file=True, download_location="~/temp")
        print(f"Markdown file path: {markdown_file_path}")
        ```
    """
    if not self.owner_id:
        raise ValueError("Must provide owner_id to get markdown URL.")
    if not self.id:
        raise ValueError("Must provide id to get markdown URL.")

    client = Synapse.get_client(synapse_client=synapse_client)
    markdown_url = await get_markdown_url(
        owner_id=self.owner_id,
        wiki_id=self.id,
        wiki_version=self.wiki_version,
        synapse_client=client,
    )
    if download_file:
        if not download_location:
            raise ValueError("Must provide download_location to download a file.")

        # download_from_url is synchronous, run it in a worker thread so that the
        # blocking HTTP request does not stall the asyncio event loop
        # TODO: SYNPY-1903 - replace with the async download_from_url once it is
        # available and drop the worker thread
        loop = asyncio.get_running_loop()
        downloaded_file_path = await loop.run_in_executor(
            client._get_thread_pool_executor(asyncio_event_loop=loop),
            lambda: download_from_url(
                url=markdown_url,
                destination=download_location,
                url_is_presigned=True,
                synapse_client=client,
            ),
        )
        unzipped_file_path = WikiPage.unzip_gzipped_file(downloaded_file_path)
        client.logger.info(
            f"[{self.owner_id}:{self.id}]: Downloaded and unzipped the markdown "
            f"file to {unzipped_file_path}."
        )
        os.remove(downloaded_file_path)
        client.logger.debug(
            f"[{self.owner_id}:{self.id}]: Removed the gzipped file "
            f"{downloaded_file_path}."
        )
        return unzipped_file_path
    else:
        return markdown_url
copy_async async
copy_async(destination_owner_id: str, destination_sub_page_id: str | None = None, update_links: bool = True, entity_map: dict[str, str] | None = None, *, synapse_client: Synapse | None = None) -> list[WikiHeader]

Copy the wiki page tree of the owner entity to another entity and update internal links.

If id is set on this WikiPage, only the sub-tree rooted at that wiki page is copied. Otherwise the entire wiki of the owner entity is copied.

PARAMETER DESCRIPTION
destination_owner_id

The Synapse ID of the entity that the wiki will be copied to.

TYPE: str

destination_sub_page_id

Optional ID of a wiki page that already exists in the destination. The root of the copied tree is written into that page, replacing its title, markdown, and attachments, and the rest of the copied pages are created beneath it. Required when the destination entity already has a root wiki page.

TYPE: str | None DEFAULT: None

update_links

Update all the internal links so that they point at the copied wiki pages. For example, syn1234/wiki/34345 becomes syn3345/wiki/49508. Defaults to True.

TYPE: bool DEFAULT: True

entity_map

A mapping of old Synapse IDs to new Synapse IDs, for example {"syn1234": "syn2345"}. If provided, the Synapse IDs referenced in the markdown of the copied wiki pages are updated, for example syn1234 becomes syn2345. If omitted, Synapse IDs are left unchanged.

TYPE: dict[str, str] | None DEFAULT: None

synapse_client

If not passed in and caching was not disabled by Synapse.allow_client_caching(False) this will use the last created instance from the Synapse class constructor.

TYPE: Synapse | None DEFAULT: None

RETURNS DESCRIPTION
list[WikiHeader]

A list of WikiHeader objects for the destination entity.

RAISES DESCRIPTION
ValueError

If owner_id is not provided or is not a Synapse ID, if destination_owner_id is not a Synapse ID, if a key or value of entity_map is not a Synapse ID, if id is set but no wiki page with that ID exists in the owner entity, if destination_sub_page_id does not exist in the destination entity, if the destination entity already has a root wiki page and destination_sub_page_id is not provided, or if copying an attachment file handle fails.

Copy the entire wiki of an entity to another entity

This example shows how to copy all wiki pages from one project to another.

from synapseclient import Synapse
from synapseclient.models import WikiPage

syn = Synapse()
syn.login()

new_wiki_headers = await WikiPage(owner_id="syn123").copy_async(
    destination_owner_id="syn456"
)
print(new_wiki_headers)

Example: Copy a wiki sub-tree and update Synapse ID references This example shows how to copy a specific wiki page and its sub-pages, rewriting references to syn1234 so they point at syn2345.

new_wiki_headers = await WikiPage(owner_id="syn123", id="34345").copy_async(
    destination_owner_id="syn456",
    entity_map={"syn1234": "syn2345"},
)
print(new_wiki_headers)

Source code in synapseclient/models/wiki.py
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
@otel_trace_method(
    method_to_trace_name=lambda self, **kwargs: f"Copy_Wiki: Owner ID {self.owner_id}, Wiki ID {self.id}"
)
async def copy_async(
    self,
    destination_owner_id: str,
    destination_sub_page_id: str | None = None,
    update_links: bool = True,
    entity_map: dict[str, str] | None = None,
    *,
    synapse_client: Synapse | None = None,
) -> list["WikiHeader"]:
    """Copy the wiki page tree of the owner entity to another entity and
    update internal links.

    If id is set on this WikiPage, only the sub-tree rooted at that wiki page
    is copied. Otherwise the entire wiki of the owner entity is copied.

    Arguments:
        destination_owner_id: The Synapse ID of the entity that the wiki
            will be copied to.
        destination_sub_page_id: Optional ID of a wiki page that already
            exists in the destination. The root of the copied tree is written
            into that page, replacing its title, markdown, and attachments,
            and the rest of the copied pages are created beneath it.
            Required when the destination entity already has a root wiki
            page.
        update_links: Update all the internal links so that they point at the
            copied wiki pages. For example, syn1234/wiki/34345 becomes
            syn3345/wiki/49508. Defaults to True.
        entity_map: A mapping of old Synapse IDs to new Synapse IDs, for
            example {"syn1234": "syn2345"}. If provided, the Synapse IDs
            referenced in the markdown of the copied wiki pages are updated,
            for example syn1234 becomes syn2345. If omitted, Synapse IDs
            are left unchanged.
        synapse_client: If not passed in and caching was not disabled by
                Synapse.allow_client_caching(False) this will use the last created
                instance from the Synapse class constructor.

    Returns:
        A list of WikiHeader objects for the destination entity.

    Raises:
        ValueError: If owner_id is not provided or is not a Synapse ID,
            if destination_owner_id is not a Synapse ID, if a key or
            value of entity_map is not
            a Synapse ID, if id is set but no wiki page with that ID
            exists in the owner entity, if destination_sub_page_id does
            not exist in the destination entity, if the destination
            entity already has a root wiki page and
            destination_sub_page_id is not provided, or if copying an
            attachment file handle fails.

    Example: Copy the entire wiki of an entity to another entity
        This example shows how to copy all wiki pages from one project to another.
        ```python
        from synapseclient import Synapse
        from synapseclient.models import WikiPage

        syn = Synapse()
        syn.login()

        new_wiki_headers = await WikiPage(owner_id="syn123").copy_async(
            destination_owner_id="syn456"
        )
        print(new_wiki_headers)
        ```
    Example: Copy a wiki sub-tree and update Synapse ID references
        This example shows how to copy a specific wiki page and its sub-pages,
        rewriting references to syn1234 so they point at syn2345.
        ```python
        new_wiki_headers = await WikiPage(owner_id="syn123", id="34345").copy_async(
            destination_owner_id="syn456",
            entity_map={"syn1234": "syn2345"},
        )
        print(new_wiki_headers)
        ```
    """
    entity_sub_page_id, destination_sub_page_id = _validate_and_format_copy_inputs(
        owner_id=self.owner_id,
        destination_owner_id=destination_owner_id,
        entity_sub_page_id=self.id,
        destination_sub_page_id=destination_sub_page_id,
        entity_map=entity_map,
    )

    client = Synapse.get_client(synapse_client=synapse_client)

    # Getting the wiki header tree fails when there is no wiki
    old_wiki_headers = []
    try:
        async for item in get_wiki_header_tree(
            owner_id=self.owner_id,
            synapse_client=client,
        ):
            old_wiki_headers.append(item)
    except SynapseHTTPError as e:
        if e.response.status_code == 404:
            if entity_sub_page_id:
                raise ValueError(
                    f"The wiki page {entity_sub_page_id} does not exist "
                    f"in the owner entity {self.owner_id}."
                ) from e
            return []
        raise

    if destination_sub_page_id:
        destination_wiki_page = await _get_existing_destination_wiki_page(
            destination_owner_id=destination_owner_id,
            destination_sub_page_id=destination_sub_page_id,
            synapse_client=client,
        )
    else:
        await _ensure_destination_has_no_root_wiki(
            destination_owner_id=destination_owner_id,
            synapse_client=client,
        )
        destination_wiki_page = None

    if entity_sub_page_id:
        all_wiki_headers = old_wiki_headers
        old_wiki_headers = _collect_wiki_sub_tree_headers(
            wiki_headers=all_wiki_headers,
            sub_page_id=entity_sub_page_id,
        )
        if not old_wiki_headers:
            raise ValueError(
                f"The wiki page {entity_sub_page_id} does not exist "
                f"in the owner entity {self.owner_id}."
            )
        collected_ids = {header["id"] for header in old_wiki_headers}
        ignored_ids = [
            header["id"]
            for header in all_wiki_headers
            if header["id"] not in collected_ids
        ]
        if ignored_ids:
            client.logger.debug(
                f"[{self.owner_id}]: Not copying {len(ignored_ids)} wiki page(s) "
                f"outside the sub-tree rooted at {entity_sub_page_id}: "
                f"{ignored_ids}"
            )

    if not old_wiki_headers:
        return []

    new_wikis, wiki_id_map = await _copy_wiki_pages(
        old_wiki_headers=old_wiki_headers,
        source_owner_id=self.owner_id,
        destination_owner_id=destination_owner_id,
        destination_wiki_page=destination_wiki_page,
        destination_sub_page_id=destination_sub_page_id,
        synapse_client=client,
    )

    if update_links:
        client.logger.debug(
            f"[{self.owner_id} -> {destination_owner_id}]: Updating internal links"
        )
        new_wikis = _update_internal_links(
            new_wikis=new_wikis,
            wiki_id_map=wiki_id_map,
            source_owner_id=self.owner_id,
            destination_owner_id=destination_owner_id,
        )
        client.logger.debug(
            f"[{self.owner_id} -> {destination_owner_id}]: Done updating internal "
            "links."
        )

    if entity_map:
        client.logger.debug(
            f"[{self.owner_id} -> {destination_owner_id}]: Updating Synapse "
            "references"
        )
        new_wikis = _update_synapse_id_references(
            new_wikis=new_wikis,
            wiki_id_map=wiki_id_map,
            entity_map=entity_map,
        )
        client.logger.debug(
            f"[{self.owner_id} -> {destination_owner_id}]: Done updating Synapse "
            "IDs."
        )

    if update_links or entity_map:
        client.logger.debug(
            f"[{self.owner_id} -> {destination_owner_id}]: Storing new wiki pages"
        )
        for new_wiki_id in wiki_id_map.values():
            new_wiki = new_wikis[new_wiki_id]
            new_wiki = await new_wiki._get_markdown_file_handle(
                synapse_client=client
            )
            wiki_data = await put_wiki_page(
                owner_id=destination_owner_id,
                wiki_id=new_wiki_id,
                request=new_wiki.to_synapse_request(),
                synapse_client=client,
            )
            new_wikis[new_wiki_id] = new_wiki.fill_from_dict(synapse_wiki=wiki_data)
            client.logger.debug(
                f"[{destination_owner_id}:{new_wiki_id}]: Stored wiki page"
            )

    new_wiki_headers = []
    async for item in get_wiki_header_tree(
        owner_id=destination_owner_id,
        synapse_client=client,
    ):
        new_wiki_headers.append(WikiHeader().fill_from_dict(wiki_header=item))
    return new_wiki_headers

Functions: