Example #1
0
def createnewalbum(albumname, rights, gds, username):
    """Create new album with specified name and rights.

    Create new album with specified name, rights and return its feed url for posting.
    """
    print 'Photos will be inserted in a newly-created album', albumname, 'with rights', rights # debug
    # prepare metadata
    gdata_entry = gdata.GDataEntry()
    gdata_entry.title = atom.Title(text=albumname)
    # create new albums as private
    gdata_entry.rights = atom.Rights(text=rights) # standard atom rights
    # extended rights definition in google namespace
    ext_rights = atom.ExtensionElement(
		    tag='access',
		    namespace='http://schemas.google.com/photos/2007')
    ext_rights.text = rights # setting the extended rights
    gdata_entry.extension_elements.append(ext_rights)
    # listing categories of gdata_entry (binding to picasa service)
    gdata_entry.category.append(atom.Category(
            scheme = gdata.GDATA_NAMESPACE + '#kind',
            term = 'http://schemas.google.com/photos/2007#album'
            ))
    # create new album entry by submitting gdata object
    try:
        album = gds.Post(
                gdata_entry,
                'http://picasaweb.google.com/data/feed/api/user/' + username
                )
    except:
        sys.exit('Error while creating new album: ' + sys.exc_info()[0])
    # Note: here we have `album` as gdata.GDataEntry object
    return album.GetFeedLink().href # return album feed url
Example #2
0
  def CreateFolder(self, title, folder_or_uri=None):
    """Creates a folder in the Document List feed.

    Args:
      title: string The title of the folder on the server after being created.
      folder_or_uri: DocumentListEntry or string (optional) An object with a
          link to a folder or a uri to a folder to upload to.
          Note: A valid uri for a folder is of the form:
                /feeds/folders/private/full/folder%3Afolder_id

    Returns:
      A DocumentListEntry containing information about the folder created on
      the Google Documents service.
    """
    if folder_or_uri:
      try:
        uri = folder_or_uri.content.src
      except AttributeError:
        uri = folder_or_uri
    else:
      uri = '/feeds/documents/private/full'

    category = atom.Category(scheme=DATA_KIND_SCHEME, term=FOLDER_KIND_TERM,
                             label='folder')
    folder_entry = gdata.docs.DocumentListEntry()
    folder_entry.title = atom.Title(text=title)
    folder_entry.category.append(category)
    folder_entry = self.Post(folder_entry, uri,
                             converter=gdata.docs.DocumentListEntryFromString)

    return folder_entry
Example #3
0
    def CreatePost(self, title, content, author_name, tags, is_draft):
        """This method creates a new post on a blog.  The new post can be stored as
    a draft or published based on the value of the is_draft parameter.  The
    method creates an GDataEntry for the new post using the title, content,
    author_name and is_draft parameters.  With is_draft, True saves the post as
    a draft, while False publishes the post.  Then it uses the given
    GDataService to insert the new post.  If the insertion is successful, the
    added post (GDataEntry) will be returned.
    """

        # Create the entry to insert.
        entry = gdata.GDataEntry()
        entry.author.append(atom.Author(atom.Name(text=author_name)))
        entry.title = atom.Title(title_type='xhtml', text=title)
        entry.content = atom.Content(content_type='html', text=content)
        for tag in tags:
            category = atom.Category(term=tag,
                                     scheme="http://www.blogger.com/atom/ns#")
            entry.category.append(category)

        if is_draft:
            control = atom.Control()
            control.draft = atom.Draft(text='yes')
            entry.control = control

        # Ask the service to insert the new entry.
        return self.service.Post(entry,
                                 '/feeds/' + self.blog_id + '/posts/default')
Example #4
0
    def updateLabels(self, labels, newLabels):

        query = service.Query()
        query.feed = self.postsUri
        query.max_results = 10000
        if labels:
            query.categories = labels

        feed = self.gdService.Get(query.ToUri())

        newCategory = []
        if newLabels:
            for label in newLabels:
                category = atom.Category(scheme=blogger.LABEL_SCHEME,
                                         term=label)
                newCategory.append(category)

        for entry in feed.entry:
            while len(entry.category) > 0:
                entry.category.pop()
            entry.category = newCategory
            editUri = entry.GetEditLink().href
            self.gdService.Put(entry, editUri)

        return newCategory
