def request(self, endpoint, post=None, login=False):
        buffer = BytesIO()
        if (not self.parent.isLoggedIn) and not login:
            raise InstagramException("Not logged in\n")

        headers = [
            'Connection: close', 'Accept: */*', 'X-IG-Capabilities: 3QI=',
            'Content-type: application/x-www-form-urlencoded; charset=UTF-8',
            'Cookie2: $Version=1', 'Accept-Language: en-US'
        ]

        ch = pycurl.Curl()

        ch.setopt(pycurl.URL, Constants.API_URL + endpoint)
        ch.setopt(pycurl.USERAGENT, self.userAgent)
        ch.setopt(pycurl.WRITEFUNCTION, buffer.write)
        ch.setopt(pycurl.FOLLOWLOCATION, True)
        ch.setopt(pycurl.HEADER, True)
        ch.setopt(pycurl.HTTPHEADER, headers)
        ch.setopt(pycurl.VERBOSE, False)
        ch.setopt(pycurl.SSL_VERIFYPEER, self.verifyPeer)
        ch.setopt(pycurl.SSL_VERIFYHOST, self.verifyHost)
        ch.setopt(
            pycurl.COOKIEFILE,
            self.parent.IGDataPath + self.parent.username + '-cookies.dat')
        ch.setopt(
            pycurl.COOKIEJAR,
            self.parent.IGDataPath + self.parent.username + '-cookies.dat')

        if post:
            ch.setopt(pycurl.POST, True)
            ch.setopt(pycurl.POSTFIELDS, post)

        if self.parent.proxy:
            ch.setopt(pycurl.PROXY, self.parent.proxyHost)
            if self.parent.proxyAuth:
                ch.setopt(pycurl.PROXYUSERPWD, self.parent.proxyAuth)

        ch.perform()
        resp = buffer.getvalue()
        header_len = ch.getinfo(pycurl.HEADER_SIZE)
        header = resp[0:header_len]
        body = resp[header_len:]
        ch.close()

        if self.parent.debug:
            import urllib
            print "REQUEST: " + endpoint
            if post is not None:
                if not isinstance(post, list):
                    print 'DATA: ' + urllib.unquote_plus(post)
            print "RESPONSE: " + body + "\n"

        return [header, json.loads(body)]
示例#2
0
    def request(self, endpoint, post=None, login=False):
        buffer = BytesIO()
        if (not self.parent.isLoggedIn) and not login:
            raise InstagramException("Not logged in\n")

        headers = [
            'Connection: close', 'Accept: */*', 'X-IG-Capabilities: 3QI=',
            'Content-type: application/x-www-form-urlencoded; charset=UTF-8',
            'Cookie2: $Version=1', 'Accept-Language: en-US'
        ]

        ch = pycurl.Curl()

        ch.setopt(pycurl.URL, Constants.API_URL + endpoint)
        ch.setopt(pycurl.USERAGENT, self.userAgent)
        ch.setopt(pycurl.WRITEFUNCTION, buffer.write)
        ch.setopt(pycurl.FOLLOWLOCATION, True)
        ch.setopt(pycurl.HEADER, True)
        ch.setopt(pycurl.HTTPHEADER, headers)
        ch.setopt(pycurl.VERBOSE, False)
        ch.setopt(pycurl.SSL_VERIFYPEER, self.verifyPeer)
        ch.setopt(pycurl.SSL_VERIFYHOST, self.verifyHost)
        ch.setopt(
            pycurl.COOKIEFILE,
            self.parent.IGDataPath + self.parent.username + '-cookies.dat')
        ch.setopt(
            pycurl.COOKIEJAR,
            self.parent.IGDataPath + self.parent.username + '-cookies.dat')

        if post:
            ch.setopt(pycurl.POST, True)
            ch.setopt(pycurl.POSTFIELDS, post)

        if self.parent.proxy:
            ch.setopt(pycurl.PROXY, self.parent.proxyHost)
            if self.parent.proxyAuth:
                ch.setopt(pycurl.PROXYUSERPWD, self.parent.proxyAuth)

        ch.perform()
        resp = buffer.getvalue().decode("utf-8")
        header_len = ch.getinfo(pycurl.HEADER_SIZE)
        header = resp[0:header_len]
        body = resp[header_len:]

        if self.parent.debug:
            if post:
                print(Utils.colouredString('POST:  ', 'light_blue') + endpoint)
            else:
                print(Utils.colouredString('GET:  ', 'light_blue') + endpoint)

            if post is not None:
                if not isinstance(post, list):
                    print('DATA: ' + compat_urllib_parse.unquote_plus(post))

            bytes = Utils.formatBytes(ch.getinfo(pycurl.SIZE_DOWNLOAD))
            httpCode = ch.getinfo(pycurl.HTTP_CODE)
            print(
                Utils.colouredString("← " + str(httpCode) + " \t " + bytes,
                                     'green'))

            if self.parent.truncatedDebug and len(body) > 1000:
                print(
                    Utils.colouredString('RESPONSE: ', 'cyan') + body[0:1000] +
                    "...\n")
            else:
                print(Utils.colouredString('RESPONSE: ', 'cyan') + body + "\n")

        ch.close()
        return [header, json.loads(body)]
