SHARE
TWEET

Untitled

a guest Sep 22nd, 2016 289 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import requests
  4. import random
  5. import json
  6. import hashlib
  7. import hmac
  8. import urllib
  9. import uuid
  10. import time
  11.  
  12.  
  13. try:
  14.     # python 2
  15.     urllib_quote_plus = urllib.quote
  16. except:
  17.     # python 3
  18.     urllib_quote_plus = urllib.parse.quote_plus
  19.  
  20. from requests_toolbelt.multipart.encoder import MultipartEncoder
  21.  
  22.  
  23.  
  24.  
  25. class InstagramAPI:
  26.     API_URL = 'https://i.instagram.com/api/v1/'
  27.     USER_AGENT = 'Instagram 9.2.0 Android (18/4.3; 320dpi; 720x1280; Xiaomi; HM 1SW; armani; qcom; en_US)'
  28.     IG_SIG_KEY = '012a54f51c49aa8c5c322416ab1410909add32c966bbaa0fe3dc58ac43fd7ede'
  29.     EXPERIMENTS = 'ig_android_progressive_jpeg,ig_creation_growth_holdout,ig_android_report_and_hide,ig_android_new_browser,ig_android_enable_share_to_whatsapp,ig_android_direct_drawing_in_quick_cam_universe,ig_android_huawei_app_badging,ig_android_universe_video_production,ig_android_asus_app_badging,ig_android_direct_plus_button,ig_android_ads_heatmap_overlay_universe,ig_android_http_stack_experiment_2016,ig_android_infinite_scrolling,ig_fbns_blocked,ig_android_white_out_universe,ig_android_full_people_card_in_user_list,ig_android_post_auto_retry_v7_21,ig_fbns_push,ig_android_feed_pill,ig_android_profile_link_iab,ig_explore_v3_us_holdout,ig_android_histogram_reporter,ig_android_anrwatchdog,ig_android_search_client_matching,ig_android_high_res_upload_2,ig_android_new_browser_pre_kitkat,ig_android_2fac,ig_android_grid_video_icon,ig_android_white_camera_universe,ig_android_disable_chroma_subsampling,ig_android_share_spinner,ig_android_explore_people_feed_icon,ig_explore_v3_android_universe,ig_android_media_favorites,ig_android_nux_holdout,ig_android_search_null_state,ig_android_react_native_notification_setting,ig_android_ads_indicator_change_universe,ig_android_video_loading_behavior,ig_android_black_camera_tab,liger_instagram_android_univ,ig_explore_v3_internal,ig_android_direct_emoji_picker,ig_android_prefetch_explore_delay_time,ig_android_business_insights_qe,ig_android_direct_media_size,ig_android_enable_client_share,ig_android_promoted_posts,ig_android_app_badging_holdout,ig_android_ads_cta_universe,ig_android_mini_inbox_2,ig_android_feed_reshare_button_nux,ig_android_boomerang_feed_attribution,ig_android_fbinvite_qe,ig_fbns_shared,ig_android_direct_full_width_media,ig_android_hscroll_profile_chaining,ig_android_feed_unit_footer,ig_android_media_tighten_space,ig_android_private_follow_request,ig_android_inline_gallery_backoff_hours_universe,ig_android_direct_thread_ui_rewrite,ig_android_rendering_controls,ig_android_ads_full_width_cta_universe,ig_video_max_duration_qe_preuniverse,ig_android_prefetch_explore_expire_time,ig_timestamp_public_test,ig_android_profile,ig_android_dv2_consistent_http_realtime_response,ig_android_enable_share_to_messenger,ig_explore_v3,ig_ranking_following,ig_android_pending_request_search_bar,ig_android_feed_ufi_redesign,ig_android_video_pause_logging_fix,ig_android_default_folder_to_camera,ig_android_video_stitching_7_23,ig_android_profanity_filter,ig_android_business_profile_qe,ig_android_search,ig_android_boomerang_entry,ig_android_inline_gallery_universe,ig_android_ads_overlay_design_universe,ig_android_options_app_invite,ig_android_view_count_decouple_likes_universe,ig_android_periodic_analytics_upload_v2,ig_android_feed_unit_hscroll_auto_advance,ig_peek_profile_photo_universe,ig_android_ads_holdout_universe,ig_android_prefetch_explore,ig_android_direct_bubble_icon,ig_video_use_sve_universe,ig_android_inline_gallery_no_backoff_on_launch_universe,ig_android_image_cache_multi_queue,ig_android_camera_nux,ig_android_immersive_viewer,ig_android_dense_feed_unit_cards,ig_android_sqlite_dev,ig_android_exoplayer,ig_android_add_to_last_post,ig_android_direct_public_threads,ig_android_prefetch_venue_in_composer,ig_android_bigger_share_button,ig_android_dv2_realtime_private_share,ig_android_non_square_first,ig_android_video_interleaved_v2,ig_android_follow_search_bar,ig_android_last_edits,ig_android_video_download_logging,ig_android_ads_loop_count_universe,ig_android_swipeable_filters_blacklist,ig_android_boomerang_layout_white_out_universe,ig_android_ads_carousel_multi_row_universe,ig_android_mentions_invite_v2,ig_android_direct_mention_qe,ig_android_following_follower_social_context'
  30.     SIG_KEY_VERSION = '4'
  31.     def __init__(self, username, password, debug = False, IGDataPath = None):
  32.         m = hashlib.md5()
  33.         m.update(username.encode('utf-8') + password.encode('utf-8'))
  34.         self.device_id = self.generateDeviceId(m.hexdigest())
  35.         self.setUser(username, password)
  36.         self.isLoggedIn = False
  37.         self.LastResponse = None
  38.  
  39.     def setUser(self, username, password):
  40.         self.username = username
  41.         self.password = password
  42.         self.uuid = self.generateUUID(True)
  43.     def login(self, force = False):
  44.         if (not self.isLoggedIn or force):
  45.             self.s = requests.Session()
  46.             if (self.SendRequest('si/fetch_headers/?challenge_type=signup&guid=' + self.generateUUID(False), None, True)):
  47.  
  48.                 data = {'phone_id'   : self.generateUUID(True),
  49.                         '_csrftoken' : self.LastResponse.cookies['csrftoken'],
  50.                         'username'   : self.username,
  51.                         'guid'       : self.uuid,
  52.                         'device_id'  : self.device_id,
  53.                         'password'   : self.password,
  54.                         'login_attempt_count' : '0'}
  55.  
  56.                 if (self.SendRequest('accounts/login/', self.generateSignature(json.dumps(data)), True)):
  57.                     print self.LastResponse.text
  58.                     self.isLoggedIn = True
  59.                     self.username_id = self.LastJson["logged_in_user"]["pk"]
  60.                     self.rank_token = "%s_%s" % (self.username_id, self.uuid)
  61.                     self.token = self.LastResponse.cookies["csrftoken"]
  62.                     print ("Login success!\n")
  63.                     return True;
  64.                 else:
  65.                     print self.LastResponse.text
  66.     def upload_images(self):
  67.         import base64
  68.         import mimetypes
  69.         filename = 'small.jpg'
  70.         content_type, encoding = mimetypes.guess_type(filename)  
  71.         files = {
  72.         '_csrftoken':self.LastResponse.cookies['csrftoken'],
  73.         'guid':self.uuid,
  74.         'device_id':self.device_id,
  75.         'photo': (filename, open(filename,'rb'),'multipart/form-data')
  76.         }
  77.         if content_type is None:
  78.             content_type = 'multipart/form-data'
  79.         make_post_requests = self.s.post('https://i.instagram.com/api/v1/upload/photo/', files=files)
  80.         print make_post_requests.request.headers
  81.  
  82.  
  83.     def comment(self):
  84.         data = {'_csrftoken':self.LastResponse.cookies['csrftoken'],
  85.                 'guid':self.uuid,
  86.                 'device_id':self.device_id,
  87.                 'comment_text':'test'}
  88.         return self.s.post('https://i.instagram.com/api/v1/media/1343078636324701362_3939745285/comment/', self.generateSignature(json.dumps(data)))
  89.    
  90.  
  91.     def generateSignature(self, data):
  92.         return 'ig_sig_key_version=' + self.SIG_KEY_VERSION + '&signed_body=' + hmac.new(self.IG_SIG_KEY.encode('utf-8'), data.encode('utf-8'), hashlib.sha256).hexdigest() + '.' + urllib_quote_plus(data)
  93.  
  94.     def generateDeviceId(self, seed):
  95.         volatile_seed = "12345"
  96.         m = hashlib.md5()
  97.         m.update(seed.encode('utf-8') + volatile_seed.encode('utf-8'))
  98.         return 'android-' + m.hexdigest()[:16]
  99.  
  100.     def generateUUID(self, type):
  101.         generated_uuid = str(uuid.uuid4())
  102.         if (type):
  103.             return generated_uuid
  104.         else:
  105.             return generated_uuid.replace('-', '')
  106.  
  107.     def buildBody(bodies, boundary):
  108.         # TODO Instagram.php 1620-1645
  109.         return False
  110.  
  111.     def SendRequest(self, endpoint, post = None, login = False):
  112.         if (not self.isLoggedIn and not login):
  113.             raise Exception("Not logged in!\n")
  114.             return;
  115.  
  116.         self.s.headers.update ({'Connection' : 'close',
  117.                                 'Accept' : '*/*',
  118.                                 'Content-type' : 'application/x-www-form-urlencoded; charset=UTF-8',
  119.                                 'Cookie2' : '$Version=1',
  120.                                 'Accept-Language' : 'en-US',
  121.                                 'User-Agent' : self.USER_AGENT})
  122.  
  123.         if (post != None): # POST
  124.             response = self.s.post(self.API_URL + endpoint, data=post) # , verify=False
  125.         else: # GET
  126.             response = self.s.get(self.API_URL + endpoint) # , verify=False
  127.  
  128.         if response.status_code == 200:
  129.             self.LastResponse = response
  130.             self.LastJson = json.loads(response.text)
  131.             return True
  132.         else:
  133.             print ("Request return " + str(response.status_code) + " error!")
  134.             # for debugging
  135.             try:
  136.                 self.LastResponse = response
  137.                 self.LastJson = json.loads(response.text)
  138.             except:
  139.                 pass
  140.             return False
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top