Adding some more functionality to peacock with Google Drive link downloads.


Google Drive

The bane of our dev days of late. A recent update with Google Drive has made it so that it is rather difficult to get any direct links to an uploaded image/file and download it. We used to be able to right-click it and select copy image, which we could paste into some auto-downloader (aela). But now, one cannot even right click in a Google Drive file. They make it so that it looks like the only downloading-type of action you can take is if you click on their specifically designed Download button.

Here’s what a link to the Abbey Road promo picture looks like:

https://drive.google.com/file/d/1CKQVt2nirGUH9BE6wBLeSE8FieyMepd_/view.

If you click the “Download” button in Chrome (doesn’t work in Firefox), you’ll get redirected to a proper download link:

https://drive.google.com/a/argentgames.co/uc?authuser=0&id=1CKQVt2nirGUH9BE6wBLeSE8FieyMepd_&export=download

We need to convert the first link into the second so that we can download it with the Python requests module. Notice that the only important part in the two links is the id, which is 1CKQVt2nirGUH9BE6wBLeSE8FieyMepd_ in this case.

So we can just extract that unique file identifier and rebuild the second link, inserting the id in the right spot.

def downloadGDrive(link, imageFolder, imgCount):
    # This version is for if links look like "https://drive.google.com/open?id=1ypZ6BLrbwlJHIC8b1UsG6cx15BnwnIVF"
    # If your link looks like "https://drive.google.com/file/d/1CKQVt2nirGUH9BE6wBLeSE8FieyMepd_/view"
    # you can do something like `link.split('/')[-2], which will split the link
    # into items at a `/` character, and we want the 2nd-to-last item
    link_id = link.split('id=')[-1]
    dl_link = "https://drive.google.com/uc?authuser=0&id=" + link_id + "&export=download"
    response = requests.get(dl_link)

    # This stuff will get the original file name so that we can name our downloaded file with the original file name
    d = response.headers['content-disposition']
    fname = re.findall("filename=(.+)", d)
    if len(fname) > 0:
        name = fname[0].split(';')[0]
        name = name.replace(" ", "-").strip('"')
    else:
        name = link_id + ".png"
    localFileName = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S_") + imgCount + "-" + name
    localPath = "discord-wips/" + imageFolder + "/" + localFileName
    if response.status_code == 200:
        print('Downloading %s as %s...' % (fname, name))
        try:
            os.makedirs(imageFolder)
        except FileExistsError:
            # directory already exists
            pass
        with open(localPath, 'wb') as fo:
            for chunk in response.iter_content(4096):
                fo.write(chunk)
        success = "...success!"
    else:
        print("Can't download {}...error: {}".format(dl_link, response.status_code))
        success = "...failed"

    return localPath, localFileName, success