Giter VIP home page Giter VIP logo

synology-drive-api's Introduction

Synology Drive API

Downloads Python License Contributions welcome

synology-drive-api is inspired by synology-api. This repo is aimed at providing Synology drive api wrapper and related helper functions. It helps you manage your files/folders/labels in synology drive. By means of Synology Office, you can edit spreadsheet on Drive and use this api wrapper read spreadsheet. It supports Python 3.7+.

Installation

pip install synology-drive-api

Get login session

You can access drive by IP, drive domain or nas domain + drive path.

Synology Drive allows same user with multiple login session. if you need multiple login session and label functions, disable label cache.

from synology_drive_api.drive import SynologyDrive

# default http port is 5000, https is 5001. 
with SynologyDrive(NAS_USER, NAS_PASS, NAS_IP) as synd:
    synd.list_folder('/mydrive')  # write your code here
# Use specified port
with SynologyDrive(NAS_USER, NAS_PASS, NAS_IP, NAS_PORT) as synd:
    synd.get_file_or_folder_info(path_or_path_id)  # write your code here
# use http instead of https. https: default is True.
with SynologyDrive(NAS_USER, NAS_PASS, NAS_IP, https=False) as synd:
    synd.create_folder('test', 'team-folder/folder2/')  # write your code here
# Enable 2fa.
with SynologyDrive(NAS_USER, NAS_PASS, otp_code='XXXXXX') as synd:
    synd.list_folder('/mydrive')  # write your code here
# use domain name or name + path access drive
# Enabled in Application Portal | Application | Drive | General | Enable customized alias
drive_path_demo = 'your_nas_domain/drive'
# Enabled in Application Portal | Application | Drive | General | Enable customized domain
drive_path_demo2 = 'your_drive_domain'
with SynologyDrive(NAS_USER, NAS_PASS, drive_path_demo) as synd:
    synd.upload_file(file, dest_folder_path=dest_folder_path)  # write your code here
# disable label cache
with SynologyDrive(NAS_USER, NAS_PASS, drive_path_demo, enable_label_cache=False) as synd:
    synd.list_folder('/mydrive')  # write your code here

If you use dsm 7, default dsm_version is '6'.

from synology_drive_api.drive import SynologyDrive

# default http port is 5000, https is 5001. 
with SynologyDrive(NAS_USER, NAS_PASS, NAS_IP, dsm_version='7') as synd:
   synd.download_file('/mydrive/test.osheet')  # write your code here

Manage labels

Synology drive thinks labels need to belong to single user. If you want share labels between users, you should have access to these user accounts. Another solution is creating a tool user.

Synology drive search function provide label union search rather than intersection search. If you need label intersection search, combine them into one label.

Get label info

# get single label info
synd.get_labels('your_label_name')
# get all labels info
synd.get_labels()

Create/delete label

Label name is unique in drive.

# create a label, color name: gray/red/orange/yellow/green/blue/purple.
# default color is gray, default position is end of labels. 0 is first position.
ret = synd.create_label('your_label_name', color='orange', pos=0)
# delete label by name/id.
ret = synd.delete_label('your_label_name')
ret = synd.delete_label(label_id=419)

Add/delete path label

# acition:add, delete
synd.manage_path_label(action, path, label)

path examples:

1. '/team-folders/test_drive/SCU285/test.xls', '/mydrive/test_sheet_file.osheet'
2. '505415003021516807'
3. ['505415003021516807', '505415003021516817']
4. ["id:505415003021516807", "id:525657984139799470", "id:525657984810888112"]
5. ['/team-folders/test_drive/SCU285/test.xls', '/team-folders/test_drive/SCU283/test2.xls']

label examples:

1. 'label_name'
2. ['label_name_1', 'lable_name_2']
3. [{"action": "add", "label_id": "15"}, {"action": "add", "label_id": "16"}]

List labelled files

Filter files or folders by single label. If you want to use label union search, use search functions (todo).

synd.list_labelled_file(label_name='your_label_name')

Manage File/Folder

Team folder start with /team-folders/, Private folder start with /mydrive/

List TeamFolder

Teamfolder is virtual parent folder of shared folders in Synology drive. When you login in Drive, you can see your authorized shared folder.

synd.get_teamfolder_info()
# {sub_folder_name: folder_id, ...}

List Folder

List Folder or files info of a folder

synd.list_folder('/mydrive')

Get specific folder or file info

Get folder or file info such as created time.

# file_path or file_id "552146100935505098"
synd.get_file_or_folder_info(path_or_path_id)

Create Folder

# create folder in your private folder
synd.create_folder(folder_name)
# create folder in dest folder
synd.create_folder('test', 'team-folder/folder2/')

Upload file

You don't need create folder subfolder before uploading your file.

# prepare your file
file = io.BytesIO(mail_attachment['file'])
# add a file name to file
file.name = strip_file_name(mail_attachment['name'])
ret_upload = synd.upload_file(file, dest_folder_path=dest_folder_path)
# upload to your private folder
ret_upload = synd.upload_file(file)
# custom conflict_action: 'version' to rewrite, 'autorename' to rename. Default: 'version'
ret_upload = synd.upload_file(file, dest_folder_path=dest_folder_path, conflict_action='version')

