Skip to content

anytype.Anytype

Used to interact with the Anytype API for authentication, retrieving spaces, creating spaces, and performing global searches. It provides methods to authenticate via a token, fetch spaces, create new spaces, and search for objects across spaces.

Source code in anytype/anytype.py
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 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
class Anytype:
    """
    Used to interact with the Anytype API for authentication, retrieving spaces, creating spaces, and performing global searches. It provides methods to authenticate via a token, fetch spaces, create new spaces, and search for objects across spaces.
    """

    def __init__(self) -> None:
        self.app_name = ""
        self.space_id = ""
        self.token = ""
        self.app_key = ""
        self._apiEndpoints: apiEndpoints | None = None
        self._headers = {}


    def auth(self, force=False, callback=None) -> None:
        """
        Authenticates the user by retrieving or creating a session token. If the session token already exists, it validates the token. If not, the user will be prompted to enter a 4-digit code for authentication.

        Parameters:
            force (bool): If True, forces re-authentication even if a token already exists.
            callback (callable): A callback function to retrieve the 4-digit code. If None, the user will be prompted to enter the code.

        Raises:
            Raises an error if the authentication request or token validation fails.
        """
        userdata = self._get_userdata_folder()
        anytoken = os.path.join(userdata, "any_token.json")

        if force and os.path.exists(anytoken):
            os.remove(anytoken)

        if self.app_name == "":
            self.app_name = "python-anytype-client"

        if os.path.exists(anytoken):
            with open(anytoken) as f:
                auth_json = json.load(f)
            self.token = auth_json.get("session_token")
            self.app_key = auth_json.get("app_key")
            if self._validate_token():
                return

        # Inicializa o client de API com o nome do app
        self._apiEndpoints = apiEndpoints()
        display_code_response = self._apiEndpoints.displayCode()
        challenge_id = display_code_response.get("challenge_id")

        if callback is None:
            api_four_digit_code = input("Enter the 4 digit code: ")
        else:
            api_four_digit_code = callback()

        token_response = self._apiEndpoints.getToken(challenge_id, api_four_digit_code)

        # Salva o token localmente
        with open(anytoken, "w") as file:
            json.dump(token_response, file, indent=4)

        self.token = token_response.get("session_token")
        self.app_key = token_response.get("app_key")
        self._validate_token()


    def _validate_token(self) -> bool:
        self._headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.app_key}",
        }
        self._apiEndpoints = apiEndpoints(self._headers)
        try:
            self._apiEndpoints.getSpaces(0, 1)
            return True
        except Exception:
            return False


    def _get_userdata_folder(self) -> str:
        userdata = os.path.join(os.path.expanduser("~"), ".anytype")
        if not os.path.exists(userdata):
            os.makedirs(userdata)
        if os.name == "nt":
            os.system(f"attrib +h {userdata}")
        return userdata


    @requires_auth
    def get_space(self, spaceId: str) -> Space:
        response = self._apiEndpoints.getSpace(spaceId)
        data = response.get("space", {})
        return Space._from_api(self._apiEndpoints, data)


    @requires_auth
    def get_spaces(self, offset=0, limit=10) -> list[Space]:
        """
        Retrieves a list of spaces associated with the authenticated user.

        Parameters:
            offset (int, optional): The offset for pagination (default: 0).
            limit (int, optional): The limit for the number of results (default: 10).

        Returns:
            A list of Space instances.

        Raises:
            Raises an error if the request to the API fails.
        """
        response = self._apiEndpoints.getSpaces(offset, limit)
        return [
            Space._from_api(self._apiEndpoints, data)
            for data in response.get("data", [])
        ]


    @requires_auth
    def create_space(self, name: str) -> Space:
        """
        Creates a new space with a given name.

        Parameters:
            name (str): The name of the space to create.

        Returns:
            A Space instance representing the newly created space.

        Raises:
            Raises an error if the space creation request fails.
        """
        response = self._apiEndpoints.createSpace(name)
        data = response.get("space", {})
        return Space._from_api(self._apiEndpoints, data)


    @requires_auth
    def global_search(self, query, offset=0, limit=10) -> list[Object]:
        """
        Performs a global search for objects across all spaces using a query string.

        Parameters:
            query (str): The search query string.
            offset (int, optional): The offset for pagination (default: 0).
            limit (int, optional): The limit for the number of results (default: 10).

        Returns:
            A list of Object instances that match the search query.

        Raises:
            Raises an error if the search request fails.
        """
        response = self._apiEndpoints.globalSearch(query, offset, limit)
        return [
            Object._from_api(self._apiEndpoints, data)
            for data in response.get("data", [])
        ]

