Ejemplo n.º 1
0
 def new(self, title='New Calendar', summary='New Calendar', place='A-Server', color='#2952A3', timezone='Africa/Cairo', hidden='false'):
     """
     Creates a new calendar using the given parameters in the user's calendars.
     
     @param title: string for the title of the new calendar to be created, default is "New Calendar"
     @param summary: string for the summary of the new calendar to be created, default is "New Calendar"
     @param place: string for the default location of the new calendar
     @param color: string for the color in hex for the online interface of the calendar, default is google's "blue" default for new calendars
     @param timezone: string for the time zone of the calendar
     @param hidden: boolean to decide whether the calendar is to be hidden or visible in the online interface
     
     """
     calendar = gdata.calendar.CalendarListEntry()
     calendar.title = atom.Title(text=title)
     calendar.summary = atom.Summary(text=summary)
     calendar.where = gdata.calendar.Where(value_string=place)
     calendar.color = gdata.calendar.Color(value=color)
     calendar.timezone = gdata.calendar.Timezone(value=timezone)
     calendar.hidden = gdata.calendar.Hidden(value=hidden)
     
     new_calendar = self._client.InsertCalendar(new_calendar=calendar)
     
     title = cleanString(title)
     self.calendars._addCalendar(self, self._client, new_calendar)
     q.logger.log('Calendar %s added'%title, 2)
     
     return new_calendar
    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'

        folder_entry = gdata.docs.DocumentListEntry()
        folder_entry.title = atom.Title(text=title)
        folder_entry.category.append(self._MakeKindCategory(FOLDER_LABEL))
        folder_entry = self.Post(
            folder_entry,
            uri,
            converter=gdata.docs.DocumentListEntryFromString)

        return folder_entry
Ejemplo n.º 3
0
    def InsertEvent(self,
                    title,
                    location,
                    description=None,
                    start_time=None,
                    attendees=[]):
        self.calendar_client = gdata.calendar.service.CalendarService()
        gdata.alt.appengine.run_on_appengine(self.calendar_client)
        self.calendar_client.SetAuthSubToken(self.client.GetAuthSubToken())

        event = gdata.calendar.CalendarEventEntry()
        event.title = atom.Title(text=title)
        event.content = atom.Content(text=description)
        event.where.append(gdata.calendar.Where(value_string=location))
        event.when.append(gdata.calendar.When(start_time=start_time))

        for attendee in attendees:
            who = gdata.calendar.Who()
            who.email = attendee
            event.who.append(who)

        new_event = self.calendar_client.InsertEvent(
            event, '/calendar/feeds/default/private/full')

        return new_event
Ejemplo n.º 4
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')
Ejemplo n.º 5
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)
Ejemplo n.º 6
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
Ejemplo n.º 7
0
    def upload_insert(self, client, album_id, options):
        """Uploads a new photo by inserting it into an album.
        """
        if options.dryrun:
            return
        album_url = '%s/%s' % (_ALBUM_URL, album_id)

        new_photo = gdata.photos.PhotoEntry()
        new_photo.title = atom.Title(text=self.title)
        comment = imageutils.get_photo_caption(self.photo,
                                               options.captiontemplate)
        if comment:
            new_photo.summary = atom.Summary(text=comment, summary_type='text')
        new_photo.media = gdata.media.Group()
        new_photo.media.keywords = gdata.media.Keywords(
            text=', '.join(self.get_export_keywords(options)))
        if options.gps and self.photo.gps:
            new_photo.geo = gdata.geo.Where()
            new_photo.geo.Point = gdata.geo.Point()
            new_photo.geo.Point.pos = gdata.geo.Pos(
                text='%.6f %.6f' %
                (self.photo.gps.latitude, self.photo.gps.longitude))
        # TODO(tilmansp): For some reason, this does not seem to work, and
        # all newly inserted images need a second update cycle to fix the
        # timestamp.
        if self.photo.date:
            new_photo.timestamp = gdata.photos.Timestamp(
                text=get_picasaweb_date(self.photo.date))

        client.throttle()
        self.picasa_photo = client.gd_client.InsertPhoto(
            album_url,
            new_photo,
            self.photo.image_path,
            content_type=get_content_type(self.photo.image_path))