You can upload xlsx or docx as synology office file.

[**Deprecation hint**] This API will be deprecated in the future. It's recommended to call upload_file and convert_to_online_office by yourself.

# custom upload_conflict_action for upload: 'version' to rewrite, 'autorename' to rename. Default: 'version'
# custom convert_conflict_action for convert: 'version' to rewrite, 'autorename' to rename. Default: 'autorename'
with open('test.xlsx', 'rb') as file:
    nas_client.upload_as_synology_office_file(file, '/mydrive/')

Convert to online office

Transform docx/xlsx/pptx to Synology online office file.

# If delete_original_file is True, origin docx/xlsx/pptx will be deleted after transformed. Default: True
# custom conflict_action: 'version' to rewrite, 'autorename' to rename. Default: 'autorename'
ret_convert = synd.convert_to_online_office(dest_file_path,
                                            delete_original_file=True,
                                            conflict_action='autorename')

Download file

New: Support osheet and odoc extensions.

file_name = 'test.osheet'
bio = synd.download_file(f'/mydrive/{file_name}')
with open(file_name, 'wb') as f:
    f.write(bio.getvalue())

Download Synology office file

import pandas as pd

# download osheet as xlsx and read into pandas dataframe.
bio = synd.download_synology_office_file('/mydrive/test.osheet')  # or
bio = synd.download_file('/mydrive/test.osheet')
pd.read_excel(bio, sheet_name=None)

# dowloand odoc as docx
bio = synd.download_synology_office_file('/mydrive/test.odoc')
with open('test.docx', 'wb') as f:
    f.write(bio.getvalue())

Delete file or folder

Delete file or folder is an async task.

synd.delete_path('/mydrive/abc_folder')
synd.delete_path('598184594644187768')

Rename file or folder

# Rename file '/mydrive/H3_AP201812091265503218_1.pdf' to '/mydrive/new.pdf'
synd.rename_path('new.pdf', '/mydrive/H3_AP201812091265503218_1.pdf')
# Rename folder '/mydrive/test_folder' to '/mydrive/abc_folder'
synd.rename_path('abc_folder', '/mydrive/test_folder')

Share file or folder

Get unique file url.

synd.create_link('team-folders/operation/H3_AP201812091265503218_1.pdf')

synology-drive-api's People

Contributors

bc0403 avatar fengdasuk19 avatar knowncold avatar wjcroom avatar zbjdonald avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

synology-drive-api's Issues

Where can I find the SynologyDrive API documentation?

Hi zbjdonald,

thanks for taking up the task of creating a much needed wrapper for the Synology Drive!
While I was browsing the code, I wondered where you got the documentation for the Drive API from since I couldn't find it myself. Could you point me to the right direction?

Sincerely,
wittenator

请问DMS7在线osheet的转换下载,能加速吗?

RT,我使用api下载一个在线osheet,大小60多MB,从开始下载,到下载完成(下载已转换后的xlsx文件的时间可以忽略),需要4分钟左右。所以请问作者能否加快文档的转换?我使用的是DS920+。谢谢。

Move file to other folder

Hi, I really love your work and it helps me a lot.

I'm trying to move a file to a different folder. In your sourcecode I see a comment

move file or folder to another folder
Is this implemented yet and I just fail to use it or is this still a todo?

Many thanks again!

Error

Hello, can you help me pls, I moved to dsm 7 and now when I connect to a file, I write such an error. What could it be
image_2022-05-06_14-14-30

Clarification about share Labels Instructions

In the README.md you say

If you want share labels between users, you should have access to these user accounts. Another solution is creating a tool user.

While it's clear the meaning of having the access to the user account I cannot understand what do you mean about the "tool user".
Is there some way, with some kind of tool_user, to share labels between users?
Can you help me?

team folder empty and list node failed with synd.list_folder

Hi, Thanks for your good work. I have been using your library for a while but after someone reinstall the Synology NAS in my company. My code using your library no longer works and I cannot figure it out. The major problem is no directories are visible to the library when creating or listing folders.

I create a team folder called "apr" using the admin console. It is under /volume1/ when I login in the Synology Drive using ssh.
However, I get a {} when I try the synd.get_teamfolder_info() command.

No matter what I put in the bracket of synd.list_folder(). I am getting the list node failed with synd.list_folder error.
Some options I have tried are "/volume1", "volume1/apr". "/" gives me a permission error.

Any help would be greatly appreciated.

error 119

I tried to connect to drive. I get always a 119 error

