# 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) opttxt = "\t{}\r\n".format(value) opt = [{'insertText' : { 'location':{ 'index': 1, }, 'text': opttxt }}] if(image != None): self.infoPrint("uploading option image... ",self.progress) req = requests.post(self.image_temp_service_url,files={"file": open(image,'rb')}) if(req.json()['status'] == 'error'): raise Exception("upload failed : {}".format(req.json())) time.sleep(3) self.infoPrint("uploading option image... ok",self.progress) u = urlparse(req.json()['data']['url']) opt.append( { 'insertInlineImage' : { 'uri' : u._replace(path="/dl"+u.path).geturl(), 'location' : { 'index' : len(opttxt)-1}} }) return opt def createQuestion(self, title, description, options, indexAnswer, itemImage=None): self.infoPrint("create question...",self.progress) itemtxt = "{}\r\n".format(description) item = [{'insertText' : { 'text': itemtxt, 'location':{'index': 1,}}}] if (itemImage != None): self.infoPrint("uploading question image...",self.progress) req = requests.post(self.image_temp_service_url,files={"file": open(itemImage,'rb')}) if(req.json()['status'] == 'error'): raise Exception("upload failed : {}".format(req.json())) time.sleep(3) self.infoPrint("uploading question image... ok",self.progress) u = urlparse(req.json()['data']['url']) item.append( { 'insertInlineImage' : { 'uri' : u._replace(path="/dl"+u.path).geturl(), 'location' : { 'index' : len(itemtxt)-1 }} }) item = list(reversed(options)) + item self.questionKey.append(indexAnswer) return item def submitItem(self, index, item): self.infoPrint("submit question",self.progress) for _item in item : submition = {} submition["requests"] = _item print(submition) r = self.docs_service.documents().batchUpdate(documentId=self.main_docs["documentId"], body=submition).execute() print(r) 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 = self.main_docs["documentId"] self.infoPrint("Updating Form... Done",self.progress)