Example #5
0
    def testMedia2(self):
        # Create media & metadata
        ms = gdata.MediaSource()
        ms.setFile(test_image_location, 'image/jpeg')
        new_media_entry = gdata.GDataEntry()
        new_media_entry.title = atom.Title(text='testimage1.jpg')
        new_media_entry.summary = atom.Summary(text='Test Image')
        new_media_entry.category.append(
            atom.Category(scheme='http://schemas.google.com/g/2005#kind',
                          term='http://schemas.google.com/photos/2007#photo'))
        media_entry = self.gd_client.Post(new_media_entry,
                                          self.album_entry.GetFeedLink().href,
                                          media_source=ms)
        self.assertTrue(media_entry is not None)
        self.assertTrue(isinstance(media_entry, gdata.GDataEntry))
        self.assertTrue(media_entry.IsMedia())
        self.assertTrue(media_entry.summary.text == 'Test Image')

        # Update media only
        ms = gdata.MediaSource()
        ms.setFile(test_image_location, 'image/jpeg')
        media_entry = self.gd_client.Put(None,
                                         media_entry.GetEditMediaLink().href,
                                         media_source=ms)
        self.assertTrue(media_entry is not None)
        self.assertTrue(isinstance(media_entry, gdata.GDataEntry))
        self.assertTrue(media_entry.IsMedia())

        # Delete entry
        response = self.gd_client.Delete(media_entry.GetEditLink().href)
        self.assertTrue(response)
Example #6
0
    def setUp(self):
        self.gd_client = gdata.service.GDataService()
        self.gd_client.email = username
        self.gd_client.password = password
        self.gd_client.service = 'lh2'
        self.gd_client.source = 'GDataService Media "Unit" Tests'
        try:
            self.gd_client.ProgrammaticLogin()
        except gdata.service.CaptchaRequired:
            self.fail('Required Captcha')
        except gdata.service.BadAuthentication:
            self.fail('Bad Authentication')
        except gdata.service.Error:
            self.fail('Login Error')

        # create a test album
        gd_entry = gdata.GDataEntry()
        gd_entry.title = atom.Title(text='GData Test Album')
        gd_entry.category.append(
            atom.Category(scheme='http://schemas.google.com/g/2005#kind',
                          term='http://schemas.google.com/photos/2007#album'))

        self.album_entry = self.gd_client.Post(
            gd_entry,
            'http://picasaweb.google.com/data/feed/api/user/' + username)
Example #7
0
    def createPost(self,
                   title,
                   content,
                   authorName,
                   labels=None,
                   isDraft=False):

        # Create a gdata entry.
        entry = gdata.GDataEntry()
        # append author.
        entry.author.append(atom.Author(atom.Name(text=authorName)))
        entry.title = atom.Title(title_type='xhtml', text=title)

        # handle labels by using atom.Category.
        if labels:
            for label in labels:
                category = atom.Category(scheme=blogger.LABEL_SCHEME,
                                         term=label)
                entry.category.append(category)

        # handle draft,
        if isDraft:
            control = atom.Control()
            control.draft = atom.Draft(text='yes')
            entry.control = control

        # add content.
        entry.content = atom.Content(content_type='html', text=content)

        return self.gdService.Post(entry, self.postsUri)
Example #8
0
 def send_post(self, blogid, post_title, post_text, labels):
     """
     Send post to the service
     """
     result, blogger_service = self._login()
     if 'success' in result:
         try:
             # create a post
             entry = gdata.GDataEntry()
             entry.title = atom.Title('xhtml', post_title)
             entry.content = atom.Content(content_type='html',
                                          text=post_text)
             # Get selected labels
             tags = labels
             for tag in tags:
                 label = atom.Category(
                     term=tag, scheme="http://www.blogger.com/atom/ns#")
                 entry.category.append(label)
             blogger_service.Post(entry, '/feeds/%s/posts/default' % blogid)
             result = u'Successfully published'
         except:
             result = u'Error'
     else:
         result = result['error']
     return result
