feat(google-drive): new Google Drive integration

Drive API v3 (25 commands): shared drive management, change tracking,
Drive activity queries, file search/get/create/upload/download/copy/
move/delete, permission list/create/update/delete, and Drive labels.
Service-account auth with domain-wide delegation (JWT RS256), runs on
a remote engine (requires PyJWT + cryptography).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Guillaume BOURGEOIS
2026-07-10 23:17:58 +02:00
parent dbb740f476
commit 3f754d14e9
26 changed files with 2592 additions and 0 deletions
@@ -0,0 +1,84 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive.activity.readonly"]
ACTIVITY_URL = "https://driveactivity.googleapis.com/v2/activity:query"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
body = {}
for key, field in (("item_name", "itemName"),
("folder_name", "ancestorName"),
("filter", "filter"),
("page_token", "pageToken"),
("page_size", "pageSize")):
val = inputs.get(key)
if val not in (None, ""):
body[field] = val
res = request("POST", ACTIVITY_URL, SCOPES, body=body, subject=inputs.get("user_id"))
print(json.dumps(res))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,97 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
page_token = inputs.get("page_token")
if not page_token:
raise Exception("page_token is required")
params = {
"pageToken": page_token,
"driveId": inputs.get("drive_id"),
"pageSize": inputs.get("page_size") or 100,
"supportsAllDrives": "true",
"spaces": inputs.get("spaces"),
}
include_removed = inputs.get("include_removed")
if include_removed in (None, ""):
params["includeRemoved"] = "true"
else:
params["includeRemoved"] = "true" if str(include_removed).lower() in ("1", "true", "yes") else "false"
for key, param in (("include_items_from_all_drives", "includeItemsFromAllDrives"),
("restrict_to_my_drive", "restrictToMyDrive")):
val = inputs.get(key)
if val not in (None, ""):
params[param] = "true" if str(val).lower() in ("1", "true", "yes") else "false"
if inputs.get("fields") == "advance":
params["fields"] = "*"
res = request("GET", BASE + "/changes", SCOPES, params=params, subject=inputs.get("user_id"))
print(json.dumps(res))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,80 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
params = {
"driveId": inputs.get("drive_id"),
"supportsAllDrives": "true",
}
res = request("GET", BASE + "/changes/startPageToken", SCOPES,
params=params, subject=inputs.get("user_id"))
print(json.dumps(res))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,86 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import uuid
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
name = inputs.get("name")
if not name:
raise Exception("name is required")
body = {"name": name}
hidden = inputs.get("hidden")
if hidden not in (None, ""):
body["hidden"] = str(hidden).lower() in ("1", "true", "yes")
res = request("POST", BASE + "/drives", SCOPES,
params={"requestId": str(uuid.uuid4())},
body=body, subject=inputs.get("user_id"))
print(json.dumps(res))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,87 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
drive_id = inputs.get("drive_id")
if not drive_id:
raise Exception("drive_id is required")
params = {}
for key, param in (("use_domain_admin_access", "useDomainAdminAccess"),
("allow_item_deletion", "allowItemDeletion")):
val = inputs.get(key)
if val not in (None, ""):
params[param] = "true" if str(val).lower() in ("1", "true", "yes") else "false"
res = request("DELETE", BASE + "/drives/" + urllib.parse.quote(str(drive_id), safe=""), SCOPES,
params=params, subject=inputs.get("user_id"))
if not res:
res = {"ok": True, "drive_id": drive_id}
print(json.dumps(res))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,82 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
drive_id = inputs.get("drive_id")
if not drive_id:
raise Exception("drive_id is required")
params = {"fields": "*"}
if str(inputs.get("use_domain_admin_access", "")).lower() in ("1", "true", "yes"):
params["useDomainAdminAccess"] = "true"
res = request("GET", BASE + "/drives/" + urllib.parse.quote(str(drive_id), safe=""), SCOPES,
params=params, subject=inputs.get("user_id"))
print(json.dumps(res))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,83 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
params = {
"q": inputs.get("query"),
"pageSize": inputs.get("page_size") or 100,
"pageToken": inputs.get("page_token"),
"fields": "*",
}
if str(inputs.get("use_domain_admin_access", "")).lower() in ("1", "true", "yes"):
params["useDomainAdminAccess"] = "true"
res = request("GET", BASE + "/drives", SCOPES, params=params, subject=inputs.get("user_id"))
print(json.dumps(res))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,90 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
if not file_id:
raise Exception("file_id is required")
subject = inputs.get("user_id")
copy_title = inputs.get("copy_title")
body = {"name": copy_title} if copy_title else {}
result = request(
"POST",
BASE + "/files/" + urllib.parse.quote(file_id, safe="") + "/copy",
SCOPES,
params={"supportsAllDrives": "true", "fields": "*"},
body=body,
subject=subject,
)
print(json.dumps(result))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,88 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_name = inputs.get("file_name")
if not file_name:
raise Exception("file_name is required")
body = {
"name": file_name,
"mimeType": inputs.get("mime_type") or "application/vnd.google-apps.folder",
}
if inputs.get("parent"):
body["parents"] = [inputs["parent"]]
if inputs.get("description"):
body["description"] = inputs["description"]
params = {"supportsAllDrives": "true", "fields": "*"}
res = request("POST", BASE + "/files", SCOPES, params=params, body=body,
subject=inputs.get("user_id"))
print(json.dumps(res))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,98 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
if not file_id:
raise Exception("file_id is required")
subject = inputs.get("user_id")
if inputs.get("soft_delete"):
result = request(
"PATCH",
BASE + "/files/" + urllib.parse.quote(file_id, safe=""),
SCOPES,
params={"supportsAllDrives": "true", "fields": "id,name,trashed,trashedTime"},
body={"trashed": True},
subject=subject,
)
print(json.dumps(result))
return
request(
"DELETE",
BASE + "/files/" + urllib.parse.quote(file_id, safe=""),
SCOPES,
params={"supportsAllDrives": "true"},
subject=subject,
)
print(json.dumps({"ok": True, "file_id": file_id}))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,102 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
import base64
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
if not file_id:
raise Exception("file_id is required")
subject = inputs.get("user_id")
meta = request(
"GET",
BASE + "/files/" + urllib.parse.quote(file_id, safe=""),
SCOPES,
params={"fields": "id,name,mimeType,size", "supportsAllDrives": "true"},
subject=subject,
)
url = (BASE + "/files/" + urllib.parse.quote(file_id, safe="")
+ "?alt=media&supportsAllDrives=true")
headers = {"Authorization": "Bearer " + _token(SCOPES, subject)}
req = urllib.request.Request(url, headers=headers, method="GET")
with urllib.request.urlopen(req, timeout=300) as r:
content = r.read()
print(json.dumps({
"id": meta.get("id"),
"file_name": meta.get("name"),
"mime_type": meta.get("mimeType"),
"size": len(content),
"content_base64": base64.b64encode(content).decode("ascii"),
}))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,83 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
if not file_id:
raise Exception("file_id is required")
params = {
"fields": inputs.get("fields") or "*",
"supportsAllDrives": "true",
}
res = request("GET", BASE + "/files/" + urllib.parse.quote(str(file_id), safe=""), SCOPES,
params=params, subject=inputs.get("user_id"))
print(json.dumps(res))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,86 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
if not file_id:
raise Exception("file_id is required")
subject = inputs.get("user_id")
result = request(
"GET",
BASE + "/files/" + urllib.parse.quote(file_id, safe=""),
SCOPES,
params={"fields": "id,parents", "supportsAllDrives": "true"},
subject=subject,
)
print(json.dumps(result))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,98 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
add_parent_id = inputs.get("add_parent_id")
remove_parent_id = inputs.get("remove_parent_id")
if not file_id:
raise Exception("file_id is required")
if not add_parent_id:
raise Exception("add_parent_id is required")
if not remove_parent_id:
raise Exception("remove_parent_id is required")
subject = inputs.get("user_id")
result = request(
"PATCH",
BASE + "/files/" + urllib.parse.quote(file_id, safe=""),
SCOPES,
params={
"addParents": add_parent_id,
"removeParents": remove_parent_id,
"supportsAllDrives": "true",
"fields": "*",
},
body={},
subject=subject,
)
print(json.dumps(result))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,96 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
import base64, mimetypes
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
content_base64 = inputs.get("content_base64")
if not file_id:
raise Exception("file_id is required")
if not content_base64:
raise Exception("content_base64 is required")
subject = inputs.get("user_id")
content = base64.b64decode(content_base64)
content_type = mimetypes.guess_type(inputs.get("file_name") or "")[0] or "application/octet-stream"
url = ("https://www.googleapis.com/upload/drive/v3/files/"
+ urllib.parse.quote(file_id, safe="")
+ "?uploadType=media&supportsAllDrives=true&fields=*")
headers = {
"Accept": "application/json",
"Authorization": "Bearer " + _token(SCOPES, subject),
"Content-Type": content_type,
}
req = urllib.request.Request(url, data=content, headers=headers, method="PATCH")
with urllib.request.urlopen(req, timeout=120) as r:
print(json.dumps(json.loads(r.read())))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,114 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
import base64, mimetypes
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_name = inputs.get("file_name")
content_base64 = inputs.get("content_base64")
if not file_name:
raise Exception("file_name is required")
if not content_base64:
raise Exception("content_base64 is required")
subject = inputs.get("user_id")
content = base64.b64decode(content_base64)
content_type = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
# Step 1: upload raw content
upload_url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=media&supportsAllDrives=true"
headers = {
"Accept": "application/json",
"Authorization": "Bearer " + _token(SCOPES, subject),
"Content-Type": content_type,
}
req = urllib.request.Request(upload_url, data=content, headers=headers, method="POST")
with urllib.request.urlopen(req, timeout=120) as r:
created = json.loads(r.read())
file_id = created.get("id")
if not file_id:
raise Exception("Upload did not return a file id: " + json.dumps(created))
# Step 2: set the name (and parent, if any)
result = request(
"PATCH",
BASE + "/files/" + urllib.parse.quote(file_id, safe=""),
SCOPES,
params={
"addParents": inputs.get("parent") or None,
"supportsAllDrives": "true",
"fields": "*",
},
body={"name": file_name},
subject=subject,
)
print(json.dumps(result))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,91 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
drive_id = inputs.get("drive_id")
corpora = inputs.get("corpora") or "user"
if drive_id:
corpora = "drive"
params = {
"q": inputs.get("query"),
"pageSize": inputs.get("page_size") or 100,
"pageToken": inputs.get("page_token"),
"driveId": drive_id,
"corpora": corpora,
"supportsAllDrives": "true",
"fields": "*",
}
val = inputs.get("include_items_from_all_drives")
if val not in (None, ""):
params["includeItemsFromAllDrives"] = "true" if str(val).lower() in ("1", "true", "yes") else "false"
res = request("GET", BASE + "/files", SCOPES, params=params, subject=inputs.get("user_id"))
print(json.dumps(res))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,85 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.labels"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
if not file_id:
raise Exception("file_id is required")
subject = inputs.get("user_id")
result = request(
"GET",
BASE + "/files/" + urllib.parse.quote(file_id, safe="") + "/listLabels",
SCOPES,
subject=subject,
)
print(json.dumps(result))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,82 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.labels"]
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
subject = inputs.get("user_id")
result = request(
"GET",
"https://drivelabels.googleapis.com/v2/labels",
SCOPES,
params={"view": "LABEL_VIEW_FULL"},
subject=subject,
)
print(json.dumps(result))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,98 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.labels"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
label_id = inputs.get("label_id")
if not file_id:
raise Exception("file_id is required")
if not label_id:
raise Exception("label_id is required")
subject = inputs.get("user_id")
mod = {"kind": "drive#labelModification", "labelId": label_id, "removeLabel": bool(inputs.get("remove_label"))}
if inputs.get("field_id"):
mod["fieldModifications"] = [{
"kind": "drive#labelFieldModification",
"fieldId": inputs["field_id"],
"setSelectionValues": [inputs.get("selection_label_id")] if inputs.get("selection_label_id") else [],
}]
body = {"kind": "drive#modifyLabelsRequest", "labelModifications": [mod]}
result = request(
"POST",
BASE + "/files/" + urllib.parse.quote(file_id, safe="") + "/modifyLabels",
SCOPES,
body=body,
subject=subject,
)
print(json.dumps(result))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,106 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
if not file_id:
raise Exception("file_id is required")
subject = inputs.get("user_id")
body = {}
for key, value in (
("role", inputs.get("role") or "reader"),
("type", inputs.get("type") or "user"),
("emailAddress", inputs.get("email_address")),
("domain", inputs.get("domain")),
):
if value:
body[key] = value
params = {"supportsAllDrives": "true", "fields": "*"}
for src, dst in (
("send_notification_email", "sendNotificationEmail"),
("transfer_ownership", "transferOwnership"),
("move_to_new_owners_root", "moveToNewOwnersRoot"),
):
if src in inputs and inputs[src] is not None:
params[dst] = "true" if inputs[src] else "false"
result = request(
"POST",
BASE + "/files/" + urllib.parse.quote(file_id, safe="") + "/permissions",
SCOPES,
params=params,
body=body,
subject=subject,
)
print(json.dumps(result))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,90 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
permission_id = inputs.get("permission_id")
if not file_id:
raise Exception("file_id is required")
if not permission_id:
raise Exception("permission_id is required")
subject = inputs.get("user_id")
request(
"DELETE",
BASE + "/files/" + urllib.parse.quote(file_id, safe="")
+ "/permissions/" + urllib.parse.quote(permission_id, safe=""),
SCOPES,
params={"supportsAllDrives": "true"},
subject=subject,
)
print(json.dumps({"ok": True, "permission_id": permission_id}))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,99 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
permission_id = inputs.get("permission_id")
if not file_id:
raise Exception("file_id is required")
if not permission_id:
raise Exception("permission_id is required")
subject = inputs.get("user_id")
body = {}
if inputs.get("role"):
body["role"] = inputs["role"]
if inputs.get("expiration_time"):
body["expirationTime"] = inputs["expiration_time"]
if not body:
raise Exception("nothing to update")
result = request(
"PATCH",
BASE + "/files/" + urllib.parse.quote(file_id, safe="")
+ "/permissions/" + urllib.parse.quote(permission_id, safe=""),
SCOPES,
params={"supportsAllDrives": "true", "fields": "*"},
body=body,
subject=subject,
)
print(json.dumps(result))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,95 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
inputs = json.loads(os.environ.get("INTEGRATION_INPUTS", "{}"))
file_id = inputs.get("file_id")
if not file_id:
raise Exception("file_id is required")
subject = inputs.get("user_id")
params = {
"pageSize": inputs.get("page_size") or 100,
"pageToken": inputs.get("page_token"),
"supportsAllDrives": "true",
"fields": "*",
}
if inputs.get("use_domain_admin_access"):
params["useDomainAdminAccess"] = "true"
result = request(
"GET",
BASE + "/files/" + urllib.parse.quote(file_id, safe="") + "/permissions",
SCOPES,
params=params,
subject=subject,
)
print(json.dumps(result))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)
@@ -0,0 +1,76 @@
import json, os, sys, time, urllib.parse, urllib.request, urllib.error
import jwt
TOKEN_URL = "https://oauth2.googleapis.com/token"
def _cfg():
return json.loads(os.environ.get("INTEGRATION_SECRETS", "{}"))
def _token(scopes, subject=None):
cfg = _cfg()
raw = cfg.get("service_account_json", "")
sa = json.loads(raw) if isinstance(raw, str) else raw
if not sa.get("client_email") or not sa.get("private_key"):
raise Exception("service_account_json must contain client_email and private_key")
now = int(time.time())
aud = sa.get("token_uri") or TOKEN_URL
payload = {
"iss": sa["client_email"],
"scope": " ".join(scopes),
"aud": aud,
"iat": now,
"exp": now + 3600,
}
sub = subject or cfg.get("user_id") or ""
if sub:
payload["sub"] = sub
assertion = jwt.encode(payload, sa["private_key"], algorithm="RS256")
data = urllib.parse.urlencode({
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": assertion,
}).encode("utf-8")
req = urllib.request.Request(aud, data=data,
headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST")
with urllib.request.urlopen(req, timeout=60) as r:
tok = json.loads(r.read())
if not tok.get("access_token"):
raise Exception("Token request failed: " + json.dumps(tok))
return tok["access_token"]
def request(method, url, scopes, params=None, body=None, subject=None):
q = {k: str(x) for k, x in (params or {}).items() if x not in (None, "")}
if q:
url += ("&" if "?" in url else "?") + urllib.parse.urlencode(q)
data = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"Accept": "application/json", "Authorization": "Bearer " + _token(scopes, subject)}
if data is not None:
headers["Content-Type"] = "application/json"
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=90) as r:
raw = r.read()
return json.loads(raw) if raw else {}
SCOPES = ["https://www.googleapis.com/auth/drive"]
BASE = "https://www.googleapis.com/drive/v3"
def main():
res = request("GET", BASE + "/about", SCOPES, params={"fields": "user"})
if "user" not in res:
raise Exception("Unexpected response from Drive API: " + json.dumps(res))
print(json.dumps({"ok": True, "user": res.get("user", {}).get("emailAddress", "")}))
try:
main()
except urllib.error.HTTPError as e:
print(json.dumps({"error": "HTTP " + str(e.code), "detail": e.read().decode("utf-8", "replace")}))
sys.exit(1)
except Exception as e:
print(json.dumps({"error": str(e)}))
sys.exit(1)