X-Git-Url: https://git.cworth.org/git?a=blobdiff_plain;f=turbot%2Fsheets.py;h=9f8b7c3e0d38eabb0fd08332b684ea39789fea66;hb=3f380c6d5227b99d703d5c8ed3c753e4d179415a;hp=3d527359dda460f9a622b875a6acbb61de7c5a33;hpb=69ac593440ed9cb320ffcd7d10b2c2c75dceb819;p=turbot diff --git a/turbot/sheets.py b/turbot/sheets.py index 3d52735..9f8b7c3 100644 --- a/turbot/sheets.py +++ b/turbot/sheets.py @@ -1,47 +1,111 @@ -from flask import current_app -import pickle -import os.path -import os +PUZZLE_TEMPLATE_ID = "1drSoyrE4gM3JaGweDkOybwXWdKPIDTfUmB1gQCYS3Uw" +PUZZLE_TEMPLATE_SHEETS = ["Text", "Square grid", "Hex Grid", + "Formula reference: indexing"] -from googleapiclient.discovery import build +def sheets_create(turb, name): + """Create a new sheet with the given name. -# If modifying these scopes, delete the file token.pickle. -SCOPES = ['https://www.googleapis.com/auth/spreadsheets'] + Returns the dict with 'id' and 'url'of the spreadsheet. + """ -turbot_deploy_dir = os.environ.get('TURBOT_DEPLOY_DIR', '.') -TOKEN_FILE = "{}/.gsheets-token.pickle".format(turbot_deploy_dir) + # Create a new spreadsheet + spreadsheet_body = { + 'properties': { + 'title': name + } + } -creds = None + new_sheet = turb.sheets.create(body=spreadsheet_body).execute() -def sheets_create(name): - """Create a new sheet with the given name. + # Now that we've created a new sheet, we need to also allow anyone + # with the link to the sheet to be able to edit it. + turb.permissions.create(fileId=new_sheet["spreadsheetId"], + body={'type': 'anyone', 'role': 'writer'}, + fields='id').execute() - Returns the URL for the spreadsheet. - """ - global creds + return { + 'id': new_sheet["spreadsheetId"], + 'url': new_sheet["spreadsheetUrl"] + } - # The file token.pickle stores token from last login/refresh - if not creds: - if os.path.exists(TOKEN_FILE): - with open(TOKEN_FILE, 'rb') as token: - creds = pickle.load(token) +def sheets_create_for_puzzle(turb, puzzle): + """Creates a new sheet for a puzzle of the given name - # If there are no (valid) credentials available, give up - if not creds or not creds.valid: - current_app.logger.error("No token found in {}".format(TOKEN_FILE)) - current_app.logger.error("Try running ./gsheets-authenticate.py") - return None + Like sheets_create(), but also copies the puzzle template sheet. - service = build('sheets', 'v4', credentials=creds) + Here, 'puzzle' is a dict that must have a 'name' key and may optionally + have a 'channel_url' or 'url' key.""" - # Create a new sheet - spreadsheet_body = { - 'properties': { - 'title': name + # First create the new sheet + new_sheet = sheets_create(turb, puzzle['name']) + + # Insert some useful links into the sheet + url_link='' + if 'url' in puzzle: + url_text = "Original puzzle is at: {}".format(puzzle['url']) + url_link = puzzle['url'] + else: + url_text = '' + + channel_url_link = '' + if 'channel_url' in puzzle: + channel_url_text = "Discussion for this puzzle is at: {}".format( + puzzle['channel_url']) + channel_url_link = puzzle['channel_url'] + else: + channel_url_text = '' + + turb.sheets.values().append( + spreadsheetId=new_sheet['id'], + range='A1:A2', + valueInputOption='USER_ENTERED', + insertDataOption='INSERT_ROWS', + body={ + 'range': 'A1:A2', + 'values': [ + ['=HYPERLINK("'+url_link+'","'+url_text+'")'], + ['=HYPERLINK("'+channel_url_link+'","'+channel_url_text+'")'] + ] + }).execute() + + # Copy some sheets from the Template spreadsheet + + response = turb.sheets.get(spreadsheetId=PUZZLE_TEMPLATE_ID).execute() + + for sheet in response["sheets"]: + if sheet["properties"]["title"] in PUZZLE_TEMPLATE_SHEETS: + turb.sheets.sheets().copyTo(spreadsheetId=PUZZLE_TEMPLATE_ID, + sheetId=sheet["properties"]["sheetId"], + body={ + "destinationSpreadsheetId": + new_sheet['id'] + }).execute() + + return new_sheet + +def renameSheet(turb, url, newName): + id = extractIdFromSheetUrl(url) + requests = [] + requests.append({ + 'updateSpreadsheetProperties': { + 'properties': { + 'title': newName + }, + 'fields': 'title' } + }) + + body = { + 'requests': requests } - request = service.spreadsheets().create(body=spreadsheet_body) - response = request.execute() + turb.sheets.batchUpdate(spreadsheetId = id, + body=body + ).execute() - return response["spreadsheetUrl"] +def extractIdFromSheetUrl(url): + # Google sheet ids are between the /d/ and /edit in the url, like + # https://docs.google.com/spreadsheets/d/1dxHBzjen...-LaXeVPrg/edit#gid=0 + startIndex = url.find('/d/') + 3 + endIndex = url.find('/edit') + return url[startIndex : endIndex]