Skip to content

dropbox

DropboxHandler

Bases: AbstractProvider

Source code in client/ayon_sitesync/providers/dropbox.py
  8
  9
 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
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
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
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
class DropboxHandler(AbstractProvider):
    CODE = "dropbox"
    LABEL = "Dropbox"

    def __init__(self, project_name, site_name, tree=None, presets=None):
        self.active = False
        self.site_name = site_name
        self.presets = presets
        self.dbx = None

        if not self.presets:
            self.log.info(
                "Sync Server: There are no presets for {}.".format(site_name)
            )
            return

        if not self.presets.get("enabled"):
            self.log.debug("Sync Server: Site {} not enabled for {}.".
                      format(site_name, project_name))
            return

        token = self.presets.get("token", "")
        if not token:
            msg = "Sync Server: No access token for dropbox provider"
            self.log.info(msg)
            return

        team_folder_name = self.presets.get("team_folder_name", "")
        if not team_folder_name:
            msg = "Sync Server: No team folder name for dropbox provider"
            self.log.info(msg)
            return

        acting_as_member = self.presets.get("acting_as_member", "")
        if not acting_as_member:
            msg = (
                "Sync Server: No acting member for dropbox provider"
            )
            self.log.info(msg)
            return

        try:
            self.dbx = self._get_service(
                token, acting_as_member, team_folder_name
            )
        except Exception as e:
            self.log.info("Could not establish dropbox object: {}".format(e))
            return

        super(AbstractProvider, self).__init__()

    def _get_service(self, token, acting_as_member, team_folder_name):
        dbx = dropbox.DropboxTeam(token)

        # Getting member id.
        member_id = None
        member_names = []
        for member in dbx.team_members_list().members:
            member_names.append(member.profile.name.display_name)
            if member.profile.name.display_name == acting_as_member:
                member_id = member.profile.team_member_id

        if member_id is None:
            raise ValueError(
                "Could not find member \"{}\". Available members: {}".format(
                    acting_as_member, member_names
                )
            )

        # Getting team folder id.
        team_folder_id = None
        team_folder_names = []
        for entry in dbx.team_team_folder_list().team_folders:
            team_folder_names.append(entry.name)
            if entry.name == team_folder_name:
                team_folder_id = entry.team_folder_id

        if team_folder_id is None:
            raise ValueError(
                "Could not find team folder \"{}\". Available folders: "
                "{}".format(
                    team_folder_name, team_folder_names
                )
            )

        # Establish dropbox object.
        path_root = dropbox.common.PathRoot.namespace_id(team_folder_id)
        return dropbox.DropboxTeam(
            token
        ).with_path_root(path_root).as_user(member_id)

    def is_active(self):
        """
            Returns True if provider is activated, eg. has working credentials.
        Returns:
            (boolean)
        """
        return self.presets.get("enabled") and self.dbx is not None

    def _path_exists(self, path):
        try:
            entries = self.dbx.files_list_folder(
                path=os.path.dirname(path)
            ).entries
        except dropbox.exceptions.ApiError:
            return False

        for entry in entries:
            if entry.name == os.path.basename(path):
                return True

        return False

    def upload_file(
        self,
        source_path,
        target_path,
        addon,
        project_name,
        file,
        repre_status,
        site_name,
        overwrite=False
    ):
        """
            Copy file from 'source_path' to 'target_path' on provider.
            Use 'overwrite' boolean to rewrite existing file on provider

        Args:
            source_path (string): absolute path on provider
            target_path (string): absolute path with or without name of the file
            addon (SiteSyncAddon): addon instance to call update_db on
            project_name (str):
            file (dict): info about uploaded file (matches structure from db)
            repre_status (dict): complete representation containing
                sync progress
            site_name (str): site name
            overwrite (boolean): replace existing file
        Returns:
            (string) file_id of created file, raises exception
        """
        # Check source path.
        if not os.path.exists(source_path):
            raise FileNotFoundError(
                "Source file {} doesn't exist.".format(source_path)
            )

        if self._path_exists(target_path) and not overwrite:
            raise FileExistsError(
                "File already exists, use 'overwrite' argument"
            )

        mode = dropbox.files.WriteMode("add", None)
        if overwrite:
            mode = dropbox.files.WriteMode.overwrite

        with open(source_path, "rb") as f:
            file_size = os.path.getsize(source_path)

            CHUNK_SIZE = 50 * 1024 * 1024

            if file_size <= CHUNK_SIZE:
                self.dbx.files_upload(f.read(), target_path, mode=mode)
            else:
                upload_session_start_result = \
                    self.dbx.files_upload_session_start(f.read(CHUNK_SIZE))

                cursor = dropbox.files.UploadSessionCursor(
                    session_id=upload_session_start_result.session_id,
                    offset=f.tell())

                commit = dropbox.files.CommitInfo(path=target_path, mode=mode)

                while f.tell() < file_size:
                    if (file_size - f.tell()) <= CHUNK_SIZE:
                        self.dbx.files_upload_session_finish(
                            f.read(CHUNK_SIZE),
                            cursor,
                            commit)
                    else:
                        self.dbx.files_upload_session_append(
                            f.read(CHUNK_SIZE),
                            cursor.session_id,
                            cursor.offset)
                        cursor.offset = f.tell()

        addon.update_db(
            project_name=project_name,
            new_file_id=None,
            file=file,
            repre_status=repre_status,
            site_name=site_name,
            side="remote",
            progress=100
        )

        return target_path

    def download_file(
        self,
        source_path,
        local_path,
        addon,
        project_name,
        file,
        repre_status,
        site_name,
        overwrite=False
    ):
        """
            Download file from provider into local system

        Args:
            source_path (string): absolute path on provider
            local_path (string): absolute path with or without name of the file
            addon (SiteSyncAddon): addon instance to call update_db on
            project_name (str):
            file (dict): info about uploaded file (matches structure from db)
            repre_status (dict): complete representation containing
                sync progress
            site_name (str): site name
            overwrite (boolean): replace existing file
        Returns:
            None
        """
        # Check source path.
        if not self._path_exists(source_path):
            raise FileNotFoundError(
                "Source file {} doesn't exist.".format(source_path)
            )

        if os.path.exists(local_path) and not overwrite:
            raise FileExistsError(
                "File already exists, use 'overwrite' argument"
            )

        if os.path.exists(local_path) and overwrite:
            os.unlink(local_path)

        self.dbx.files_download_to_file(local_path, source_path)

        addon.update_db(
            project_name=project_name,
            new_file_id=None,
            file=file,
            repre_status=repre_status,
            site_name=site_name,
            side="local",
            progress=100
        )

        return os.path.basename(source_path)

    def delete_file(self, path):
        """
            Deletes file from 'path'. Expects path to specific file.

        Args:
            path (string): absolute path to particular file

        Returns:
            None
        """
        if not self._path_exists(path):
            raise FileExistsError("File {} doesn't exist".format(path))

        self.dbx.files_delete(path)

    def list_folder(self, folder_path):
        """
            List all files and subfolders of particular path non-recursively.
        Args:
            folder_path (string): absolut path on provider

        Returns:
            (list)
        """
        if not self._path_exists(folder_path):
            raise FileExistsError(
                "Folder \"{}\" does not exist".format(folder_path)
            )

        entry_names = []
        for entry in self.dbx.files_list_folder(path=folder_path).entries:
            entry_names.append(entry.name)
        return entry_names

    def create_folder(self, folder_path):
        """
            Create all nonexistent folders and subfolders in 'path'.

        Args:
            path (string): absolute path

        Returns:
            (string) folder id of lowest subfolder from 'path'
        """
        if self._path_exists(folder_path):
            return folder_path

        self.dbx.files_create_folder_v2(folder_path)

        return folder_path

    def get_tree(self):
        """
            Creates folder structure for providers which do not provide
            tree folder structure (GDrive has no accessible tree structure,
            only parents and their parents)
        """
        pass

    def get_roots_config(self, anatomy=None):
        """
            Returns root values for path resolving

            Takes value from Anatomy which takes values from Settings
            overridden by Local Settings

        Returns:
            (dict) - {"root": {"root": "/My Drive"}}
                     OR
                     {"root": {"root_ONE": "value", "root_TWO":"value}}
            Format is importing for usage of python's format ** approach
        """
        # TODO implement multiple roots
        return {"root": {"work": self.presets['root']}}

    def resolve_path(self, path, root_config=None, anatomy=None):
        """
            Replaces all root placeholders with proper values

            Args:
                path(string): root[work]/folder...
                root_config (dict): {'work': "c:/..."...}
                anatomy (Anatomy): object of Anatomy
            Returns:
                (string): proper url
        """
        if not root_config:
            root_config = self.get_roots_config(anatomy)

        if root_config and not root_config.get("root"):
            root_config = {"root": root_config}

        try:
            if not root_config:
                raise KeyError

            path = path.format(**root_config)
        except KeyError:
            try:
                path = anatomy.fill_root(path)
            except KeyError:
                msg = "Error in resolving local root from anatomy"
                self.log.error(msg)
                raise ValueError(msg)

        return path