def CreateAllHandsEvent(options, users):

  url = '/calendar/feeds/default/private/full'
  status = gdata.calendar.AttendeeStatus()
  status.value = 'INVITED'
  att_type = gdata.calendar.AttendeeType()
  att_type.value = 'REQUIRED'

  conn = GetCalendarConnection(options)

  start_time = '%sT%s:00.000Z' % (options.event_date, options.start_time)
  end_time = '%sT%s:00.000Z' % (options.event_date, options.end_time)

  event = gdata.calendar.CalendarEventEntry()
  event.title = atom.Title(text=options.title)
  event.content = atom.Content(text=options.description)
  event.where.append(gdata.calendar.Where(value_string=options.where))
  new_who = []
  for u in users:
    new_who.append(gdata.calendar.Who(email=u,
                                      attendee_status=status,
                                      attendee_type=att_type))
  event.who = new_who

  event.when.append(gdata.calendar.When(start_time=start_time,
                                        end_time=end_time))
  event.send_event_notifications = gdata.calendar.SendEventNotifications(value="true")

  return conn.InsertEvent(event, url)
def AddPhoto(filename, summary, title, imageFormat='jpeg', timestamp=None):
    if isImageFile(filename) == False:
        log('Not Image: %s', filename)
        OTHER_FILES.append(filename)
        return
    log('Uploading photo: %s', filename)
    url = '/data/feed/api/user/%s/albumid/%s?kind=photo' % (USERNAME, ALBUM_ID)
    metadata = gdata.photos.PhotoEntry()
    metadata.title = atom.Title(text=title)
    metadata.summary = atom.Summary(text=summary, summary_type='text')
    if UPDATE_FILE_METADATA == True and timestamp is not None:
        metadata.timestamp = gdata.photos.Timestamp(text=timestamp)
        metadata.published = atom.Published(
            text=metadata.timestamp.isoformat())
        metadata.updated = atom.Updated(text=metadata.timestamp.isoformat())
        UpdateFileMetadata(filename, metadata.timestamp.datetime())

    if DRY_RUN == False:
        try:
            photo = gd_client.InsertPhoto( \
                url, metadata, filename, 'image/' + imageFormat)
            if photo is None:
                ERRORS.append('Photo may not have been uploaded: ' + filename)
        except gdata.photos.service.GooglePhotosException:
            ERRORS.append('Photo may not have been uploaded: ' + filename)
Ejemplo n.º 10
0
    def editPost(self,
                 blogID,
                 postID,
                 title,
                 content,
                 author_name,
                 is_draft,
                 timestamp=None):

        # Create the entry to insert.
        entry = gdata.GDataEntry()
        entry.author.append(atom.Author(atom.Name(text='Post author')))
        entry.title = atom.Title('xhtml', text=title)
        entry.content = atom.Content('html', text=content)
        if is_draft:
            control = atom.Control()
            control.draft = atom.Draft(text='yes')
            entry.control = control

        # If a timestamp is specified, use that timestamp
        if timestamp:
            entry.published = atom.Published(timestamp)

        # Ask the service to insert the new entry.
        return self.service.Put(
            entry, '/feeds/' + blogID + '/posts/default/' + postID)