Example #9
0
 def __init__(self,
              author=None,
              category=None,
              content=None,
              atom_id=None,
              link=None,
              published=None,
              title=None,
              updated=None,
              extended_property=None,
              extension_elements=None,
              extension_attributes=None,
              text=None):
     gdata.GDataEntry.__init__(self,
                               author=author,
                               category=category,
                               content=content,
                               atom_id=atom_id,
                               link=link,
                               published=published,
                               title=title,
                               updated=updated,
                               text=text,
                               extension_elements=extension_elements,
                               extension_attributes=extension_attributes)
     self.category.append(
         atom.Category(scheme='http://schemas.google.com/g/2005#kind',
                       term='http://schemas.google.com/photos/2007#%s' %
                       self._kind))
Example #10
0
    def test_event(self):
        event = self.client.GetEvent('/event/10302445')
        author = event.author[0]
        assert event.title.text == '当代波兰影展暨罗曼.波兰斯基大师见面活动'

        entry = douban.EventEntry()
        entry.when = douban.When(start_time='2008-09-13T15:00:00+08:00', end_time='2008-11-13T15:00:00+08:00')
        entry.where = douban.Where('北京')
        entry.title = atom.Title(text="a test event")
        entry.content = atom.Content(text="this event is for testing") 
        entry.category = atom.Category(term='http://www.douban.com/2007#event.music', scheme='http://www.douban.com/2007#kind') 
        entry = self.client.AddEvent("/events", entry, False, True)
        assert entry.title.text == 'a test event'
        entry = self.client.UpdateEvent(entry, 'changing'*100, 'changed'*2, True, False)
        assert entry.title.text == 'changed'*2
        self.client.DeleteEvent(entry, reason='对不起大家,我真的不能办了')

        events = self.client.GetLocationEvents('beijing', type='party')
        assert any(e.title.text == '去坐世界最大的摩天轮吧' for e in events.entry)

        events = self.client.SearchEvents('798', location='beijing')
        assert any(e.title.text == '2008年798艺术节' for e in events.entry)

        events = self.client.GetEvents('/people/aka/events')#, status='initiate')
        assert any(e.title.text == '豆瓣私家猫照片汇' for e in events.entry)
Example #11
0
def _make_kind_category(label):
  """Stolen from gdata-2.0.10 docs.service."""
  import atom
  if label is None:
    return None
  documents_namespace = 'http://schemas.google.com/docs/2007'
  return atom.Category(scheme=gdata.docs.service.DATA_KIND_SCHEME,
                       term=documents_namespace + '#' + label, label=label)
Example #12
0
    def AddLabel(self, label):
        """Adds a label to the blog post.

        The label is represented by an Atom category element, so this method
        is shorthand for appending a new atom.Category object.

        Args:
          label: str
        """
        self.category.append(atom.Category(scheme=LABEL_SCHEME, term=label))