create_folder(folder_path)

Create all nonexistent folders and subfolders in 'path'.

Parameters:

Name Type Description Default
path string

absolute path

required

Returns:

Type Description

(string) folder id of lowest subfolder from 'path'

Source code in client/ayon_sitesync/providers/dropbox.py
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def create_folder(self, folder_path):
    """
        Create all nonexistent folders and subfolders in 'path'.

    Args:
        path (string): absolute path

    Returns:
        (string) folder id of lowest subfolder from 'path'
    """
    if self._path_exists(folder_path):
        return folder_path

    self.dbx.files_create_folder_v2(folder_path)

    return folder_path

delete_file(path)

Deletes file from 'path'. Expects path to specific file.

Parameters:

Name Type Description Default
path string

absolute path to particular file

required

Returns:

Type Description

None

Source code in client/ayon_sitesync/providers/dropbox.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def delete_file(self, path):
    """
        Deletes file from 'path'. Expects path to specific file.

    Args:
        path (string): absolute path to particular file

    Returns:
        None
    """
    if not self._path_exists(path):
        raise FileExistsError("File {} doesn't exist".format(path))

    self.dbx.files_delete(path)

download_file(source_path, local_path, addon, project_name, file, repre_status, site_name, overwrite=False)

Download file from provider into local system