示例#3
0
    def uploadPhoto(self,
                    photo,
                    caption=None,
                    upload_id=None,
                    customPreview=None,
                    location=None,
                    filter_=None,
                    reel_flag=False):

        endpoint = Constants.API_URL + 'upload/photo/'
        boundary = self.parent.uuid

        if upload_id is not None and customPreview is None:
            fileToUpload = Utils.createVideoIcon(photo)
        elif customPreview is not None:
            fileToUpload = file_get_contents(customPreview)
        else:
            upload_id = locale.format(
                "%.*f", (0, round(float('%.2f' % time.time()) * 1000)),
                grouping=False)
            fileToUpload = file_get_contents(photo)

        bodies = [
            OrderedDict([('type', 'form-data'), ('name', 'upload_id'),
                         ('data', upload_id)]),
            OrderedDict([('type', 'form-data'), ('name', '_uuid'),
                         ('data', self.parent.uuid)]),
            OrderedDict([('type', 'form-data'), ('name', '_csrftoken'),
                         ('data', self.parent.token)]),
            OrderedDict([
                ('type', 'form-data'), ('name', 'image_compression'),
                ('data',
                 '{"lib_name":"jt","lib_version":"1.3.0","quality":"70"}')
            ]),
            OrderedDict([
                ('type', 'form-data'), ('name', 'photo'),
                ('data', fileToUpload),
                ('filename', 'pending_media_' +
                 locale.format("%.*f",
                               (0, round(float('%.2f' % time.time()) * 1000)),
                               grouping=False) + '.jpg'),
                ('headers', [
                    'Content-Transfer-Encoding: binary',
                    'Content-type: application/octet-stream',
                ])
            ]),
        ]

        data = self.buildBody(bodies, boundary)
        headers = [
            'Connection: close',
            'Accept: */*',
            'Content-type: multipart/form-data; boundary=' + boundary,
            'Content-Length: ' + str(len(data)),
            'Cookie2: $Version=1',
            'Accept-Language: en-US',
            'Accept-Encoding: gzip',
        ]

        buffer = BytesIO()
        ch = pycurl.Curl()

        ch.setopt(pycurl.URL, endpoint)
        ch.setopt(pycurl.USERAGENT, self.userAgent)
        ch.setopt(pycurl.WRITEFUNCTION, buffer.write)
        ch.setopt(pycurl.FOLLOWLOCATION, True)
        ch.setopt(pycurl.HEADER, True)
        ch.setopt(pycurl.VERBOSE, self.parent.debug)
        ch.setopt(pycurl.SSL_VERIFYPEER, self.verifyPeer)
        ch.setopt(pycurl.SSL_VERIFYHOST, self.verifyHost)
        ch.setopt(pycurl.HTTPHEADER, headers)
        ch.setopt(
            pycurl.COOKIEFILE,
            self.parent.IGDataPath + self.parent.username + "-cookies.dat")
        ch.setopt(
            pycurl.COOKIEJAR,
            self.parent.IGDataPath + self.parent.username + "-cookies.dat")
        ch.setopt(pycurl.POST, True)
        ch.setopt(pycurl.POSTFIELDS, data)

        if self.parent.proxy:
            ch.setopt(pycurl.PROXY, self.parent.proxyHost)
            if self.parent.proxyAuth:
                ch.setopt(pycurl.PROXYUSERPWD, self.parent.proxyAuth)

        ch.perform()
        resp = buffer.getvalue()
        header_len = ch.getinfo(pycurl.HEADER_SIZE)

        header = resp[0:header_len]
        upload = UploadPhotoResponse(json.loads(resp[header_len:]))

        ch.close()

        if not upload.isOk():
            raise InstagramException(upload.getMessage())

        if self.parent.debug:
            print('RESPONSE: ' + resp[header_len:] + "\n")

        if reel_flag:
            configure = self.parent.configureToReel(upload.getUploadId(),
                                                    photo)
        else:
            configure = self.parent.configure(upload.getUploadId(), photo,
                                              caption, location, filter_)

        if not configure.isOk():
            raise InstagramException(configure.getMessage())

        self.parent.expose()

        return configure