Example #13
0
    def AddNewsSitemap(self,
                       site_uri,
                       sitemap_uri,
                       sitemap_news_publication_label,
                       uri=SITEMAPS_FEED_TEMPLATE,
                       url_params=None,
                       escape_params=True,
                       converter=None):
        """Adds a news sitemap to a site.

        Args:
          site_uri: str URI of which site to add sitemap for.
          sitemap_uri: str URI of sitemap to add to a site.
          sitemap_news_publication_label: str, list of str Publication Labels for
                                          sitemap.
          uri: str (optional) URI template to add a sitemap.
               Default SITEMAP_FEED_TEMPLATE.
          url_params: dict (optional) Additional URL parameters to be included
                      in the insertion request.
          escape_params: boolean (optional) If true, the url_parameters will be
                         escaped before they are included in the request.
          converter: func (optional) Function which is executed on the server's
              response before it is returned. Usually this is a function like
              SitemapsEntryFromString which will parse the response and turn it into
              an object.

        Returns:
          If converter is defined, the results of running converter on the server's
          response. Otherwise, it will be a SitemapsEntry object.
        """

        sitemap_entry = webmastertools.SitemapsEntry(
            atom_id=atom.Id(text=sitemap_uri),
            category=atom.Category(
                scheme='http://schemas.google.com/g/2005#kind',
                term=
                'http://schemas.google.com/webmasters/tools/2007#sitemap-news'
            ),
            sitemap_news_publication_label=[],
        )
        if isinstance(sitemap_news_publication_label, str):
            sitemap_news_publication_label = [sitemap_news_publication_label]
        for label in sitemap_news_publication_label:
            sitemap_entry.sitemap_news_publication_label.append(
                webmastertools.SitemapNewsPublicationLabel(text=label))
        print(sitemap_entry)
        response = self.Post(sitemap_entry,
                             uri %
                             {'site_id': urllib.parse.quote_plus(site_uri)},
                             url_params=url_params,
                             escape_params=escape_params,
                             converter=converter)
        if not converter and isinstance(response, atom.Entry):
            return webmastertools.SitemapsEntryFromString(response.ToString())
        return response
    def __post(self, author, title, summary, content, category, draft,
               entryXml):
        """ to post the content to the server
        @param author: Author name
        @type author: String
        @param title: Title of the content
        @type title: String
        @param summary: Summary of the content
        @type summary: String
        @param content: Content 
        @type content: String
        @param draft: Type of the document:
        @type draft: boolean
        @param entryXml: extra entry
        @type entryXml: String
        
        @rtype: (Atom Entry, String)
        @return: entry, httpResponse
        """
        # create/update the atom entry
        if entryXml == None:
            entry = atom.Entry()
            entryUri = self.entryUri

        else:
            entry = atom.EntryFromString(entryXml)
            entryUri = entry.GetEditLink().href
        entry.author = [atom.Author(text=author)]
        entry.title = atom.Title(text=title)
        entry.summary = atom.Summary(text=summary)
        entry.content = atom.Content(content_type="html",
                                     text=unicode(content, "utf-8"))
        if category != "":
            entry.category = atom.Category(term=category)
        if draft:
            entry.control = atom.Control(draft=atom.Draft(text="yes"))
        else:
            entry.control = atom.Control(draft=atom.Draft(text="no"))
        # setup the http headers for authorisation
        extraHeaders = {"Slug": title}
        extraHeaders.update(self.authHeaders)
        # use POST or PUT depending on whether it is a new entry or an update
        if entryXml != None:
            publishFunc = self.atomService.Put
        else:
            publishFunc = self.atomService.Post
        self.__checkNoProxy(entryUri)
        httpResponse = publishFunc(data=entry,
                                   uri=entryUri,
                                   extra_headers=extraHeaders)
        self.__resetProxy()
        return entry, httpResponse
Example #15
0
 def testInsertPhotoUpdateBlobAndDelete(self):
   new_entry = gdata.photos.PhotoEntry()
   new_entry.title = atom.Title(text='a_test_image')
   new_entry.summary = atom.Summary(text='Just a test.')
   new_entry.category.append(atom.Category(
       scheme='http://schemas.google.com/g/2005#kind', 
       term='http://schemas.google.com/photos/2007#photo'))
   entry = self.client.InsertPhoto(self.test_album, new_entry, 
       test_image_location, content_type='image/jpeg')
   self.assert_(entry.id.text)
   updated_entry = self.client.UpdatePhotoBlob(entry, test_image_location)
   self.assert_(entry.GetEditLink().href != updated_entry.GetEditLink().href)
   self.client.Delete(updated_entry)
