Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: ec7a13bfde
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 73 lines (59 sloc) 2.291 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
import urllib, urllib2
import os
import json
import datetime

API_KEY = "6e3014faf9dc441b84e69ac0fa94f6fa"
API_SECRET = "737cbfd564c443a08b434b3a91525706"

TOKEN_FILE = os.path.expandvars("$HOME/.instabackup.token")

def main():
    # look for existing token
    try:
        with file(TOKEN_FILE) as f:
            token = f.read().strip()

    except IOError:
        # ok, we don't have a token
        redirect = "http://movieos.org/toys/instabackup/"
        auth = "https://instagram.com/oauth/authorize/?client_id=%s&redirect_uri=%s&response_type=token"%(API_KEY, urllib.quote(redirect))
        print "Open\n\n%s\n\nin a web browser, then paste the token (bit after the # in the landing page) here:"%(auth)

        token = raw_input("--> ")
        with file(TOKEN_FILE, "w") as f:
            f.write(token)

    if not os.path.exists('data'):
        os.mkdir('data')

    index = []
    url = "https://api.instagram.com/v1/users/self/media/recent?access_token=%s"%token
    while url:
        print "fetching page.."
        conn = urllib2.urlopen(url)
        raw = conn.read()
        data = json.loads(raw)

        for photo in data["data"]:
            index.append(photo)
            image = photo["images"]["standard_resolution"]["url"]
            image_low = photo["images"]["low_resolution"]["url"]
            try:
                title = photo["caption"]["text"]
            except (KeyError, TypeError):
                title = "untitled"

            filename = u"data/%s.jpg" % (photo["id"])
            if not os.path.exists(filename):
                print u"+ %s" % title
                u = urllib2.urlopen(image)
                with open(filename, 'w') as f:
                    f.write(u.read())

            filename_low = u"data/%s_low.jpg" % (photo["id"])
            if not os.path.exists(filename_low):
                print u"+ %s" % title
                u = urllib2.urlopen(image_low)
                with open(filename_low, 'w') as f:
                    f.write(u.read())
            else:
                print u"= %s" % title

        try:
            url = data["pagination"]["next_url"]
        except KeyError:
            break

    json.dump(index, open('data/index.json', 'w'))
    print "All done!"

if __name__ == "__main__":
    main()
Something went wrong with that request. Please try again.