# 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 self.infoPrint = self._defaultPrint self.progress = -1 self.resultUri = "" self.savePath = './' self.questionKey = [] 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",] 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) 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) except HttpError as err: print(err) ''' End Tokenizing ''' def createDocs(self, name): try: self.infoPrint("creating document",self.progress) self.main_docs = self.docs_service.documents().create(body={"title":name}).execute() 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) } } 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) 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() print(self.submition) print(question_setting) def update(self): self.infoPrint("Updating Docs...",self.progress) # 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'] print(get_result) self.infoPrint("Updating Form... Done",self.progress)