Example #16
0
    def AddMobileSitemap(self,
                         site_uri,
                         sitemap_uri,
                         sitemap_mobile_markup_language='XHTML',
                         uri=SITEMAPS_FEED_TEMPLATE,
                         url_params=None,
                         escape_params=True,
                         converter=None):
        """Adds a mobile sitemap to a site.

        Args:
          site_uri: str URI of which site to add sitemap for.
          sitemap_uri: str URI of sitemap to add to a site.
          sitemap_mobile_markup_language: str Format of added sitemap. Valid types:
                                          XHTML, WML, or cHTML.
          uri: str (optional) URI template to add a sitemap.
               Default SITEMAP_FEED_TEMPLATE.
          url_params: dict (optional) Additional URL parameters to be included
                      in the insertion request.
          escape_params: boolean (optional) If true, the url_parameters will be
                         escaped before they are included in the request.
          converter: func (optional) Function which is executed on the server's
              response before it is returned. Usually this is a function like
              SitemapsEntryFromString which will parse the response and turn it into
              an object.

        Returns:
          If converter is defined, the results of running converter on the server's
          response. Otherwise, it will be a SitemapsEntry object.
        """
        # FIXME
        sitemap_entry = webmastertools.SitemapsEntry(
            atom_id=atom.Id(text=sitemap_uri),
            category=atom.Category(
                scheme='http://schemas.google.com/g/2005#kind',
                term='http://schemas.google.com/webmasters/tools/2007#sitemap-mobile'),
            sitemap_mobile_markup_language= \
                webmastertools.SitemapMobileMarkupLanguage(
                    text=sitemap_mobile_markup_language))
        print(sitemap_entry)
        response = self.Post(sitemap_entry,
                             uri %
                             {'site_id': urllib.parse.quote_plus(site_uri)},
                             url_params=url_params,
                             escape_params=escape_params,
                             converter=converter)
        if not converter and isinstance(response, atom.Entry):
            return webmastertools.SitemapsEntryFromString(response.ToString())
        return response
Example #17
0
    def UpdatePreferredDomain(self,
                              site_uri,
                              preferred_domain,
                              uri=SITE_TEMPLATE,
                              url_params=None,
                              escape_params=True,
                              converter=None):
        """Updates preferred domain setting of a site.

        Note that if using 'preferwww', will also need www.example.com in account to
        take effect.

        Args:
          site_uri: str URI of which site to add sitemap for.
          preferred_domain: str The preferred domain for a site. Valid values are 'none',
                            'preferwww', and 'prefernowww'.
          uri: str (optional) URI template to update a site.
               Default SITE_TEMPLATE.
          url_params: dict (optional) Additional URL parameters to be included
                      in the insertion request.
          escape_params: boolean (optional) If true, the url_parameters will be
                         escaped before they are included in the request.
          converter: func (optional) Function which is executed on the server's
              response before it is returned. Usually this is a function like
              SitemapsEntryFromString which will parse the response and turn it into
              an object.

        Returns:
          If converter is defined, the results of running converter on the server's
          response. Otherwise, it will be a SitesEntry object.
        """

        site_entry = webmastertools.SitesEntry(
            atom_id=atom.Id(text=site_uri),
            category=atom.Category(
                scheme='http://schemas.google.com/g/2005#kind',
                term=
                'http://schemas.google.com/webmasters/tools/2007#sites-info'),
            preferred_domain=webmastertools.PreferredDomain(
                text=preferred_domain))
        response = self.Put(site_entry,
                            uri % urllib.quote_plus(site_uri),
                            url_params=url_params,
                            escape_params=escape_params,
                            converter=converter)
        if not converter and isinstance(response, atom.Entry):
            return webmastertools.SitesEntryFromString(response.ToString())
        return response
Example #18
0
    def MovePresentationIntoFolder(self, document_entry, folder_entry):
        """Moves a presentation into a folder in the Document List Feed.

    Args:
      document_entry: DocumentListEntry An object representing the source
          document.
      folder_entry: DocumentListEntry An object representing the destination
          folder.

    Returns:
      A GDataEntry containing information about the document created on
      the Google Documents service.
    """
        category = atom.Category(scheme=DATA_KIND_SCHEME,
                                 term=PRESENTATION_KIND_TERM)
        return self._MoveIntoFolder(document_entry, folder_entry, category)
Example #19
0
  def MoveFolderIntoFolder(self, src_folder_entry, dest_folder_entry):
    """Moves a folder into another folder.

    Args:
      src_folder_entry: DocumentListEntry An object with a link to the
          source folder.
      dest_folder_entry: DocumentListEntry An object with a link to the
          destination folder.

    Returns:
      A DocumentListEntry containing information about the folder created on
      the Google Documents service.
    """
    category = atom.Category(scheme=DATA_KIND_SCHEME,
                             term=FOLDER_KIND_TERM, label='folder')
    return self._MoveIntoFolder(src_folder_entry, dest_folder_entry, category)
Example #20
0
  def MoveSpreadsheetIntoFolder(self, document_entry, folder_entry):
    """Moves a spreadsheet into a folder in the Document List Feed.

    Args:
      document_entry: DocumentListEntry An object representing the source
          document.
      folder_entry: DocumentListEntry An object representing the destination
          folder.

    Returns:
      A DocumentListEntry containing information about the document created on
      the Google Documents service.
    """
    category = atom.Category(scheme=DATA_KIND_SCHEME,
                             term=SPREADSHEET_KIND_TERM, label='spreadsheet')
    return self._MoveIntoFolder(document_entry, folder_entry, category)
Example #21
0
  def UploadDocument(self, media_source, title):
    """Uploads a document inside of a MediaSource object to the Document List
       feed with the given title.

    Args:
      media_source: MediaSource The gdata.MediaSource object containing a
                    document file to be uploaded.
      title: string The title of the document on the server after being
             uploaded.

    Returns:
      A GDataEntry containing information about the document created on the
      Google Documents service.
    """
    category = atom.Category(scheme=DATA_KIND_SCHEME,
        term=DOCUMENT_KIND_TERM)
    return self._UploadFile(media_source, title, category)
Example #22
0
    def VerifySite(self,
                   site_uri,
                   verification_method,
                   uri=SITE_TEMPLATE,
                   url_params=None,
                   escape_params=True,
                   converter=None):
        """Requests a verification of a site.

    Args: 
      site_uri: str URI of which site to add sitemap for.
      verification_method: str The method to verify a site. Valid values are
                           'htmlpage', and 'metatag'.
      uri: str (optional) URI template to update a site.
           Default SITE_TEMPLATE.
      url_params: dict (optional) Additional URL parameters to be included
                  in the insertion request. 
      escape_params: boolean (optional) If true, the url_parameters will be
                     escaped before they are included in the request.
      converter: func (optional) Function which is executed on the server's
          response before it is returned. Usually this is a function like
          SitemapsEntryFromString which will parse the response and turn it into
          an object.

    Returns:
      If converter is defined, the results of running converter on the server's
      response. Otherwise, it will be a SitesEntry object.
    """

        site_entry = webmastertools.SitesEntry(
            atom_id=atom.Id(text=site_uri),
            category=atom.Category(
                scheme='http://schemas.google.com/g/2005#kind',
                term=
                'http://schemas.google.com/webmasters/tools/2007#sites-info'),
            verification_method=webmastertools.VerificationMethod(
                type=verification_method, in_use='true'))
        response = self.Put(site_entry,
                            uri % six.moves.urllib.parse.quote_plus(site_uri),
                            url_params=url_params,
                            escape_params=escape_params,
                            converter=converter)
        if not converter and isinstance(response, atom.Entry):
            return webmastertools.SitesEntryFromString(response.ToString())
        return response
