将Zoom录音下载到本地机器,并使用可恢复上传法将视频上传到Google Drive。

问题描述 投票:0回答:1

我在Python3中建立了一个函数,它将从Google电子表格中检索数据。数据将包含记录的Download_URL和其他信息。

该函数将下载录音并将其存储在本地机器中。一旦视频被保存,函数将使用Resumable Upload方法将其上传到Google Drive。

尽管Resumable Upload方法的响应是200,并且它也给了我文件的Id,但我似乎在Google Drive的任何地方都找不到这个文件。下面是我的代码。

import os
import requests
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials

DOWNLOAD_DIRECTORY = 'Parent_Folder'

def upload_recording(file_location,file_name):
    filesize = os.path.getsize(file_location)

    # Retrieve session for resumable upload.

    headers = {"Authorization": "Bearer " + access_token, "Content-Type": "application/json"}
    params = {
        "name": file_name,
        "mimeType": "video/mp4"
    }
    r = requests.post(
        "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
        headers=headers,
        data=json.dumps(params)
    )
    print(r)
    location = r.headers['Location']

    # Upload the file.

    headers = {"Content-Range": "bytes 0-" + str(filesize - 1) + "/" + str(filesize)}
    r = requests.put(
        location,
        headers=headers,
        data=open(file_location, 'rb')
    )
    print(r.text)
    return True

def download_recording(download_url, foldername, filename):
    upload_success = False
    dl_dir = os.sep.join([DOWNLOAD_DIRECTORY, foldername])
    full_filename = os.sep.join([dl_dir, filename])
    os.makedirs(dl_dir, exist_ok=True)

    response = requests.get(download_url, stream=True)
    try:
        with open(full_filename, 'wb') as fd:
            for chunk in response.iter_content(chunk_size=512 * 1024):
                fd.write(chunk)
        upload_success = upload_recording(full_filename,filename)
        return upload_success
    except Exception as e:
        # if there was some exception, print the error and return False
        print(e)
        return upload_success

def main():
    scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/spreadsheets",
             "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]
    creds = ServiceAccountCredentials.from_json_keyfile_name('creds.json', scope)
    client = gspread.authorize(creds)
    sheet = client.open("Zoom Recordings Data").sheet1
    data = sheet.get_all_records()

    # Get the Recordings information that are needed to download
    for index in range(len(sheet.col_values(9))+1 ,len(data)+2):
        success = False
        getRow = sheet.row_values(index)
        session_name = getRow[0]
        topic = getRow[1]
        topic = topic.replace('/', '')
        topic = topic.replace(':', '')
        account_name = getRow[2]
        start_date = getRow[3]
        file_size = getRow[4]
        file_type = getRow[5]
        url_token = getRow[6] + '?access_token=' + getRow[7]

        file_name = start_date + ' - ' + topic + '.' + file_type.lower()
        file_destination = session_name + '/' + account_name + '/' + topic

        success |= download_recording(url_token, file_destination, file_name)

        # Update status on Google Sheet
        if success:
            cell = 'I' + str(index)
            sheet.update_acell(cell,'success')

if __name__ == "__main__":
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        'creds.json',
        scopes='https://www.googleapis.com/auth/drive'
    )

    delegated_credentials = credentials.create_delegated('Service_Account_client_email')

    access_token = delegated_credentials.get_access_token().access_token
    main()

我还在试图找出如何将视频上传到需要的文件夹中。我对Python和Drive API很陌生。如果你能给我一些建议,我会非常感激。

python-3.x google-drive-api
1个回答
2
投票

这个答案怎么样?

问题和解决方案。

尽管Resumable Upload方法的响应是200,并且它也给了我文件的Id,但我似乎无法在Google Drive的任何地方找到这个文件。下面是我的代码。

我认为你的脚本对于可恢复上传是正确的。从你上面的情况和你的脚本中,我了解到你的脚本是有效的,文件已经可以用可恢复上传的方式上传到Google Drive。

而且,当我看到你的问题的 I can't seem to find the file anywhere in my Google Drive 和你的脚本,我注意到你是用服务账户获取的访问令牌上传文件。在这种情况下,上传的文件被放到了服务账户的驱动器上。你的Google Drive和服务账户的Drive是不同的。这样,你就不能用浏览器看到上传的文件了。在这种情况下,我想提出以下2种方法。

模式1.上传文件的所有者是谁?

上传文件的所有者是服务账户。在这种情况下,将上传的文件与Google账户共享。功能 upload_recording 修改如下。并请将您的谷歌账户的电子邮件地址设置为 emailAddress.

修改后的脚本。

def upload_recording(file_location, file_name):
    filesize = os.path.getsize(file_location)

    # Retrieve session for resumable upload.

    headers1 = {"Authorization": "Bearer " + access_token, "Content-Type": "application/json"}  # Modified
    params = {
        "name": file_name,
        "mimeType": "video/mp4"
    }
    r = requests.post(
        "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable",
        headers=headers1,  # Modified
        data=json.dumps(params)
    )
    print(r)
    location = r.headers['Location']

    # Upload the file.

    headers2 = {"Content-Range": "bytes 0-" + str(filesize - 1) + "/" + str(filesize)}  # Modified
    r = requests.put(
        location,
        headers=headers2,  # Modified
        data=open(file_location, 'rb')
    )

    # I added below script.
    fileId = r.json()['id']
    permissions = {
        "role": "writer",
        "type": "user",
        "emailAddress": "###"  # <--- Please set your email address of your Google account.
    }
    r2 = requests.post(
        "https://www.googleapis.com/drive/v3/files/" + fileId + "/permissions",
        headers=headers1,
        data=json.dumps(permissions)
    )
    print(r2.text)
    return True
  • 当你运行上述修改后的脚本时,你可以在你的Google Drive的 "Shared with me "看到上传的文件。

模式2.将文件上传到共享文件夹

在这个模式中,文件被上传到共享文件夹 使用服务帐户的可恢复上传。所以 起初,请在您的Google Drive中准备一个文件夹,并将该文件夹与服务账号的邮箱共享。

修改后的脚本。

请修改功能 upload_recording 如下所示。并请设置你与服务账号共享的文件夹ID。

发件人
params = {
    "name": file_name,
    "mimeType": "video/mp4"
}
收件人:
params = {
    "name": file_name,
    "mimeType": "video/mp4",
    "parents": ["###"]  # <--- Please set the folder ID you shared with the service account.
}
  • 当你运行上述修改后的脚本时,你可以在你的Google Drive的共享文件夹中看到上传的文件。

注意:在这种情况下,文件的所有者是Google Drive的用户。

  • 在这种情况下,所有者是服务账户,当然,所有者也可以是修改后的账户。当然,所有者也可以更改。

参考文献

© www.soinside.com 2019 - 2024. All rights reserved.