Exemplo n.º 1
0
    def testMultipartFormPOST(self):
        tmp = NamedTemporaryFile()
        tmp.write('asdf')
        tmp.seek(0, 0)

        content_type, postdata = encode_multipart_formdata(
            fields=[],
            files=[('fake_name', 'fake_filename', tmp.name)]
        )

#        print postdata
        path = 'api/fake_email_address_here'

        # Set up the server
#        self.port = reactor.listenTCP(8000, syncsend.SyncSendHttpFactory(), interface="127.0.0.1")
#        self.portno = self.port.getHost().port
        self.portno = 8000

        subp = subprocess.Popen(
            shell=True,
            args=['python ../syncsend.py'],
        )
        url = self.get_url(path, self.portno)

        # Set up the client to DOWNLOAD the file
        #client.getPage(url)

        # Set up the client to UPLOAD the file
        post_factory = client.HTTPClientFactory(
            url=url,
            method='POST',
            postdata=postdata,
            headers={
                'Content-Type': content_type,
            }
        )

        def callback(subp):
            print 'callback'
            subp.terminate()


        def error(failure, subp):
            print 'error: %s' % failure
            subp.terminate()

        post_factory.deferred.addCallback(callback, subp).addErrback(error, subp)

        connector = reactor.connectTCP('127.0.0.1', self.portno, post_factory)
        #.addErrback(error).addCallback(callback)

        reactor.run()
    def fileUpload(self,
                   filedata,
                   siteid,
                   containerid,
                   uploaddirectory,
                   updatenoderef=None,
                   description=None,
                   contenttype=None,
                   majorversion=None,
                   overwrite=None,
                   thumbnails=None):

        filename = filedata.name
        contenttype = get_content_type(filename)
        pars = dict(siteid=siteid,
                    containerid=containerid,
                    uploaddirectory=uploaddirectory,
                    filename=filename,
                    contenttype=contenttype)
        files = (("filedata", filename, filedata.read()), )
        method, url = parseComm(FILEUPLOAD[1])

        content_type, body = encode_multipart_formdata(pars.items(), files)

        headers = {
            "User-Agent": "alfREST",
            "Host": "%s:%s" % (self.host, self.port),
            "Accept": "*/*",
            "Content-Length": str(len(body)),
            "Expect": "100-continue",
            "Content-Type": content_type,
        }

        res = self.request(method, url, body, headers)
        if res is not None:
            logger.info('File %s uploaded in %s/%s%s.' %
                        (filename, siteid, containerid, uploaddirectory))
            return eval(res.read())["nodeRef"].split("/")[-1]
        return False
Exemplo n.º 3
0
    def __mark_photo_private(self, postID, editPage):

        debug('  >> Parsing Edit Page')
        soup = BeautifulSoup(editPage)

        form = {}

        # Build caption
        m = re.search(r'<textarea.*?id="post_two".*?>(.*?)</textarea>', editPage, re.I | re.M | re.DOTALL)
        if not m:
            debug('  !! Couldn\'t find caption!')
            return

        caption = m.group(1)
        caption = re.sub('&lt;', '<', caption)
        caption = re.sub('&gt;', '>', caption)
        caption = re.sub('&amp;', '&', caption)
        caption = re.sub('&#13;', '\r', caption)

        # Build the form data for posting
        form['UPLOAD_IDENTIFIER'] = soup.select('#upload_id')[0]['value']
        form['post[state]'] = 'private'
        form['post[publish_on]'] = ''
        form['post[draft_status]'] = ''
        form['post[date]'] = soup.select('#post_date')[0].get('value') or ''
        form['post[source_url]'] = soup.select('#post_source_url')[0].get('value') or ''
        form['post[tags]'] = soup.select('#post_tags')[0].get('value') or ''
        form['post[slug]'] = ''
        form['custom_tweet'] = 'Photo: [URL]'
        form['custom_tweet_changed'] = '0'
        form['is_rich_text[one]'] = '0'
        form['is_rich_text[two]'] = '1'
        form['is_rich_text[three]'] = '0'
        form['form_key'] = soup.select('#form_key')[0]['value']
        form['photo_raw'] = ''
        form['images'] = ('', '')
        form['photo_src'] = ''
        form['MAX_FILE_SIZE'] = '10485760'
        form['post[two]'] = caption
        form['post[three]'] = soup.select('#post_three')[0].get('value') or ''
        form['post[type]'] = 'photo'
        form['post[id]'] = str(postID)
        form['post[promotion_data][message]'] = '(No message)'
        form['post[promotion_data][icon]'] = '/images/highlighted_posts/icons/bolt_white.png'
        form['post[promotion_data][color]'] = '#bb3434'

        postData = encode_multipart_formdata(form)

        multipartHandler = HTTPPostHandler(postData[1])

        debug("  >> Editing post to 'Private'")

        opener = self._make_opener()
        opener.add_handler(multipartHandler)
        opener.addheaders.append(('Referer', 'http://www.tumblr.com/edit/%s' % postID))
        opener.addheaders.append(('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'))
        opener.addheaders.append(('Accept-Charset', 'UTF-8,*;q=0.5'))

        resp = opener.open('http://www.tumblr.com/edit/%s' % postID, data = postData[0])
        html = resp.fp.read()

        # hacky heuristic:
        # After a successful edit, we should be returned to the Dashboard
        if '<body id="dashboard_index"' in html:
            debug('  >> Success!')
            return True
        else:
            debug('  !! Failed! Something went wrong!')
            return False