Example #23
0
    def UpdateEnhancedImageSearch(self,
                                  site_uri,
                                  enhanced_image_search,
                                  uri=SITE_TEMPLATE,
                                  url_params=None,
                                  escape_params=True,
                                  converter=None):
        """Updates enhanced image search setting of a site.

        Args:
          site_uri: str URI of which site to add sitemap for.
          enhanced_image_search: str The enhanced image search setting for a site.
                                 Valid values are 'true', and 'false'.
          uri: str (optional) URI template to update a site.
               Default SITE_TEMPLATE.
          url_params: dict (optional) Additional URL parameters to be included
                      in the insertion request.
          escape_params: boolean (optional) If true, the url_parameters will be
                         escaped before they are included in the request.
          converter: func (optional) Function which is executed on the server's
              response before it is returned. Usually this is a function like
              SitemapsEntryFromString which will parse the response and turn it into
              an object.

        Returns:
          If converter is defined, the results of running converter on the server's
          response. Otherwise, it will be a SitesEntry object.
        """

        site_entry = webmastertools.SitesEntry(
            atom_id=atom.Id(text=site_uri),
            category=atom.Category(
                scheme='http://schemas.google.com/g/2005#kind',
                term=
                'http://schemas.google.com/webmasters/tools/2007#sites-info'),
            enhanced_image_search=webmastertools.EnhancedImageSearch(
                text=enhanced_image_search))
        response = self.Put(site_entry,
                            uri % urllib.quote_plus(site_uri),
                            url_params=url_params,
                            escape_params=escape_params,
                            converter=converter)
        if not converter and isinstance(response, atom.Entry):
            return webmastertools.SitesEntryFromString(response.ToString())
        return response
Example #24
0
    def UpdateGeoLocation(self,
                          site_uri,
                          geolocation,
                          uri=SITE_TEMPLATE,
                          url_params=None,
                          escape_params=True,
                          converter=None):
        """Updates geolocation setting of a site.

        Args:
          site_uri: str URI of which site to add sitemap for.
          geolocation: str The geographic location. Valid values are listed in
                       http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
          uri: str (optional) URI template to update a site.
               Default SITE_TEMPLATE.
          url_params: dict (optional) Additional URL parameters to be included
                      in the insertion request.
          escape_params: boolean (optional) If true, the url_parameters will be
                         escaped before they are included in the request.
          converter: func (optional) Function which is executed on the server's
              response before it is returned. Usually this is a function like
              SitemapsEntryFromString which will parse the response and turn it into
              an object.

        Returns:
          If converter is defined, the results of running converter on the server's
          response. Otherwise, it will be a SitesEntry object.
        """

        site_entry = webmastertools.SitesEntry(
            atom_id=atom.Id(text=site_uri),
            category=atom.Category(
                scheme='http://schemas.google.com/g/2005#kind',
                term=
                'http://schemas.google.com/webmasters/tools/2007#sites-info'),
            geolocation=webmastertools.GeoLocation(text=geolocation))
        response = self.Put(site_entry,
                            uri % urllib.parse.quote_plus(site_uri),
                            url_params=url_params,
                            escape_params=escape_params,
                            converter=converter)
        if not converter and isinstance(response, atom.Entry):
            return webmastertools.SitesEntryFromString(response.ToString())
        return response
Example #25
0
    def createAlbum(self, folderName, public=True):
        gd_entry = gdata.GDataEntry()
        gd_entry.title = atom.Title(text=folderName)
        gd_entry.category.append(
            atom.Category(scheme='http://schemas.google.com/g/2005#kind',
                          term='http://schemas.google.com/photos/2007#album'))

        rights = public and "public" or "private"
        gd_entry.rights = atom.Rights(text=rights)

        ext_rights = atom.ExtensionElement(
            tag='access', namespace='http://schemas.google.com/photos/2007')
        ext_rights.text = rights
        gd_entry.extension_elements.append(ext_rights)

        album_entry = self.Post(
            gd_entry,
            'http://picasaweb.google.com/data/feed/api/user/' + self.email)

        return PicasaAlbum(self, album_entry)
Example #26
0
    def uploadPhoto(self, file, description=""):
        ms = gdata.MediaSource()

        try:
            ms.setFile(file, 'image/jpeg')
            metadata_entry = gdata.GDataEntry()
            name = os.path.basename(file)
            metadata_entry.title = atom.Title(text=name)
            metadata_entry.summary = atom.Summary(text=description)
            metadata_entry.category.append(
                atom.Category(
                    scheme='http://schemas.google.com/g/2005#kind',
                    term='http://schemas.google.com/photos/2007#photo'))

            link = self.__ae.link[
                0].href  # self.__ae.GetFeedLink().href on created album
            media_entry = self.__gd.Post(metadata_entry, link, media_source=ms)
            return True
        except gdata.service.RequestError:
            return False
