Advertisement
Guest User

Untitled

a guest
Feb 7th, 2013
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.82 KB | None | 0 0
  1. #!/usr/bin/env python
  2. """
  3. Command line uploader for Vine.
  4.  
  5. For Python 2.7. Batteries included.
  6. Educational/research use only. No warranty. Public domain.
  7.  
  8. usage: vinup.py <username> <video filename> <thumbnail filename> <description>
  9.  
  10.    username           - Your Vine login (email address)
  11.  
  12.    video filename     - Filename for a local MP4 video to upload.
  13.                         Usually this is 480x480 resolution. The server will transcode it
  14.                         to a lower-quality version that the app requests, but this original
  15.                         is available to download too.
  16.  
  17.    thumbnail filename - Filename for a local JPEG thumbnail.
  18.                         Usually this is 480x480 resolution.
  19.  
  20.    description        - A text description for the video. (Remember to quote this properly
  21.                         if it has spaces or other commandline-unfriendly characters.)
  22.  
  23. """
  24.  
  25. import sys, httplib, urllib, json, hmac, hashlib, base64, uuid, random, getpass
  26. from email.utils import formatdate
  27.  
  28. class APIError(Exception):
  29.     pass
  30.  
  31. def checkStatus(resp):
  32.     if resp.status != 200:
  33.         raise APIError("Status code %d, response %r" % (resp.status, resp.read()))
  34.  
  35. class AmazonS3(object):
  36.     def __init__(self, bucket, accessKey, secret):
  37.         self.host = '%s.s3.amazonaws.com' % bucket
  38.         self.bucketPrefix = '/' + bucket
  39.         self.accessKey = accessKey
  40.         self.secret = secret
  41.         self.conn = httplib.HTTPSConnection(self.host)
  42.         self.headers = {
  43.             'Host': self.host,
  44.             'User-Agent': 'aws-sdk-iOS/1.4.4 iPhone-OS/6.1 en_US',
  45.         }
  46.  
  47.     def _sign(self, msg):
  48.         h = hmac.new(self.secret, msg, hashlib.sha1)
  49.         return base64.encodestring(h.digest()).strip()
  50.  
  51.     def _authorize(self, method, resource, headers):
  52.         headers['Date'] = formatdate(usegmt=True)
  53.         msg = '\n'.join((method, '', headers['Content-Type'], headers['Date'], self.bucketPrefix + resource))
  54.         headers['Authorization'] = "AWS %s:%s" % (self.accessKey, self._sign(msg))
  55.  
  56.     def url(self, resource, versionId):
  57.         return 'https://%s%s?versionId=%s' % (self.host, resource, versionId)
  58.  
  59.     def put(self, resource, contentType, content):
  60.         headers = dict(self.headers)
  61.         headers['Content-Type'] = contentType
  62.         headers['Content-Length'] = len(content)
  63.         self._authorize('PUT', resource, headers)
  64.         self.conn.request('PUT', resource, content, headers)
  65.         resp = self.conn.getresponse()
  66.         checkStatus(resp)
  67.         resp.read()
  68.         return self.url(resource, resp.getheader('x-amz-version-id'))
  69.  
  70. class VineClient(object):
  71.     host = 'api.vineapp.com'
  72.     version = '1.0.5'
  73.  
  74.     def __init__(self):
  75.         self.s3 = AmazonS3('vines', 'AKIAJL2SSORTZ5AK6D4A', 'IN0mNk2we4QqnFaDUUeC7DYzBD9BRCwRYnTutoxj')
  76.         self.conn = httplib.HTTPSConnection(self.host)
  77.         self.headers = {
  78.             'Host': self.host,
  79.             'User-Agent': 'com.vine.iphone/1.0.5 (unknown, iPhone OS 6.1, iPad, Scale/2.000000)',
  80.         }
  81.  
  82.     def _contentId(self):
  83.         return "%s-%d-%016X_%s" % (uuid.uuid4(), random.randint(1024, 0xffff),
  84.             random.randint(0x1000000000, 0xf0000000000), self.version)
  85.  
  86.     def _postForm(self, url, **args):
  87.         headers = dict(self.headers)
  88.         headers['content-type'] = 'application/x-www-form-urlencoded'
  89.         self.conn.request('POST', url, urllib.urlencode(args), headers)
  90.         resp = self.conn.getresponse()
  91.         checkStatus(resp)
  92.         return json.loads(resp.read())
  93.  
  94.     def login(self, username, password):
  95.         r = self._postForm('/users/authenticate', username=username, password=password)
  96.         if not r['success']:
  97.             raise APIError(repr(r['error']))
  98.         self.username = r['data']['username']
  99.         self.userId = r['data']['userId']
  100.         self.headers['vine-session-id'] = r['data']['key']
  101.  
  102.     def upload(self, videoData, thumbData, description):
  103.         cid = self._contentId()
  104.         self._postForm('/posts',
  105.             videoUrl = self.s3.put('/videos/%s.mp4' % cid, 'video/mp4', videoData),
  106.             thumbnailUrl = self.s3.put('/thumbs/%s.mp4.jpg' % cid, 'image/jpeg', thumbData),
  107.             description = description
  108.         )
  109.         return cid
  110.  
  111. def main():
  112.     if len(sys.argv) != 5:
  113.         sys.stderr.write(__doc__)
  114.         sys.exit(1)
  115.  
  116.     _, username, videoFile, thumbFile, desc = sys.argv
  117.     password = getpass.getpass("Password [Vine user %s]: " % username)
  118.  
  119.     videoData = open(videoFile, 'rb').read()
  120.     thumbData = open(thumbFile, 'rb').read()
  121.  
  122.     client = VineClient()
  123.     client.login(username, password)
  124.     print "Successfully logged in. Uploading video..."
  125.     cid = client.upload(videoData, thumbData, desc)
  126.     print "Done. (%s)" % cid
  127.  
  128. if __name__ == '__main__':
  129.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement