]> git.cworth.org Git - turbot/blobdiff - turbot/sheets.py
Use the Google drive API to create a hunt's sheet within a folder
[turbot] / turbot / sheets.py
index 37bd363ac8a85270d90df6d16b4415b47dd72bf2..831998d6f52c581c71b21d3b3daf67c475003d78 100644 (file)
@@ -2,17 +2,50 @@ PUZZLE_TEMPLATE_ID = "1drSoyrE4gM3JaGweDkOybwXWdKPIDTfUmB1gQCYS3Uw"
 PUZZLE_TEMPLATE_SHEETS = ["Text", "Square grid", "Hex Grid",
                           "Formula reference: indexing"]
 
-def sheets_create(turb, name):
+def sheets_create_folder(turb, folder_name):
+    """Create a new folder within Google Drive
+
+    Returns the id of the created folder."""
+
+    body = {
+        "name": folder_name,
+        "mimeType": "application/vnd.google-apps.folder"
+    }
+
+    folder = turb.files.create(body=body, fields='id').execute()
+
+    return folder.get('id')
+
+def sheets_create(turb, name, folder_id):
     """Create a new spreadsheet with the given name.
 
     Returns a dict with 'id' and 'url' of the spreadsheet
     """
 
-    spreadsheet = create_spreadsheet(turb, name)
+    body = {
+        "name": name,
+        "parents": [folder_id],
+        "mimeType": "application/vnd.google-apps.spreadsheet"
+    }
+
+    spreadsheet = turb.files.create(body=body, fields='id').execute()
+    id = spreadsheet['id']
+
+    # The files.create call gives us the ID for our new sheet, but we
+    # need the URL for it as well. So we get that with the sheets API.
+    spreadsheet = turb.sheets.get(spreadsheetId=id,
+                                  fields='spreadsheetUrl').execute()
+    url = spreadsheet['spreadsheetUrl']
+
+    # Finally, we want to also allow anyone with the link to the sheet
+    # to be able to edit it.
+    turb.permissions.create(fileId=id,
+                            body={'type': 'anyone', 'role': 'writer'},
+                            fields='').execute()
 
     return {
-        'id': spreadsheet['spreadsheetId'],
-        'url': spreadsheet['spreadsheetUrl']
+        'id': id,
+        'url': url
     }
 
 def create_spreadsheet(turb, name):
@@ -66,9 +99,12 @@ def sheets_create_for_puzzle(turb, puzzle):
                 body={
                     "destinationSpreadsheetId": spreadsheet_id
                 }).execute()
-            # Rename each copied sheet to match original name
-            rename_sheet(turb, spreadsheet_id, res['sheetId'],
-                         sheet["properties"]["title"])
+            # Rename each copied sheet to match the name from the template
+            sheet_name = sheet["properties"]["title"]
+            # Except for "Text" which we rename to the puzzle name
+            if sheet_name == "Text":
+                sheet_name = puzzle['name']
+            rename_sheet(turb, spreadsheet_id, res['sheetId'], sheet_name)
 
     # Next, delete the blank sheet that's was created before the template
     sheet_id = spreadsheet['sheets'][0]['properties']['sheetId']