auth(force=False, callback=None)

Authenticates the user by retrieving or creating a session token. If the session token already exists, it validates the token. If not, the user will be prompted to enter a 4-digit code for authentication.

Parameters:

Name Type Description Default
force bool

If True, forces re-authentication even if a token already exists.

False
callback callable

A callback function to retrieve the 4-digit code. If None, the user will be prompted to enter the code.

None
Source code in anytype/anytype.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def auth(self, force=False, callback=None) -> None:
    """
    Authenticates the user by retrieving or creating a session token. If the session token already exists, it validates the token. If not, the user will be prompted to enter a 4-digit code for authentication.

    Parameters:
        force (bool): If True, forces re-authentication even if a token already exists.
        callback (callable): A callback function to retrieve the 4-digit code. If None, the user will be prompted to enter the code.

    Raises:
        Raises an error if the authentication request or token validation fails.
    """
    userdata = self._get_userdata_folder()
    anytoken = os.path.join(userdata, "any_token.json")

    if force and os.path.exists(anytoken):
        os.remove(anytoken)

    if self.app_name == "":
        self.app_name = "python-anytype-client"

    if os.path.exists(anytoken):
        with open(anytoken) as f:
            auth_json = json.load(f)
        self.token = auth_json.get("session_token")
        self.app_key = auth_json.get("app_key")
        if self._validate_token():
            return

    # Inicializa o client de API com o nome do app
    self._apiEndpoints = apiEndpoints()
    display_code_response = self._apiEndpoints.displayCode()
    challenge_id = display_code_response.get("challenge_id")

    if callback is None:
        api_four_digit_code = input("Enter the 4 digit code: ")
    else:
        api_four_digit_code = callback()

    token_response = self._apiEndpoints.getToken(challenge_id, api_four_digit_code)

    # Salva o token localmente
    with open(anytoken, "w") as file:
        json.dump(token_response, file, indent=4)

    self.token = token_response.get("session_token")
    self.app_key = token_response.get("app_key")
    self._validate_token()

create_space(name)

Creates a new space with a given name.

Parameters:

Name Type Description Default
name str

The name of the space to create.

required

Returns:

Type Description
Space

A Space instance representing the newly created space.

Source code in anytype/anytype.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
@requires_auth
def create_space(self, name: str) -> Space:
    """
    Creates a new space with a given name.

    Parameters:
        name (str): The name of the space to create.

    Returns:
        A Space instance representing the newly created space.

    Raises:
        Raises an error if the space creation request fails.
    """
    response = self._apiEndpoints.createSpace(name)
    data = response.get("space", {})
    return Space._from_api(self._apiEndpoints, data)

get_spaces(offset=0, limit=10)

Retrieves a list of spaces associated with the authenticated user.

Parameters:

Name Type Description Default
offset int

The offset for pagination (default: 0).

0
limit int

The limit for the number of results (default: 10).

10

Returns:

Type Description
list[Space]

A list of Space instances.

Source code in anytype/anytype.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
@requires_auth
def get_spaces(self, offset=0, limit=10) -> list[Space]:
    """
    Retrieves a list of spaces associated with the authenticated user.

    Parameters:
        offset (int, optional): The offset for pagination (default: 0).
        limit (int, optional): The limit for the number of results (default: 10).

    Returns:
        A list of Space instances.

    Raises:
        Raises an error if the request to the API fails.
    """
    response = self._apiEndpoints.getSpaces(offset, limit)
    return [
        Space._from_api(self._apiEndpoints, data)
        for data in response.get("data", [])
    ]

Performs a global search for objects across all spaces using a query string.

Parameters:

Name Type Description Default
query str

The search query string.

required
offset int

The offset for pagination (default: 0).

0
limit int

The limit for the number of results (default: 10).

10

Returns:

Type Description
list[Object]

A list of Object instances that match the search query.

Source code in anytype/anytype.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
@requires_auth
def global_search(self, query, offset=0, limit=10) -> list[Object]:
    """
    Performs a global search for objects across all spaces using a query string.

    Parameters:
        query (str): The search query string.
        offset (int, optional): The offset for pagination (default: 0).
        limit (int, optional): The limit for the number of results (default: 10).

    Returns:
        A list of Object instances that match the search query.

    Raises:
        Raises an error if the search request fails.
    """
    response = self._apiEndpoints.globalSearch(query, offset, limit)
    return [
        Object._from_api(self._apiEndpoints, data)
        for data in response.get("data", [])
    ]