Parameters:

Name Type Description Default
source_path string

absolute path on provider

required
local_path string

absolute path with or without name of the file

required
addon SiteSyncAddon

addon instance to call update_db on

required
project_name str
required
file dict

info about uploaded file (matches structure from db)

required
repre_status dict

complete representation containing sync progress

required
site_name str

site name

required
overwrite boolean

replace existing file

False

Returns: None

Source code in client/ayon_sitesync/providers/dropbox.py
206
207
208
209
210
211
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
252
253
254
255
256
257
258
259
def download_file(
    self,
    source_path,
    local_path,
    addon,
    project_name,
    file,
    repre_status,
    site_name,
    overwrite=False
):
    """
        Download file from provider into local system

    Args:
        source_path (string): absolute path on provider
        local_path (string): absolute path with or without name of the file
        addon (SiteSyncAddon): addon instance to call update_db on
        project_name (str):
        file (dict): info about uploaded file (matches structure from db)
        repre_status (dict): complete representation containing
            sync progress
        site_name (str): site name
        overwrite (boolean): replace existing file
    Returns:
        None
    """
    # Check source path.
    if not self._path_exists(source_path):
        raise FileNotFoundError(
            "Source file {} doesn't exist.".format(source_path)
        )

    if os.path.exists(local_path) and not overwrite:
        raise FileExistsError(
            "File already exists, use 'overwrite' argument"
        )

    if os.path.exists(local_path) and overwrite:
        os.unlink(local_path)

    self.dbx.files_download_to_file(local_path, source_path)

    addon.update_db(
        project_name=project_name,
        new_file_id=None,
        file=file,
        repre_status=repre_status,
        site_name=site_name,
        side="local",
        progress=100
    )

    return os.path.basename(source_path)

get_roots_config(anatomy=None)

Returns root values for path resolving

Takes value from Anatomy which takes values from Settings
overridden by Local Settings

Returns:

Type Description

