A bug in the google drive app resulted in a user accidentally orphaning thousands of documents that were in a shared folder.
By looking at the Admin console, I'm able to get the IDs of those documents, but not the IDs of the folders in question (I get the names of the folders, but folder names are not unique and I'm dealing with thousands of documents and hundreds of folders)
If any given user searches for the orphaned document, they can find the document and, by clicking on it, see in the "Activity" pane the information about when the document was removed from its home and where it was removed from.
I'm thinking my best crack at scripting a solution to this is:
For each google document ID...
-> Access the activity history and grab the "removed from folder" event
-> Get the FolderID from that event (surely that exists and there's API access, right?)
-> Reparent the folder
The question is how to get the API access I need to the FolderID.
Note that in the meantime, I have the following code which is sometimes but not always able to get me the parent folders (it seems to fail often enough as to be useless for my overall problem)
function recoverFile (id) {
Logger.log('recoverFile called with id='+id);
try {
f = DriveApp.getFileById(id);
}
catch (exc) {
Logger.log('Error getting file '+id+'- no permission?');
return false
}
Logger.log('Successfully got file: '+f);
parents = f.getParents()
if (parents.hasNext()) {
p = parents.next();
}
else {
Logger.log('Document has no parents');
return false
}
all_parents = [p]
Logger.log('We have parents: '+p);
while (p) {
p.addFile(f)
all_parents.push(p)
Logger.log(p);
if (parents.hasNext()) {
p = parents.next()
}
else {
p = false
}
}
return {'file':f, 'parents':all_parents}
}
Note that the other problem with this code is that it slows down enormously after a few runs -- the try/catch on the getId() is killing me, but I don't know who owns each file, so I have to try to find out.
The Admin Reports API is the key to an actual solution: https://developers.google.com/admin-sdk/reports/v1/reference/activity-ref-appendix-a/drive-event-names
Using that API, it is possible to pull out data on folders that have been orphaned. Once you have that data, it's relatively straightforward to make a script that reads doc IDs and folder IDs and puts the docs back in the folder, though that script has to be run per-creator of the documents in question.
Here's a snipped of the script that grabs the data out of the API:
That lovely script generates a spreadsheet with the data we need to use to pull Data. Here's part 2 of the program -- a script to go through that data row by row and recover the files we can recover...