示例#4
0
    def request(self, endpoint, post=None, login=False):
        buffer = BytesIO()
        if (not self.parent.isLoggedIn) and not login:
            raise InstagramException("Not logged in\n")

        headers = [
            'Connection: close', 'Accept: */*', 'X-IG-Capabilities: 3QI=',
            'Content-type: application/x-www-form-urlencoded; charset=UTF-8',
            'Cookie2: $Version=1', 'Accept-Language: en-US'
        ]

        ch = pycurl.Curl()

        ch.setopt(pycurl.URL, Constants.API_URL + endpoint)
        ch.setopt(pycurl.USERAGENT, self.userAgent)
        ch.setopt(pycurl.WRITEFUNCTION, buffer.write)
        ch.setopt(pycurl.FOLLOWLOCATION, True)
        ch.setopt(pycurl.HEADER, True)
        ch.setopt(pycurl.HTTPHEADER, headers)
        ch.setopt(pycurl.VERBOSE, False)
        ch.setopt(pycurl.SSL_VERIFYPEER, self.verifyPeer)
        ch.setopt(pycurl.SSL_VERIFYHOST, self.verifyHost)
        ch.setopt(
            pycurl.COOKIEFILE,
            self.parent.IGDataPath + self.parent.username + '-cookies.dat')
        ch.setopt(
            pycurl.COOKIEJAR,
            self.parent.IGDataPath + self.parent.username + '-cookies.dat')

        ch.setopt(pycurl.CONNECTTIMEOUT, 20)
        ch.setopt(pycurl.TIMEOUT, 20)

        if post:
            ch.setopt(pycurl.POST, True)
            ch.setopt(pycurl.POSTFIELDS, post)

        if self.parent.proxy:
            ch.setopt(pycurl.IPRESOLVE, pycurl.IPRESOLVE_WHATEVER)
            ch.setopt(pycurl.PROXY, self.parent.proxyHost)
            if self.parent.proxyAuth:
                ch.setopt(pycurl.PROXYUSERPWD, self.parent.proxyAuth)

        # костыль для отлова 'Tls packet with unexpected length was received'
        safe_counter = 0
        while True:
            safe_counter += 1
            if safe_counter > 5:
                return

            try:
                ch.perform()
                break
            except Exception as e:
                # код нужной ошибки
                if e.args[0] == 56 or e.args[0] == 18:
                    buffer = BytesIO()
                    ch.setopt(pycurl.WRITEFUNCTION, buffer.write)
                    continue
                else:
                    raise e

        resp = buffer.getvalue().decode("utf-8")
        header_len = ch.getinfo(pycurl.HEADER_SIZE)
        header = resp[0:header_len]
        body = resp[header_len:]

        if self.parent.debug:
            if post:
                print(Utils.colouredString('POST:  ', 'light_blue') + endpoint)
            else:
                print(Utils.colouredString('GET:  ', 'light_blue') + endpoint)

            if post is not None:
                if not isinstance(post, list):
                    print('DATA: ' + compat_urllib_parse.unquote_plus(post))

            bytes = Utils.formatBytes(ch.getinfo(pycurl.SIZE_DOWNLOAD))
            httpCode = ch.getinfo(pycurl.HTTP_CODE)
            print(
                Utils.colouredString("← " + str(httpCode) + " \t " + bytes,
                                     'green'))

            if self.parent.truncatedDebug and len(body) > 1000:
                print(
                    Utils.colouredString('RESPONSE: ', 'cyan') + body[0:1000] +
                    "...\n")
            else:
                print(Utils.colouredString('RESPONSE: ', 'cyan') + body + "\n")

        ch.close()
        response_dict = {}
        try:
            response_dict = json.loads(body)
        except ValueError as e:
            return self.request(endpoint, post, login)

        return [header, response_dict]