boring_edu_doc/Scripts/python/Library/gdoc.py

127 lines
4.5 KiB
Python
Raw Normal View History

2024-03-12 22:15:06 +07:00
# coding: utf-8
from __future__ import unicode_literals
import os.path, time
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from pprint import pprint
import requests
from urllib.parse import urlparse
class gdoc:
def __init__(self):
'''
Args :
templateId : get the id from link GoogleForm
'''
self.image_temp_service_url = "https://tmpfiles.org/api/v1/upload"
# self.image_temp_service_url = "https://uguu.se/upload.php"
self.submition = {"requests":[]}
self.docs_service = None
self.main_docs = None
2024-03-12 22:15:06 +07:00
self.infoPrint = self._defaultPrint
self.progress = -1
self.resultUri = ""
self.savePath = './'
self.questionKey = []
2024-03-12 22:15:06 +07:00
def setProgress(self, i : int):
self.progress = i
def setSavePath(self, path):
self.savePath = path
def AttachProcessInfo(self, callback):
self.infoPrint = callback
def _defaultPrint(self, text : str, progress: int):
print("{}% {}".format(progress, text))
def generateService(self):
''' Start Tokenizing
here is the way to get token
link : https://developers.google.com/docs/api/quickstart/python
'''
SCOPES = ["https://www.googleapis.com/auth/documents",]
2024-03-12 22:15:06 +07:00
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
self.infoPrint("token already exist",self.progress)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
self.infoPrint("refresh token",self.progress)
else:
flow = InstalledAppFlow.from_client_secrets_file(
self.savePath+'/secret/client_secret.json', SCOPES)
2024-03-12 22:15:06 +07:00
creds = flow.run_local_server(port=0)
self.infoPrint("generate token",self.progress)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
try:
self.infoPrint("creating service",self.progress)
self.docs_service = build('docs', 'v1', credentials=creds)
2024-03-12 22:15:06 +07:00
except HttpError as err:
print(err)
''' End Tokenizing
'''
def createDocs(self, name):
2024-03-12 22:15:06 +07:00
try:
self.infoPrint("creating document",self.progress)
self.main_docs = self.docs_service.documents().create(body={"title":name}).execute()
2024-03-12 22:15:06 +07:00
except HttpError as error:
print('An error occurred: %s' % error)
def createOption(self, value, image=None):
self.infoPrint("creating option",self.progress)
opt = {
'insertText' : {
'location':{
'index': 1,
},
'text': "\t{}\r\n".format(value)
}
}
2024-03-12 22:15:06 +07:00
return opt
def createQuestion(self, title, description, options, indexAnswer, itemImage=None):
self.infoPrint("create question...",self.progress)
item = [{
'insertText' : {
'location':{
'index': 1,
},
'text': "{}\r\n".format(description)
}
}]
item = list(reversed(options)) + item
self.questionKey.append(indexAnswer)
2024-03-12 22:15:06 +07:00
return item
def submitItem(self, index, item):
self.infoPrint("submit question",self.progress)
self.submition['requests'].append(item)
question_setting = self.docs_service.documents().batchUpdate(documentId=self.main_docs["documentId"], body=self.submition).execute()
2024-03-12 22:15:06 +07:00
print(self.submition)
print(question_setting)
def update(self):
self.infoPrint("Updating Docs...",self.progress)
2024-03-12 22:15:06 +07:00
# Prints the result to show the question has been added
get_result = self.docs_service.documents().get(documentId=self.main_docs["documentId"]).execute()
# self.resultUri = get_result['responderUri']
2024-03-12 22:15:06 +07:00
print(get_result)
self.infoPrint("Updating Form... Done",self.progress)