Ejemplo n.º 11
0
    def createPost(self,
                   blogID,
                   title,
                   content,
                   author_name,
                   is_draft,
                   timestamp=None):
        """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='Post author')))
        entry.title = atom.Title('xhtml', text=title)
        entry.content = atom.Content('html', text=content)
        if is_draft:
            control = atom.Control()
            control.draft = atom.Draft(text='yes')
            entry.control = control

        # If a timestamp is specified, use that timestamp
        if timestamp:
            entry.published = atom.Published(timestamp)

        # Ask the service to insert the new entry.
        return self.service.Post(entry, '/feeds/' + blogID + '/posts/default')
Ejemplo n.º 12
0
 def UpdateContactMenu(self):
   selected_entry = self._SelectContact()
   new_name = raw_input('Enter a new name for the contact: ')
   if not selected_entry.title:
     selected_entry.title = atom.Title()
   selected_entry.title.text = new_name
   self.gd_client.UpdateContact(selected_entry.GetEditLink().href, selected_entry)
Ejemplo n.º 13
0
    def upload_insert(self, client, album_id, options):
        """Uploads a new photo by inserting it into an album.
        """
        if options.dryrun:
            return
        album_url = '%s/%s' % (_ALBUM_URL, album_id)

        new_photo = gdata.photos.PhotoEntry()
        new_photo.title = atom.Title(text=self.title)
        # Combine title and description because PicasaWeb does not show the
        # title anywhere.
        comment = imageutils.get_photo_caption(self.photo,
                                               options.captiontemplate)
        export_keywords = self.get_export_keywords(options)
        photo_gps = self.photo.gps

        if comment:
            new_photo.summary = atom.Summary(text=comment, summary_type='text')
        new_photo.media = gdata.media.Group()
        new_photo.media.keywords = gdata.media.Keywords(
            text=', '.join(export_keywords))
        if options.gps and photo_gps:
            new_photo.geo = gdata.geo.Where()
            new_photo.geo.Point = gdata.geo.Point()
            new_photo.geo.Point.pos = gdata.geo.Pos(
                text='%.6f %.6f' % (photo_gps.latitude, photo_gps.longitude))

        client.throttle()
        self.picasa_photo = client.gd_client.InsertPhoto(
            album_url,
            new_photo,
            self.photo.image_path,
            content_type=get_content_type(self.photo.image_path))
Ejemplo n.º 14
0
    def add(self):
        """
        Add an address from From: field of a mail. This assumes a single mail file is supplied through stdin. . 
        """

        fromLine = ""
        for l in sys.stdin:
            if l.startswith("From: "):
                fromLine = l
                break
        if fromLine == "":
            print "Not a valid mail file!"
            sys.exit(2)
        #In a line like
        #From: John Doe <*****@*****.**>
        els = fromLine.split()
        #Drop "From: "
        del els[0]
        #get the last element as mail
        mailaddr = els[-1]
        if mailaddr.startswith("<"):
            mailaddr = mailaddr[1:]
        if mailaddr.endswith(">"):
            mailaddr = mailaddr[:-1]
        #and the rest as name
        name = " ".join(els[:-1])
        #save to contacts
        client = ContactsService()
        client.ClientLogin(self.username, self.password)
        new_contact = ContactEntry(title=atom.Title(text=name))
        new_contact.email.append(Email(address=mailaddr, primary='true'))
        contact_entry = client.CreateContact(new_contact)
        print contact_entry
Ejemplo n.º 15
0
    def save(self):

        self._meta.get_field('slug').pre_save(self, not self.pk)

        content = self.summary
        content += """<p><a target="_top" href="%s%s">Full event details</a></p>""" % (Site.objects.get_current().domain, self.get_absolute_url(), )

        if self.uri:
            # existing event, update
            entry = self.calendar.account.service.GetCalendarEventEntry(uri = self.edit_uri)
            entry.title.text = self.title
            entry.content.text = content
            start_time = format_datetime(self.start_time)
            end_time = format_datetime(self.end_time)
            entry.when = []
            entry.when.append(gdata.calendar.When(start_time = start_time, end_time = end_time))
            new_entry = with_request_error_try(lambda: self.calendar.account.service.UpdateEvent(entry.GetEditLink().href, entry))
        else:
            entry = gdata.calendar.CalendarEventEntry()
            entry.title = atom.Title(text = self.title)
            entry.content = atom.Content(text = content)
            if not self.start_time:
                self.start_time = datetime.datetime.utcnow()
            if not self.end_time:
                self.end_time = self.start_time + datetime.timedelta(hours = 1)
            start_time = format_datetime(self.start_time)
            end_time = format_datetime(self.end_time)
            entry.when.append(gdata.calendar.When(start_time = start_time, end_time = end_time))
            new_entry = with_request_error_try(lambda: self.calendar.account.service.InsertEvent(entry, self.calendar.feed_uri))
            self.uri = new_entry.id.text
            self.edit_uri = new_entry.GetEditLink().href
            self.view_uri = new_entry.GetHtmlLink().href

        super(Event, self).save()
Ejemplo n.º 16
0
 def send(self):
     """Add new event and set SMS-reminder"""
     event = gdata.calendar.CalendarEventEntry()
     event.title = atom.Title(text=self.title)
     event.content = atom.Content(text='')
     event.where.append(gdata.calendar.Where(value_string=self.location))
     # Set start time in 6 minutes
     start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z',
                                 time.gmtime(time.time() + 6 * 60))
     # Set end time in an hour
     end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z',
                                 time.gmtime(time.time() + 3600))
     event.when.append(gdata.calendar.When(start_time=start_time,
                                             end_time=end_time))
     minutes = 5
     for a_when in event.when:
         if len(a_when.reminder) > 0:
             # Adding reminder in 5 minutes before event (start_time)
             a_when.reminder[0].minutes = 5
         else:
             a_when.reminder.append(
                     gdata.calendar.Reminder(minutes=minutes))
     # Insert new event
     new_event = self.calendar_service.InsertEvent(event,
                                                 self.calendar_link)
     return new_event
Ejemplo n.º 17
0
    def full_add_event(self, titles, calendar_user, date, reminder):
        """Create an event piece by piece (no quick add).

        Args:
          titles: List of titles of events.
          calendar_user: "******" of the calendar to add to.
          date: Text representation of a date and/or time.
          reminder: Number of minutes before event to send reminder. Set to 0 for no
              reminder.

        Returns:
          Response entries from batch-inserting the events.
        """

        import atom
        request_feed = gdata.calendar.CalendarEventFeed()
#    start_text, _, end_text = googlecl.calendar.date.split_string(date, [','])
        parser = DateRangeParser()
        date_range = parser.parse(date)
        start_time, end_time = date_range.to_when()
        for title in titles:
            event = gdata.calendar.CalendarEventEntry()
            event.title = atom.Title(text=title)
            when = gdata.calendar.When(start_time=start_time,
                                       end_time=end_time)
            if reminder:
                when.reminder.append(gdata.calendar.Reminder(minutes=reminder))
            event.when.append(when)
            request_feed.AddInsert(event, 'insert-' + title[0:5])
        response_feed = self.ExecuteBatch(request_feed,
                                          USER_BATCH_URL_FORMAT % calendar_user)
        return response_feed.entry
Ejemplo n.º 18
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
Ejemplo n.º 19
0
def send_events(client, api_url, events):
    """Send events to Google Calendar.
    
    client - a CalendarService object
    api_url - the URL to send events to
    events - a list of Event objects
    """
    for event in events:
        # TODO - we need to check whether to insert or update an existing entry
        gevent = gdata.calendar.CalendarEventEntry()
        gevent.title = atom.Title(text=event.subject)
        gevent.content = atom.Content(text=event.description)
        gevent.where.append(gdata.calendar.Where(value_string=event.location))
        if event.recurrence:
            gevent.recurrence = gdata.calendar.Recurrence(
                text=event.recurrence)
        else:
            gevent.when.append(
                gdata.calendar.When(
                    start_time=event.start.strftime(GOOGLE_STRFTIME),
                    end_time=event.end.strftime(GOOGLE_STRFTIME)))

        print "sending new event (%s%s) to %s" % (
            event.start.strftime('%Y-%m-%d %H:%M'),
            event.recurrence and ' recurring' or '', api_url)
        try:
            new_event = client.InsertEvent(gevent, api_url)
        except gdata.service.RequestError, e:
            # Google sometimes barfs
            new_event = client.InsertEvent(gevent, api_url)
Ejemplo n.º 20
0
  def SendNotice(self, subject, body=None, content_type='html',
                 ccr=None, profile_id=None):
    """Sends (posts) a notice to the user's Google Health profile.

    Args:
      subject: A string representing the message's subject line.
      body: string (optional) The message body.
      content_type: string (optional) The content type of the notice message
          body.  This parameter is only honored when a message body is
          specified.
      ccr: string (optional) The CCR XML document to reconcile into the
          user's profile.
      profile_id: string (optional) The profile id to work with when using
          ClientLogin.  Note: this parameter is ignored if query is set.

    Returns:
      A gdata.health.ProfileEntry object of the posted entry.
    """
    if body:
      content = atom.Content(content_type=content_type, text=body)
    else:
      content = body

    entry = gdata.GDataEntry(
        title=atom.Title(text=subject), content=content,
        extension_elements=[atom.ExtensionElementFromString(ccr)])

    projection = profile_id and 'ui' or 'default'
    query = HealthRegisterQuery(service=self.__get_service(),
                                projection=projection, profile_id=profile_id)
    return self.Post(entry, query.ToUri(),
                     converter=gdata.health.ProfileEntryFromString)
Ejemplo n.º 21
0
    def testPostAndDeleteExtendedPropertyEvent(self):
        """Test posting a new entry with an extended property, deleting it"""
        # Get random data for creating event
        r = random.Random()
        r.seed()
        random_event_number = str(r.randint(100000, 1000000))
        random_event_title = 'My Random Extended Property Test Event %s' % (
            random_event_number)

        # Set event data
        event = gdata.calendar.CalendarEventEntry()
        event.author.append(
            atom.Author(name=atom.Name(text='GData Test user')))
        event.title = atom.Title(text=random_event_title)
        event.content = atom.Content(text='Picnic with some lunch')
        event.extended_property.append(
            gdata.calendar.ExtendedProperty(name='prop test name',
                                            value='prop test value'))

        # Insert event
        self.cal_client.ProgrammaticLogin()
        new_event = self.cal_client.InsertEvent(
            event, '/calendar/feeds/default/private/full')

        self.assertEquals(event.extended_property[0].value,
                          new_event.extended_property[0].value)

        # Delete the event
        self.cal_client.DeleteEvent(new_event.GetEditLink().href)
Ejemplo n.º 22
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)
Ejemplo n.º 23
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)
Ejemplo n.º 24
0
 def _export_task(self, cr, uid, data, context):
     obj_user = pooler.get_pool(cr.dbname).get('res.users')
     blog_auth_details = obj_user.read(cr, uid, uid, [])
     if not blog_auth_details['blogger_email'] or not blog_auth_details[
             'blogger_password']:
         raise osv.except_osv(
             'Warning !',
             'Please  blogger Enter email id and password in users')
     try:
         self.blog_service = service.GDataService(
             blog_auth_details['blogger_email'],
             blog_auth_details['blogger_password'])
         self.blog_service.source = 'Tiny'
         self.blog_service.service = 'blogger'
         self.blog_service.server = 'www.blogger.com'
         self.blog_service.ProgrammaticLogin()
         feed = self.blog_service.Get('/feeds/default/blogs')
         self_link = feed.entry[0].GetSelfLink()
         if self_link:
             self.blog_id = self_link.href.split('/')[-1]
         obj_task = pooler.get_pool(cr.dbname).get('project.task')
         data_task = obj_task.read(cr, uid, data['form']['blog_id'][0][2],
                                   [])
         for task in data_task:
             entry = gdata.GDataEntry()
             entry.author.append(atom.Author(atom.Name(text='uid')))
             entry.title = atom.Title(title_type='xhtml', text=task['name'])
             entry.content = atom.Content(content_type='html',
                                          text=task['description'])
             self.blog_service.Post(
                 entry, '/feeds/' + self.blog_id + '/posts/default')
         return {'summary': 'Succefully sent tasks to blogger'}
     except Exception, e:
         raise osv.except_osv('Error !', e)
Ejemplo n.º 25
0
    def InsertTag(self, photo_or_uri, tag):
        """Add a tag (a.k.a. keyword) to a photo.

    Needs authentication, see self.ClientLogin()

    Arguments:
    photo_or_uri: a gdata.photos.PhotoEntry that will be tagged, or a
      `post' uri pointing to it
    (string) tag: The tag/keyword

    Returns:
    The new gdata.photos.TagEntry

    Example:
    p = GetFeed(PhotoUri)
    tag = InsertTag(p, 'Beautiful sunsets')

    """
        tag = gdata.photos.TagEntry(title=atom.Title(text=tag))
        if isinstance(photo_or_uri, (str, unicode)):
            post_uri = photo_or_uri  # it's a uri
        elif hasattr(photo_or_uri, 'GetEditMediaLink'):
            post_uri = photo_or_uri.GetPostLink().href
        try:
            return self.Post(data=tag,
                             uri=post_uri,
                             converter=gdata.photos.TagEntryFromString)
        except gdata.service.RequestError, e:
            raise GooglePhotosException(e.args[0])
Ejemplo n.º 26
0
    def testPostDraftUpdateAndDelete(self):
        new_entry = gdata.blogger.BlogPostEntry(title=atom.Title(
            text='Unit Test Post'))
        new_entry.content = atom.Content('text', None, 'Hello World')
        # Make this post a draft so it will not appear publicly on the blog.
        new_entry.control = atom.Control(draft=atom.Draft(text='yes'))
        new_entry.AddLabel('test')

        posted = self.client.AddPost(new_entry, blog_id=test_blog_id)

        self.assertEqual(posted.title.text, new_entry.title.text)
        # Should be one category in the posted entry for the 'test' label.
        self.assertEqual(len(posted.category), 1)
        self.assertTrue(isinstance(posted, gdata.blogger.BlogPostEntry))

        # Change the title and add more labels.
        posted.title.text = 'Updated'
        posted.AddLabel('second')
        updated = self.client.UpdatePost(entry=posted)

        self.assertEqual(updated.title.text, 'Updated')
        self.assertEqual(len(updated.category), 2)

        # Cleanup and delete the draft blog post.
        self.client.DeletePost(entry=posted)
Ejemplo n.º 27
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)
Ejemplo n.º 28
0
  def _UploadFile(self, media_source, title, category, folder_or_uri=None):
    """Uploads a file to the Document List feed.

    Args:
      media_source: A gdata.MediaSource object containing the file to be
          uploaded.
      title: string The title of the document on the server after being
          uploaded.
      category: An atom.Category object specifying the appropriate document
          type.
      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.
    """
    if folder_or_uri:
      try:
        uri = folder_or_uri.content.src
      except AttributeError:
        uri = folder_or_uri
    else:
      uri = '/feeds/documents/private/full'

    entry = gdata.docs.DocumentListEntry()
    entry.title = atom.Title(text=title)
    if category is not None:
      entry.category.append(category)
    entry = self.Post(entry, uri, media_source=media_source,
                      extra_headers={'Slug': media_source.file_name},
                      converter=gdata.docs.DocumentListEntryFromString)
    return entry
Ejemplo n.º 29
0
    def AddWorksheet(self, title, row_count, col_count, key):
        """Creates a new worksheet in the desired spreadsheet.

    The new worksheet is appended to the end of the list of worksheets. The
    new worksheet will only have the available number of columns and cells 
    specified.

    Args:
      title: str The title which will be displayed in the list of worksheets.
      row_count: int or str The number of rows in the new worksheet.
      col_count: int or str The number of columns in the new worksheet.
      key: str The spreadsheet key to the spreadsheet to which the new 
          worksheet should be added. 

    Returns:
      A SpreadsheetsWorksheet if the new worksheet was created succesfully.  
    """
        new_worksheet = gdata.spreadsheet.SpreadsheetsWorksheet(
            title=atom.Title(text=title),
            row_count=gdata.spreadsheet.RowCount(text=str(row_count)),
            col_count=gdata.spreadsheet.ColCount(text=str(col_count)))
        return self.Post(
            new_worksheet,
            'https://%s/feeds/worksheets/%s/private/full' % (self.server, key),
            converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString)
Ejemplo n.º 30
0
    def _upload_content(self,
                        post_title,
                        content,
                        blog_id=None,
                        is_draft=False):
        """Uploads content.

        Keyword arguments:
          blog_title: Title of the blog to post to.
          title: Title to give the post.
          content: String to get posted. This may be contents from a file, but NOT
                   the path itself!
          is_draft: If this content is a draft post or not. (Default False)

        Returns:
          Entry of post. (Returns same results as self.AddPost())
        """
        entry = gdata.blogger.BlogPostEntry()
        entry.title = atom.Title(title_type='xhtml', text=post_title)
        entry.content = atom.Content(content_type='html', text=content)
        if is_draft:
            control = atom.Control()
            control.draft = atom.Draft(text='yes')
            entry.control = control
        return self.AddPost(entry, blog_id)