upload_video_3.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. def upload_video(self, video, thumbnail, caption=None, upload_id=None):
  2. if upload_id is None:
  3. upload_id = str(int(time.time() * 1000))
  4. data = {
  5. 'upload_id': upload_id,
  6. '_csrftoken': self.token,
  7. 'media_type': '2',
  8. '_uuid': self.uuid,
  9. }
  10. m = MultipartEncoder(data, boundary=self.uuid)
  11. self.session.headers.update({'X-IG-Capabilities': '3Q4=',
  12. 'X-IG-Connection-Type': 'WIFI',
  13. 'Host': 'i.instagram.com',
  14. 'Cookie2': '$Version=1',
  15. 'Accept-Language': 'en-US',
  16. 'Accept-Encoding': 'gzip, deflate',
  17. 'Content-type': m.content_type,
  18. 'Connection': 'keep-alive',
  19. 'User-Agent': self.user_agent})
  20. response = self.session.post(config.API_URL + "upload/video/", data=m.to_string())
  21. if response.status_code == 200:
  22. body = json.loads(response.text)
  23. upload_url = body['video_upload_urls'][3]['url']
  24. upload_job = body['video_upload_urls'][3]['job']
  25. with open(video, 'rb') as video_bytes:
  26. video_data = video_bytes.read()
  27. # solve issue #85 TypeError: slice indices must be integers or None or have an __index__ method
  28. request_size = len(video_data) // 4
  29. last_request_extra = len(video_data) - 3 * request_size
  30. headers = copy.deepcopy(self.session.headers)
  31. self.session.headers.update({
  32. 'X-IG-Capabilities': '3Q4=',
  33. 'X-IG-Connection-Type': 'WIFI',
  34. 'Cookie2': '$Version=1',
  35. 'Accept-Language': 'en-US',
  36. 'Accept-Encoding': 'gzip, deflate',
  37. 'Content-type': 'application/octet-stream',
  38. 'Session-ID': upload_id,
  39. 'Connection': 'keep-alive',
  40. 'Content-Disposition': 'attachment; filename="video.mov"',
  41. 'job': upload_job,
  42. 'Host': 'upload.instagram.com',
  43. 'User-Agent': self.user_agent
  44. })
  45. for i in range(4):
  46. start = i * request_size
  47. if i == 3:
  48. end = i * request_size + last_request_extra
  49. else:
  50. end = (i + 1) * request_size
  51. length = last_request_extra if i == 3 else request_size
  52. content_range = "bytes {start}-{end}/{len_video}".format(
  53. start=start, end=end - 1, len_video=len(video_data)).encode('utf-8')
  54. self.session.headers.update({'Content-Length': str(end - start), 'Content-Range': content_range})
  55. response = self.session.post(upload_url, data=video_data[start:start + length])
  56. self.session.headers = headers
  57. if response.status_code == 200:
  58. if self.configure_video(upload_id, video, thumbnail, caption):
  59. self.expose()
  60. return True
  61. return False