(dict) - {"root": {"root": "/My Drive"}} OR {"root": {"root_ONE": "value", "root_TWO":"value}}

Format is importing for usage of python's format ** approach

Source code in client/ayon_sitesync/providers/dropbox.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
def get_roots_config(self, anatomy=None):
    """
        Returns root values for path resolving

        Takes value from Anatomy which takes values from Settings
        overridden by Local Settings

    Returns:
        (dict) - {"root": {"root": "/My Drive"}}
                 OR
                 {"root": {"root_ONE": "value", "root_TWO":"value}}
        Format is importing for usage of python's format ** approach
    """
    # TODO implement multiple roots
    return {"root": {"work": self.presets['root']}}

get_tree()

Creates folder structure for providers which do not provide tree folder structure (GDrive has no accessible tree structure, only parents and their parents)

Source code in client/ayon_sitesync/providers/dropbox.py
312
313
314
315
316
317
318
def get_tree(self):
    """
        Creates folder structure for providers which do not provide
        tree folder structure (GDrive has no accessible tree structure,
        only parents and their parents)
    """
    pass

is_active()

Returns True if provider is activated, eg. has working credentials.

Returns: (boolean)

Source code in client/ayon_sitesync/providers/dropbox.py
 99
100
101
102
103
104
105
def is_active(self):
    """
        Returns True if provider is activated, eg. has working credentials.
    Returns:
        (boolean)
    """
    return self.presets.get("enabled") and self.dbx is not None

list_folder(folder_path)

List all files and subfolders of particular path non-recursively.

Args: folder_path (string): absolut path on provider

Returns:

Type Description

(list)

Source code in client/ayon_sitesync/providers/dropbox.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def list_folder(self, folder_path):
    """
        List all files and subfolders of particular path non-recursively.
    Args:
        folder_path (string): absolut path on provider

    Returns:
        (list)
    """
    if not self._path_exists(folder_path):
        raise FileExistsError(
            "Folder \"{}\" does not exist".format(folder_path)
        )

    entry_names = []
    for entry in self.dbx.files_list_folder(path=folder_path).entries:
        entry_names.append(entry.name)
    return entry_names

resolve_path(path, root_config=None, anatomy=None)

Replaces all root placeholders with proper values

Parameters:

Name Type Description Default
path(string)

root[work]/folder...

required
root_config dict

{'work': "c:/..."...}

None
anatomy Anatomy

object of Anatomy

None

Returns: (string): proper url

Source code in client/ayon_sitesync/providers/dropbox.py
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
def resolve_path(self, path, root_config=None, anatomy=None):
    """
        Replaces all root placeholders with proper values

        Args:
            path(string): root[work]/folder...
            root_config (dict): {'work': "c:/..."...}
            anatomy (Anatomy): object of Anatomy
        Returns:
            (string): proper url
    """
    if not root_config:
        root_config = self.get_roots_config(anatomy)

    if root_config and not root_config.get("root"):
        root_config = {"root": root_config}

    try:
        if not root_config:
            raise KeyError

        path = path.format(**root_config)
    except KeyError:
        try:
            path = anatomy.fill_root(path)
        except KeyError:
            msg = "Error in resolving local root from anatomy"
            self.log.error(msg)
            raise ValueError(msg)

    return path

upload_file(source_path, target_path, addon, project_name, file, repre_status, site_name, overwrite=False)

Copy file from 'source_path' to 'target_path' on provider.
Use 'overwrite' boolean to rewrite existing file on provider

Parameters:

Name Type Description Default
source_path string

absolute path on provider

required
target_path string

absolute path with or without name of the file

required
addon SiteSyncAddon

addon instance to call update_db on

required
project_name str
required
file dict

info about uploaded file (matches structure from db)

required
repre_status dict

complete representation containing sync progress

required
site_name str

site name

required
overwrite boolean

replace existing file

False

Returns: (string) file_id of created file, raises exception

Source code in client/ayon_sitesync/providers/dropbox.py
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
def upload_file(
    self,
    source_path,
    target_path,
    addon,
    project_name,
    file,
    repre_status,
    site_name,
    overwrite=False
):
    """
        Copy file from 'source_path' to 'target_path' on provider.
        Use 'overwrite' boolean to rewrite existing file on provider

    Args:
        source_path (string): absolute path on provider
        target_path (string): absolute path with or without name of the file
        addon (SiteSyncAddon): addon instance to call update_db on
        project_name (str):
        file (dict): info about uploaded file (matches structure from db)
        repre_status (dict): complete representation containing
            sync progress
        site_name (str): site name
        overwrite (boolean): replace existing file
    Returns:
        (string) file_id of created file, raises exception
    """
    # Check source path.
    if not os.path.exists(source_path):
        raise FileNotFoundError(
            "Source file {} doesn't exist.".format(source_path)
        )

    if self._path_exists(target_path) and not overwrite:
        raise FileExistsError(
            "File already exists, use 'overwrite' argument"
        )

    mode = dropbox.files.WriteMode("add", None)
    if overwrite:
        mode = dropbox.files.WriteMode.overwrite

    with open(source_path, "rb") as f:
        file_size = os.path.getsize(source_path)

        CHUNK_SIZE = 50 * 1024 * 1024

        if file_size <= CHUNK_SIZE:
            self.dbx.files_upload(f.read(), target_path, mode=mode)
        else:
            upload_session_start_result = \
                self.dbx.files_upload_session_start(f.read(CHUNK_SIZE))

            cursor = dropbox.files.UploadSessionCursor(
                session_id=upload_session_start_result.session_id,
                offset=f.tell())

            commit = dropbox.files.CommitInfo(path=target_path, mode=mode)

            while f.tell() < file_size:
                if (file_size - f.tell()) <= CHUNK_SIZE:
                    self.dbx.files_upload_session_finish(
                        f.read(CHUNK_SIZE),
                        cursor,
                        commit)
                else:
                    self.dbx.files_upload_session_append(
                        f.read(CHUNK_SIZE),
                        cursor.session_id,
                        cursor.offset)
                    cursor.offset = f.tell()

    addon.update_db(
        project_name=project_name,
        new_file_id=None,
        file=file,
        repre_status=repre_status,
        site_name=site_name,
        side="remote",
        progress=100
    )

    return target_path