synd.get_info()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python39\lib\site-packages\synology_drive_api\drive.py", line 45, in get_info
    return self.session.http_get(endpoint, params=params)
  File "C:\Python39\lib\site-packages\synology_drive_api\base.py", line 203, in http_get
    return self._request('get', endpoint, **kwargs)
  File "C:\Python39\lib\site-packages\synology_drive_api\base.py", line 196, in _request
    raise_synology_exception(res, bio_exist=bio_flag)
  File "C:\Python39\lib\site-packages\synology_drive_api\base.py", line 118, in raise_synology_exception
    raise SynologyException(
synology_drive_api.base.SynologyException: {"error":{"code":119},"success":false}

No problem with https://github.com/N4S4/synology-api

dsm_version parameter not working

Hi,

dsm_version parameter is not accepted by SynologyDrive class and is not passed to SynologySession. SynologySession dsm_version default value is 6 thus the documentation description is wrong, please update the code.

"update file information failed" when trying to list a file shared with user in question.

I was using the following line of code to access a certain spreadsheet, shared with the user used in the request below. After updating to DSM 7, and updating this python module to latest version, it suddenly stopped working:

with SynologyDrive(os.environ.get('SYNO_USER'), os.environ.get('SYNO_PASS'), os.environ.get('SYNO_HOST'), dsm_version='7') as synd:
    sheet_file = synd.download_file("543138139674295052")

Returns the following error:

Traceback (most recent call last):
  File "./test.py", line 18, in <module>
    sheet_file = synd.download_file("543138139674295052")
  File "/Users/jonas/Library/Python/3.8/lib/python/site-packages/synology_drive_api/files.py", line 151, in download_file
    ret = self.get_file_or_folder_info(file_path)
  File "/Users/jonas/Library/Python/3.8/lib/python/site-packages/synology_drive_api/files.py", line 126, in get_file_or_folder_info
    return self.session.http_post(endpoint, data=urlencoded_data)
  File "/Users/jonas/Library/Python/3.8/lib/python/site-packages/synology_drive_api/base.py", line 220, in http_post
    return self._request('post', endpoint, **kwargs)
  File "/Users/jonas/Library/Python/3.8/lib/python/site-packages/synology_drive_api/base.py", line 210, in _request
    raise_synology_exception(res, bio_exist=bio_flag)
  File "/Users/jonas/Library/Python/3.8/lib/python/site-packages/synology_drive_api/base.py", line 132, in raise_synology_exception
    raise SynologyException(
synology_drive_api.base.SynologyException: {"error":{"code":1003,"errors":{"line":172,"message":"update file information failed"}},"success":false}

Any ideas why this is suddenly happening?

connect with Quickconnect link on DSM 7

Hello

The api works fine with IP on local network 192.168.X.Y
Is there a possibility to make it work with quickconnect link from internet ?

I couldn't find the right syntax so far
I'm trying
NAS_USER = 'mylogin'
NAS_PASS = 'mypassword'
NAS_path = 'https://quickconnect.to/nasname/drive/'
with SynologyDrive(NAS_USER, NAS_PASS, NAS_path, dsm_version='7') as synd:

Thanks

Can you add IMPORTRANGE manual update?

Hi! I have found method with F12+Chrome called SYNO.Office.Sheet.Snapshot. It is working when updating links between sheets in Synology, running IMPORTRANGE function. Can we repeat this manually with API call?

Add OTP support

I have OTP enabled for my NAS wich leads to an Execption of type otp when attempting to create a SynologyDrive instance.

Are you planning on supporting OTP?

Overwriting when upload files

Hi! Thanks for the great work!

In the original API there's argument overwrite for SYNO.FileStation.Upload method. I am going to move my data from Google Sheets to Synology Office and have many scripts working with gsheets now. So if there's no option to work with osheet like with Gsheets API (inserting rows, lists, remove rows, e.t.c), I think I could manage all scripts to work inside excel and then reupload it in Synology with osheet format. But .upload_file() method creating new files in Drive instead of overwriting old ones with the same name.

Any help or advice? Thanks in advance

synd.create_link error! Not support & character

Hello,

I am trying to use (synd.create_link) function to get a unique file URL, but I found that if my folder includes & such as Anniversary Statements & Illustration then will show the below error message.

{"error":{"code":1000,"errors":{"line":61,"message":"use link failed"}},"success":false}

May I know is it possible to support "&" character when i call (synd.create_link) function?

Thank you.

Copy fails when it is not a synology office file

Copy works well for synology office files like:

synd.copy("/mydrive/test.odoc","/mydrive/tests/test.odoc")

Always gives error for other files:

synd.copy("/mydrive/test.pdf","/mydrive/tests/test.pdf")

Using SYNO.SynologyDrive.Files in the code solve the issue for me, I don't know if this could be included/replace in files.py:

`def copy(self, source: str, dist: str) -> dict:
"""

    copy file or dir

    :param source : id:23333333333  or "'team-folders/folder2/'"

    :param dist: "'team-folders/folder2/temp.odoc'"

    """

    api_name = "SYNO.SynologyDrive.Files"

    endpoint = 'entry.cgi'

    distpath, distname = os.path.split(dist)

    params = {'api': api_name, 'version': 2, 'method': 'copy',

              'to_parent_folder': distpath, 'to_parent_name': distname,

              'conflict_action': 'autorename', 

              'files': f'["{source}"]'}

    return self.session.http_put(endpoint, params=params)

`

I encountered exceptions when invoking each API

like this:
raise SynologyException(
synology_drive_api.base.SynologyException: {"error":{"code":1000,"errors":{"line":107,"message":"list node failed"}},"success":false}

My Synology version is DSM 7.1-42661

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.