File size: 4,058 Bytes
7ce8db8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
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
from oauth2client import client
import base64
import datetime
import json

import flask
from flask import request, Response
import requests
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
import src.functions.config

downloadBP = flask.Blueprint("download", __name__)


def save_response_content(response, destination):
    CHUNK_SIZE = 32768

    with open(destination, "wb") as f:
        for chunk in response.iter_content(CHUNK_SIZE):
            if chunk:  # filter out keep-alive new chunks
                f.write(chunk)


@downloadBP.route("/api/v1/download/<name>")
async def downloadFunction(name):
    a = flask.request.args.get("a")  # AUTH
    config = src.functions.config.readConfig()

    gauth = GoogleAuth()
    content = '{"access_token": "ya29.a0AXooCgtLK5HzYMtRs4R9J7FRZSGR3i5jUkeMeVhGjorlrgq_BupFi8d9upA2skYC5FofxUqo23Nivk_P_Hy8eRn0DWM3deSKoiWMhA3lsy05JVakD0vd2fPRaFOXfRV20jAEGt6ql9yy_0up3Y9z8u9yXZ28IUxRRZAHaCgYKASQSARISFQHGX2MipVyGD4fFFZJWXGvyd-sJnQ0171", "client_id": "895306463817-h14aujg3ohgptue5safg2d81530qs4c3.apps.googleusercontent.com", "client_secret": "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", "refresh_token": "1//0gsu0CorccmScCgYIARAAGBASNwF-L9IrF-TDYDXR_MTQGAGGf4fY4BBBSBUipsz_7c0B6HjmRYZV3uxPVU4CAJjqWoWBm0T4pxA", "token_expiry": "2024-05-25T11:14:56Z", "token_uri": "https://oauth2.googleapis.com/token", "user_agent": null, "revoke_uri": "https://oauth2.googleapis.com/revoke", "id_token": null, "id_token_jwt": null, "token_response": {"access_token": "ya29.a0AXooCgtLK5HzYMtRs4R9J7FRZSGR3i5jUkeMeVhGjorlrgq_BupFi8d9upA2skYC5FofxUqo23Nivk_P_Hy8eRn0DWM3deSKoiWMhA3lsy05JVakD0vd2fPRaFOXfRV20jAEGt6ql9yy_0up3Y9z8u9yXZ28IUxRRZAHaCgYKASQSARISFQHGX2MipVyGD4fFFZJWXGvyd-sJnQ0171", "expires_in": 3599, "refresh_token": "1//0gsu0CorccmScCgYIARAAGBASNwF-L9IrF-TDYDXR_MTQGAGGf4fY4BBBSBUipsz_7c0B6HjmRYZV3uxPVU4CAJjqWoWBm0T4pxA", "scope": "https://www.googleapis.com/auth/drive", "token_type": "Bearer"}, "scopes": ["https://www.googleapis.com/auth/drive"], "token_info_uri": "https://oauth2.googleapis.com/tokeninfo", "invalid": false, "_class": "OAuth2Credentials", "_module": "oauth2client.client"}'
    gauth.credentials = client.Credentials.new_from_json(content)
    if gauth.access_token_expired:
        # Refresh them if expired
        gauth.Refresh()
    else:
        gauth.Authorize()
    DRIVE = GoogleDrive(gauth)

    def download_file(response):
        print("Started Streamming")
        for chunk in response.iter_content(4096):
            yield chunk

    def get_confirm_token(response):
        for key, value in response.cookies.items():
            if key.startswith("download_warning"):
                return value

        return None

    if (
        datetime.datetime.strptime(
            config.get("token_expiry", datetime.datetime.utcnow()),
            "%Y-%m-%d %H:%M:%S.%f",
        )
        <= datetime.datetime.utcnow()
    ):
        config, drive = src.functions.credentials.refreshCredentials(config)
        #with open("config.json", "w+") as w:
        #    json.dump(obj=config, fp=w, sort_keys=True, indent=4)

    file_id = flask.request.args.get("id")
    file_obj = DRIVE.CreateFile({'id': file_id})
    file_obj.Upload()
    download_url = file_obj.metadata.get('downloadUrl')
    # download_url = download_url.replace("v2", "v3").replace("&source=downloadUrl", "") + "&supportsAllDrives=true&key=AIzaSyDF0v4AzL3y0beyAadnhbF131CGVlFpFOo"
    print(download_url)
    try:
        file_obj.http = file_obj.auth.Get_Http_Object()
        credentials = file_obj.http.request.credentials.__dict__
        # response = requests.get(download_url, stream=True)
        response = requests.get(download_url, headers={'Authorization': f'{credentials["token_response"]["token_type"]} {credentials["access_token"]}'}, stream=True)

        return download_file(response), {"Content-Type": "video/mp4"}
        # return flask.Response(
        #     flask.stream_with_context(download_file(response))
        # )
    except Exception as e:
        print("error", e)