SHARE
TWEET

Untitled

a guest Sep 21st, 2016 124 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.  
  11. try:
  12.     # python 2
  13.     urllib_quote_plus = urllib.quote
  14. except:
  15.     # python 3
  16.     urllib_quote_plus = urllib.parse.quote_plus
  17.  
  18. from requests_toolbelt.multipart.encoder import MultipartEncoder
  19.  
  20.  
  21.  
  22.  
  23. class InstagramAPI:
  24.     API_URL = 'https://i.instagram.com/api/v1/'
  25.     USER_AGENT = 'Instagram 9.2.0 Android (18/4.3; 320dpi; 720x1280; Xiaomi; HM 1SW; armani; qcom; en_US)'
  26.     IG_SIG_KEY = '012a54f51c49aa8c5c322416ab1410909add32c966bbaa0fe3dc58ac43fd7ede'
  27.     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'
  28.     SIG_KEY_VERSION = '4'
  29.     def __init__(self, username, password, debug = False, IGDataPath = None):
  30.         m = hashlib.md5()
  31.         m.update(username.encode('utf-8') + password.encode('utf-8'))
  32.         self.device_id = self.generateDeviceId(m.hexdigest())
  33.         self.setUser(username, password)
  34.         self.isLoggedIn = False
  35.         self.LastResponse = None
  36.  
  37.     def setUser(self, username, password):
  38.         self.username = username
  39.         self.password = password
  40.         self.uuid = self.generateUUID(True)
  41.     def login(self, force = False):
  42.         if (not self.isLoggedIn or force):
  43.             self.s = requests.Session()
  44.             if (self.SendRequest('si/fetch_headers/?challenge_type=signup&guid=' + self.generateUUID(False), None, True)):
  45.  
  46.                 data = {'phone_id'   : self.generateUUID(True),
  47.                         '_csrftoken' : self.LastResponse.cookies['csrftoken'],
  48.                         'username'   : self.username,
  49.                         'guid'       : self.uuid,
  50.                         'device_id'  : self.device_id,
  51.                         'password'   : self.password,
  52.                         'login_attempt_count' : '0'}
  53.  
  54.                 if (self.SendRequest('accounts/login/', self.generateSignature(json.dumps(data)), True)):
  55.                     print self.LastResponse.text
  56.                     self.isLoggedIn = True
  57.                     self.username_id = self.LastJson["logged_in_user"]["pk"]
  58.                     self.rank_token = "%s_%s" % (self.username_id, self.uuid)
  59.                     self.token = self.LastResponse.cookies["csrftoken"]
  60.                     print ("Login success!\n")
  61.                     return True;
  62.                 else:
  63.                     print self.LastResponse.text
  64.     def upload_images(self):
  65.         data = {'_csrftoken':self.LastResponse.cookies['csrftoken'],
  66.                 'guid':self.uuid,
  67.                 'device_id':self.device_id
  68.                 }
  69.         files = {
  70.         'photo':open('small.jpg','rb')
  71.         }
  72.         make_post_requests = self.s.post('https://i.instagram.com/api/v1/upload/photo/'self.generateSignature(json.dumps(data)), files=files)
  73.         print make_post_requests.text
  74.  
  75.  
  76.     def comment(self):
  77.         data = {'_csrftoken':self.LastResponse.cookies['csrftoken'],
  78.                 'guid':self.uuid,
  79.                 'device_id':self.device_id,
  80.                 'comment_text':'test'}
  81.         return self.s.post('https://i.instagram.com/api/v1/media/1343078636324701362_3939745285/comment/', self.generateSignature(json.dumps(data)))
  82.    
  83.  
  84.     def generateSignature(self, data):
  85.         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)
  86.  
  87.     def generateDeviceId(self, seed):
  88.         volatile_seed = "12345"
  89.         m = hashlib.md5()
  90.         m.update(seed.encode('utf-8') + volatile_seed.encode('utf-8'))
  91.         return 'android-' + m.hexdigest()[:16]
  92.  
  93.     def generateUUID(self, type):
  94.         generated_uuid = str(uuid.uuid4())
  95.         if (type):
  96.             return generated_uuid
  97.         else:
  98.             return generated_uuid.replace('-', '')
  99.  
  100.     def buildBody(bodies, boundary):
  101.         # TODO Instagram.php 1620-1645
  102.         return False
  103.  
  104.     def SendRequest(self, endpoint, post = None, login = False):
  105.         if (not self.isLoggedIn and not login):
  106.             raise Exception("Not logged in!\n")
  107.             return;
  108.  
  109.         self.s.headers.update ({'Connection' : 'close',
  110.                                 'Accept' : '*/*',
  111.                                 'Content-type' : 'application/x-www-form-urlencoded; charset=UTF-8',
  112.                                 'Cookie2' : '$Version=1',
  113.                                 'Accept-Language' : 'en-US',
  114.                                 'User-Agent' : self.USER_AGENT})
  115.  
  116.         if (post != None): # POST
  117.             response = self.s.post(self.API_URL + endpoint, data=post) # , verify=False
  118.         else: # GET
  119.             response = self.s.get(self.API_URL + endpoint) # , verify=False
  120.  
  121.         if response.status_code == 200:
  122.             self.LastResponse = response
  123.             self.LastJson = json.loads(response.text)
  124.             return True
  125.         else:
  126.             print ("Request return " + str(response.status_code) + " error!")
  127.             # for debugging
  128.             try:
  129.                 self.LastResponse = response
  130.                 self.LastJson = json.loads(response.text)
  131.             except:
  132.                 pass
  133.             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
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top