Example #27
0
  def UploadDocument(self, media_source, title, folder_or_uri=None):
    """Uploads a document inside of a MediaSource object to the Document List
       feed with the given title.

    Args:
      media_source: MediaSource The gdata.MediaSource object containing a
          document file to be uploaded.
      title: string The title of the document on the server after being
          uploaded.
      folder_or_uri: DocumentListEntry or string (optional) An object with a
          link to a folder or a uri to a folder to upload to.
          Note: A valid uri for a folder is of the form:
                /feeds/folders/private/full/folder%3Afolder_id

    Returns:
      A DocumentListEntry containing information about the document created
      on the Google Documents service.
    """
    category = atom.Category(scheme=DATA_KIND_SCHEME,
                             term=DOCUMENT_KIND_TERM, label='document')
    return self._UploadFile(media_source, title, category, folder_or_uri)
Example #28
0
def blogPoster():
    
    if len(sys.argv)==1:
        print 'Error: argument required.'
    else:
        file = sys.argv[1]

    post = open(file)
    user ='******'
    #password = sys.argv[2] 
    password = getpass.getpass()

    # login
    blogger_service = service.GDataService(user,password)
    blogger_service.source = 'wjmBlogger-0.01'
    blogger_service.service = 'blogger'
    blogger_service.account_type = 'GOOGLE'
    blogger_service.server = 'www.blogger.com'
    blogger_service.ProgrammaticLogin()
    
    feed = blogger_service.Get('/feeds/default/blogs')    
    blog_id = feed.entry[0].GetSelfLink().href.split("/")[-1]


    entry = gdata.GDataEntry()
    entry.title = atom.Title('xhtml', text=post.readline())
    tags = post.readline().split(',')
    if tags == ['\n']:
        print 'no tags'
    else:
        for tag in tags :
            category = atom.Category(term=tag, scheme="http://www.blogger.com/atom/ns#")
            entry.category.append(category)
    entry.content = atom.Content(content_type='html', text=post.read()) 
    
    blogger_service.Post(entry, '/feeds/%s/posts/default' % blog_id)


    print('posted')
    post.close()
Example #29
0
    def label_posts(self, post_entries, tags):
        """Add or remove labels on a list of posts.

        Keyword arguments:
          post_entries: List of post entry objects.
          tags: String representation of tags in a comma separated list.
                For how tags are generated from the string,
                see googlecl.base.generate_tag_sets().
        """
        scheme = 'http://www.blogger.com/atom/ns#'
        remove_set, add_set, replace_tags = googlecl.base.generate_tag_sets(
            tags)
        successes = []
        for post in post_entries:
            # No point removing tags if we're replacing all of them.
            if remove_set and not replace_tags:
                # Keep categories if they meet one of two criteria:
                # 1) Are of a different scheme than the one we're looking at, or
                # 2) Are of the same scheme, but the term is in the 'remove'
                # set
                post.category = [
                    c for c in post.category if c.scheme != scheme or (
                        c.scheme == scheme and c.term not in remove_set)
                ]

            if replace_tags:
                # Remove categories that match the scheme we are updating.
                post.category = [
                    c for c in post.category if c.scheme != scheme
                ]
            if add_set:
                new_tags = [
                    atom.Category(term=tag, scheme=scheme) for tag in add_set
                ]
                post.category.extend(new_tags)
            updated_post = self.UpdatePost(post)
            if updated_post:
                successes.append(updated_post)
        return successes
 def _MakeKindCategory(self, label):
     if label is None:
         return None
     return atom.Category(scheme=DATA_KIND_SCHEME,
                          term=gdata.docs.DOCUMENTS_NAMESPACE + '#' + label,
                          label=label)