def InsertEvent(cs, url, title, content, where, start, end, items): event = gdata.calendar.CalendarEventEntry() event.title = atom.Title(text=title) event.content = atom.Content(text=content) event.where.append(gdata.calendar.Where(value_string=where)) event.when.append(gdata.calendar.When(start_time=start, end_time=end)) for key, val in items.items(): event.extended_property.append( gdata.calendar.ExtendedProperty(name=str(key), value=str(val))) newevent = cs.InsertEvent(event, url) return newevent
def UpdateReview(self, entry, title, content, rating=None): if isinstance(entry, (str, unicode)): entry = self.Get(entry, douban.ReviewEntryFromString) entry.title = atom.Title(text=title) entry.content = atom.Content(text=content) if rating: entry.rating = douban.Rating(value=rating) uri = entry.GetSelfLink().href return self.Put(entry, uri, converter=douban.ReviewEntryFromString)
def _InsertQuickAddEvent(self, content="Tennis with John today 3pm-3:30pm"): """Creates an event with the quick_add property set to true so the content is processed as quick add content instead of as an event description.""" event = gdata.calendar.CalendarEventEntry() event.content = atom.Content(text=content) event.quick_add = gdata.calendar.QuickAdd(value='true') new_event = self.cal_client.InsertEvent( event, '/calendar/feeds/default/private/full') return new_event
def testCreateUpdateDeleteContactAndUpdatePhoto(self): DeleteTestContact(self.gd_client) # Create a new entry new_entry = gdata.contacts.ContactEntry() new_entry.title = atom.Title(text='Elizabeth Bennet') new_entry.content = atom.Content(text='Test Notes') new_entry.email.append(gdata.contacts.Email( rel='http://schemas.google.com/g/2005#work', primary='true', address='*****@*****.**')) new_entry.phone_number.append(gdata.contacts.PhoneNumber( rel='http://schemas.google.com/g/2005#work', text='(206)555-1212')) new_entry.organization = gdata.contacts.Organization( org_name=gdata.contacts.OrgName(text='TestCo.'), rel='http://schemas.google.com/g/2005#work') entry = self.gd_client.CreateContact(new_entry) # Generate and parse the XML for the new entry. self.assertEquals(entry.title.text, new_entry.title.text) self.assertEquals(entry.content.text, 'Test Notes') self.assertEquals(len(entry.email), 1) self.assertEquals(entry.email[0].rel, new_entry.email[0].rel) self.assertEquals(entry.email[0].address, '*****@*****.**') self.assertEquals(len(entry.phone_number), 1) self.assertEquals(entry.phone_number[0].rel, new_entry.phone_number[0].rel) self.assertEquals(entry.phone_number[0].text, '(206)555-1212') self.assertEquals(entry.organization.org_name.text, 'TestCo.') # Edit the entry. entry.phone_number[0].text = '(555)555-1212' updated = self.gd_client.UpdateContact(entry.GetEditLink().href, entry) self.assertEquals(updated.content.text, 'Test Notes') self.assertEquals(len(updated.phone_number), 1) self.assertEquals(updated.phone_number[0].rel, entry.phone_number[0].rel) self.assertEquals(updated.phone_number[0].text, '(555)555-1212') # Change the contact's photo. updated_photo = self.gd_client.ChangePhoto(test_image_location, updated, content_type='image/jpeg') # Refetch the contact so that it has the new photo link updated = self.gd_client.GetContact(updated.GetSelfLink().href) self.assert_(updated.GetPhotoLink() is not None) # Fetch the photo data. hosted_image = self.gd_client.GetPhoto(updated) self.assert_(hosted_image is not None) # Delete the entry. self.gd_client.DeleteContact(updated.GetEditLink().href)
def testPostEntryWithCommentAndDelete(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 Comments 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') # Insert event self.cal_client.ProgrammaticLogin() new_event = self.cal_client.InsertEvent( event, '/calendar/feeds/default/private/full') # Get comments feed comments_url = new_event.comments.feed_link.href comments_query = gdata.calendar.service.CalendarEventCommentQuery( comments_url) comments_feed = self.cal_client.CalendarQuery(comments_query) # Add comment comments_entry = gdata.calendar.CalendarEventCommentEntry() comments_entry.content = atom.Content(text='Comments content') comments_entry.author.append( atom.Author(name=atom.Name(text='GData Test user'), email=atom.Email(text=username))) new_comments_entry = self.cal_client.InsertEventComment( comments_entry, comments_feed.GetPostLink().href) # Delete the event event_to_delete = self.cal_client.GetCalendarEventEntry( new_event.id.text) self.cal_client.DeleteEvent(event_to_delete.GetEditLink().href)
def _InsertQuickAddEvent( self, content="Tennis with John today ... 3pm-3:30pm ... ok?", title=None): """Creates an event with the quick_add property set to true so the content is processed as quick add content instead of as an event description.""" event = gdata.calendar.CalendarEventEntry() event.content = atom.Content(text=content) event.quick_add = gdata.calendar.QuickAdd(value='true') new_event = self.cal_client.InsertEvent( event, '/calendar/feeds/default/private/full') if title: new_event.quick_add = gdata.calendar.QuickAdd(value='false') new_event.title = atom.Title(text=title) new_event.content = atom.Content(text=content) self.cal_client.UpdateEvent(new_event.GetEditLink().href, new_event) return new_event
def testCreateAndDeleteContactUsingBatch(self): # Get random data for creating contact r = random.Random() random_contact_number = str(r.randint(100000, 1000000)) random_contact_title = 'Random Contact %s' % ( random_contact_number) # Set contact data contact = gdata.contacts.ContactEntry() contact.title = atom.Title(text=random_contact_title) contact.email = gdata.contacts.Email( address='*****@*****.**' % random_contact_number, primary='true', rel=gdata.contacts.REL_WORK) contact.content = atom.Content(text='Contact created by ' 'gdata-python-client automated test ' 'suite.') # Form a batch request batch_request = gdata.contacts.ContactsFeed() batch_request.AddInsert(entry=contact) # Execute the batch request to insert the contact. self.gd_client.ProgrammaticLogin() default_batch_url = gdata.contacts.service.DEFAULT_BATCH_URL batch_result = self.gd_client.ExecuteBatch(batch_request, default_batch_url) self.assertEquals(len(batch_result.entry), 1) self.assertEquals(batch_result.entry[0].title.text, random_contact_title) self.assertEquals(batch_result.entry[0].batch_operation.type, gdata.BATCH_INSERT) self.assertEquals(batch_result.entry[0].batch_status.code, '201') expected_batch_url = re.compile('default').sub( urllib.quote(self.gd_client.email), gdata.contacts.service.DEFAULT_BATCH_URL) self.failUnless(batch_result.GetBatchLink().href, expected_batch_url) # Create a batch request to delete the newly created entry. batch_delete_request = gdata.contacts.ContactsFeed() batch_delete_request.AddDelete(entry=batch_result.entry[0]) batch_delete_result = self.gd_client.ExecuteBatch( batch_delete_request, batch_result.GetBatchLink().href) self.assertEquals(len(batch_delete_result.entry), 1) self.assertEquals(batch_delete_result.entry[0].batch_operation.type, gdata.BATCH_DELETE) self.assertEquals(batch_result.entry[0].batch_status.code, '201')
def AddDoumail(self, receiverURI, subject, body): entry = douban.DoumailEntry() entry.entity.append( douban.Entity('receiver', "", extension_elements=[atom.Uri(text=receiverURI)])) entry.title = atom.Title(text=subject) entry.content = atom.Content(text=body) return self.Post(entry, '/doumails', converter=douban.DoumailEntryFromString)
def testCreateAndDeleteContactUsingBatch(self): if not conf.options.get_value('runlive') == 'true': return conf.configure_service_cache(self.gd_client, 'testCreateAndDeleteContactUsingBatch') # Get random data for creating contact random_contact_number = 'notRandom12' random_contact_title = 'Random Contact %s' % (random_contact_number) # Set contact data contact = gdata.contacts.ContactEntry() contact.title = atom.Title(text=random_contact_title) contact.email = gdata.contacts.Email(address='*****@*****.**' % random_contact_number, primary='true', rel=gdata.contacts.REL_WORK) contact.content = atom.Content(text='Contact created by ' 'gdata-python-client automated test ' 'suite.') # Form a batch request batch_request = gdata.contacts.ContactsFeed() batch_request.AddInsert(entry=contact) # Execute the batch request to insert the contact. default_batch_url = gdata.contacts.service.DEFAULT_BATCH_URL batch_result = self.gd_client.ExecuteBatch(batch_request, default_batch_url) self.assertEqual(len(batch_result.entry), 1) self.assertEqual(batch_result.entry[0].title.text, random_contact_title) self.assertEqual(batch_result.entry[0].batch_operation.type, gdata.BATCH_INSERT) self.assertEqual(batch_result.entry[0].batch_status.code, '201') expected_batch_url = re.compile('default').sub( urllib.parse.quote(self.gd_client.email), gdata.contacts.service.DEFAULT_BATCH_URL) self.assertTrue(batch_result.GetBatchLink().href, expected_batch_url) # Create a batch request to delete the newly created entry. batch_delete_request = gdata.contacts.ContactsFeed() batch_delete_request.AddDelete(entry=batch_result.entry[0]) batch_delete_result = self.gd_client.ExecuteBatch( batch_delete_request, batch_result.GetBatchLink().href) self.assertEqual(len(batch_delete_result.entry), 1) self.assertEqual(batch_delete_result.entry[0].batch_operation.type, gdata.BATCH_DELETE) self.assertEqual(batch_result.entry[0].batch_status.code, '201')
def process(self): import gdata.contacts.service import atom from etl_test import etl_test import etl calendar_service = self.connector.open() event = gdata.calendar.CalendarEventEntry() for channel, trans in self.input_get().items(): for iterator in trans: for d in iterator: event.title = atom.Title(text=d['name']) event.content = atom.Content(text=d['name']) start_time = d['date_begin'] timestring = time.strftime( self.datetime_format, time.gmtime( time.mktime( time.strptime(start_time, self.datetime_format)))) starttime = time.strptime(timestring, self.datetime_format) start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', starttime) end_time = d['date_end'] timestring_end = time.strftime( self.datetime_format, time.gmtime( time.mktime( time.strptime(end_time, self.datetime_format)))) endtime = time.strptime(timestring_end, self.datetime_format) end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', endtime) if start_time is None: start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime()) end_time = time.strftime( '%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 3600)) event.when = [] event.when.append( gdata.calendar.When(start_time=start_time, end_time=end_time)) new_event = calendar_service.InsertEvent( event, "/calendar/feeds/default/private/full") d.update({'calendar': new_event}) yield d, 'main'
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
def post_job(self, title, content): """ Post a job with given title and content """ # Create the entry to insert. entry = gdata.GDataEntry() entry.author.append(atom.Author(atom.Name(text="Post Author"))) entry.title = atom.Title(title_type='xhtml', text=title) entry.content = atom.Content(content_type='html', text=content) # Ask the service to insert the new entry. job_post = self.service.Post( entry, '/feeds/' + str(self.blog_id) + '/posts/default') print "Successfully created post: \"" + job_post.title.text + "\".\n"
def __getEntryForDocument(self, queryPath, id): """ @param queryPath: Query to search for the entry @type queryPath: String @param id: Id to be applied to atom feed @type id: String @rtype: ElementTree._Element, or xml_wrapper.ElementWrapper @return entry """ docPath = self.rep.getPathForId(id) # check docPath if docPath.startswith(queryPath): item = self.rep.getItem(docPath) if item.hasHtml: docPath = self.iceContext.fs.splitExt(docPath)[0] + ".htm" title = item.getMeta("title") try: title = title.decode("utf-8") except: msg = "[Can not display title because of an encoding error!]" print "%s\n title='%s' path='%s'\n" % (msg, title, docPath) title = msg content = item.getRendition(".xhtml.body") if content is None: content = "<p>[Not rendered!]</p>" contentElem = ElementTree.XML(content) firstPara = contentElem.find("p") summary = "No summary" if firstPara != None: summary = ElementTree.tostring(firstPara) name = item.name lastModifiedTime = self.iceContext.fs.getModifiedTime( self.rep.getAbsPath(name)) entryDate = datetime.fromtimestamp( lastModifiedTime).isoformat() + 'Z' srcUrl = "http://%s:%s%s" % (self.hostname, self.iceWebPort, docPath) entry = atom.Entry(title=atom.Title(text=title)) entry.id = atom.Id(text="urn:uid:%s" % id) entry.link = [atom.Link(href=srcUrl, rel="alternate")] entry.updated = atom.Updated(text=entryDate) entry.published = atom.Published(text=entryDate) entry.summary = atom.Summary(summary_type="html", text=unicode(summary, "utf-8")) entry.content = atom.Content(content_type="html", text=unicode(content, "utf-8")) return entry else: return None
def test_broadcasting(self): uri = '/people/sakinijino/miniblog' broadcastingfeed = self.client.GetBroadcastingFeed(uri, 1, 2) entry = broadcastingfeed.entry[0]; #assert any(cate.term == "http://www.douban.com/2007#miniblog.blog" for cate in entry.category) contacturi = '/people/2463802/miniblog/contacts' broadcastingfeed = self.client.GetContactsBroadcastingFeed(contacturi, 1, 2) entry = broadcastingfeed.entry[0] #assert any(cate.term == "http://www.douban.com/2007#miniblog.saying" for cate in entry.category) entry = douban.BroadcastingEntry() entry.content = atom.Content(text = "You should not see this") entry = self.client.AddBroadcasting("/miniblog/saying", entry) self.client.DeleteBroadcasting(entry)
def add_event(self, title, content, start_time, end_time, guests): event = gdata.calendar.CalendarEventEntry() event.title = atom.Title(text=title) event.content = atom.Content(text=content) event.when.append( gdata.calendar.When(start_time=start_time.isoformat(), end_time=end_time.isoformat())) event.when[0].reminder.append( gdata.calendar.Reminder(days='1', method='email')) for guest in guests: event.who.append(gdata.calendar.Who(email=guest)) new_event = self.cal_srv.InsertEvent( event, '/calendar/feeds/%s/private/full' % self.CALENDAR_ID)
def add_to_google_calendar(calendar_service, item, calendar_id='default'): title = imap_utils.safe_get_event_value(item, 'summary.value', 'Imported Event') description = imap_utils.safe_get_event_value(item, 'description.value', 'Imported Event') where = imap_utils.safe_get_event_value(item, 'location.value', 'Unspecified') start_time = imap_utils.safe_get_event_value(item, 'dtstart.value', datetime.datetime.now()) end_time = imap_utils.safe_get_event_value( item, 'dtend.value', datetime.datetime.now() + datetime.timedelta(hours=1)) attendees = [ "%s [%s]" % (a.cn_paramlist[0], a.value) for a in imap_utils.safe_get_event_value(item, 'attendee_list', []) ] # tack the attendees list to the bottom of the thing (should really add it to 'event.who') if len(attendees): description = description + "\n-- Attendees:\n" + "\n".join(attendees) event = gdata.calendar.CalendarEventEntry() event.title = atom.Title(text=title) event.content = atom.Content(text=description) event.where.append(gdata.calendar.Where(value_string=where)) if start_time is None: # Use current time for the start_time start_time = datetime.datetime.now() if end_time is None: # have the event last 1 hour end_time = datetime.datetime.now() + datetime.timedelta(hour=1) # http://code.google.com/apis/calendar/data/1.0/developers_guide_python.html#Reminders event.when.append( gdata.calendar.When(start_time=UTC.to_utc_str(start_time), end_time=UTC.to_utc_str(end_time), reminder=gdata.calendar.Reminder(minutes=1, method='alert'))) exception = None for i in range(3): try: new_event = calendar_service.InsertEvent( event, '/calendar/feeds/%s/private/full' % calendar_id) return new_event except gdata.service.RequestError, e: print "Got 302, trying again..." exception = e time.sleep(3)
def test_create_update_delete(self): if not conf.settings.RUN_LIVE_TESTS: return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_create_update_delete') blog_post = atom.Entry( title=atom.Title(text=conf.settings.BloggerConfig.title), content=atom.Content(text=conf.settings.BloggerConfig.content)) http_request = atom.http_core.HttpRequest() http_request.add_body_part(str(blog_post), 'application/atom+xml') def entry_from_string_wrapper(response): return atom.EntryFromString(response.read()) entry = self.client.request( 'POST', 'http://www.blogger.com/feeds/%s/posts/default' % (conf.settings.BloggerConfig.blog_id), converter=entry_from_string_wrapper, http_request=http_request) self.assertEqual(entry.title.text, conf.settings.BloggerConfig.title) # TODO: uncomment once server bug is fixed #self.assertEqual(entry.content.text, conf.settings.BloggerConfig.content) # Edit the test entry. edit_link = None for link in entry.link: # Find the edit link for this entry. if link.rel == 'edit': edit_link = link.href entry.title.text = 'Edited' http_request = atom.http_core.HttpRequest() http_request.add_body_part(str(entry), 'application/atom+xml') edited_entry = self.client.request('PUT', edit_link, converter=entry_from_string_wrapper, http_request=http_request) self.assertEqual(edited_entry.title.text, 'Edited') # TODO: uncomment once server bug is fixed #self.assertEqual(edited_entry.content.text, entry.content.text) # Delete the test entry from the blog. edit_link = None for link in edited_entry.link: if link.rel == 'edit': edit_link = link.href response = self.client.request('DELETE', edit_link) self.assertEqual(response.status, 200)
def test_create_update_delete(self): if not conf.options.get_value('runlive') == 'true': return # Either load the recording or prepare to make a live request. conf.configure_cache(self.client, 'test_create_update_delete') blog_post = atom.Entry( title=atom.Title(text='test from python BloggerTest'), content=atom.Content(text='This is only a test.')) http_request = atom.http_core.HttpRequest() http_request.add_body_part(str(blog_post), 'application/atom+xml') def entry_from_string_wrapper(response): self.assertTrue(response.getheader('content-type') is not None) self.assertTrue(response.getheader('gdata-version') is not None) return atom.EntryFromString(response.read()) entry = self.client.request( 'POST', 'http://www.blogger.com/feeds/%s/posts/default' % (conf.options.get_value('blogid')), converter=entry_from_string_wrapper, http_request=http_request) self.assertEqual(entry.title.text, 'test from python BloggerTest') self.assertEqual(entry.content.text, 'This is only a test.') # Edit the test entry. edit_link = None for link in entry.link: # Find the edit link for this entry. if link.rel == 'edit': edit_link = link.href entry.title.text = 'Edited' http_request = atom.http_core.HttpRequest() http_request.add_body_part(str(entry), 'application/atom+xml') edited_entry = self.client.request('PUT', edit_link, converter=entry_from_string_wrapper, http_request=http_request) self.assertEqual(edited_entry.title.text, 'Edited') self.assertEqual(edited_entry.content.text, entry.content.text) # Delete the test entry from the blog. edit_link = None for link in edited_entry.link: if link.rel == 'edit': edit_link = link.href response = self.client.request('DELETE', edit_link) self.assertEqual(response.status, 200)
def CreateComment(self, post_id, comment_text): """This method adds a comment to the specified post. First the comment feed's URI is built using the given post ID. Then a GDataEntry is created for the comment and submitted to the GDataService. The post_id is the ID of the post on which to post comments. The comment_text is the text of the comment to store. Returns: an entry containing the newly-created comment NOTE: This functionality is not officially supported yet. """ # Build the comment feed URI feed_uri = '/feeds/' + self.blog_id + '/' + post_id + '/comments/default' # Create a new entry for the comment and submit it to the GDataService entry = gdata.GDataEntry() entry.content = atom.Content(content_type='xhtml', text=comment_text) return self.service.Post(entry, feed_uri)
def modifyBlogRedirectUrl(blog_id, proxy_url, client): """ Modifies the given blog settings to make the feed redirect to the given proxy. """ # The basic idea here is to PUT a new value to the Atom entry defined at # /feeds/blogid/settings/BLOG_FEED_REDIRECT_URL, which updates it. I'm not sure # why the code also needs to see the BLOG_FEED_REDIRECT_URL name in the id as well # as the POSTed URL... anyway, this works and it's just for demo purposes: data = atom.Entry( atom_id=atom.Id(text='tag:blogger.com,1999:blog-' + blog_id + '.settings.BLOG_FEED_REDIRECT_URL'), content=atom.Content(text=proxy_url) ) # The content of the setting is just the proxy URL logging.info("Data is: %s", data) uri = 'http://www.blogger.com/feeds/' + blog_id + '/settings/BLOG_FEED_REDIRECT_URL' client.blogger.Put(data, uri, extra_headers=None, url_params=None)
def test_note(self): uri = '/note/17030527' entry = self.client.GetNote(uri) assert entry.content.text == 'my note' assert entry.title.text == 'my note' entry = douban.NoteEntry() entry.title = atom.Title(text="a test note") entry.content = atom.Content(text="this note is for testing") entry = self.client.AddNote("/notes", entry, False, True) assert entry.title.text == 'a test note' entry = self.client.UpdateNote(entry, 'it a good day!', 'my good note', True, False); assert entry.title.text == 'my good note' self.client.DeleteNote(entry) feed = self.client.GetMyNotes('/people/2463802/notes', 1, 2) assert any(entry.title.text == 'a test note' for entry in feed.entry)
def sendSMS(self, title, content=''): event = gdata.calendar.CalendarEventEntry() event.title = atom.Title(text=title) event.content = atom.Content(text=content) start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + self.DELAY)) end_time = time.strftime( '%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + self.DELAY + 60 * 2)) event.when.append( gdata.calendar.When(start_time=start_time, end_time=end_time)) event.when[0].reminder.append( gdata.calendar.Reminder(minutes=1, method="sms")) self.service.InsertEvent(event, '/calendar/feeds/default/private/full')
def UpdateEvent(self, entry, content, title, invite_only=False, can_invite=True): if isinstance(entry, (str, unicode)): entry = self.Get(entry, douban.EventEntryFromString) entry.title = atom.Title(text=title) entry.content = atom.Content(text=content) entry.attribute.append( douban.Attribute('invite_only', invite_only and 'yes' or 'no')) entry.attribute.append( douban.Attribute('can_invite', can_invite and 'yes' or 'no')) uri = entry.GetSelfLink().href return self.Put(entry, uri, converter=douban.EventEntryFromString)
def AddCaptchaDoumail(self, receiverURI, subject, body, captcha_token, captacha_string): entry = douban.DoumailEntry() entry.entity.append( douban.Entity('receiver', "", extension_elements=[atom.Uri(text=receiverURI)])) entry.title = atom.Title(text=subject) entry.content = atom.Content(text=body) entry.attribute = [] entry.attribute.append( douban.Attribute('captcha_string', captacha_string)) entry.attribute.append(douban.Attribute('captcha_token', captcha_token)) return self.Post(entry, '/doumails', converter=douban.DoumailEntryFromString)
def updatePost(self, user, password, startTime, endTime, newContent): self.blogerLogin(user, password) self.getOneBlog(0) # find the update entry. query = service.Query() query.feed = '/feeds/' + self.blogId + '/posts/default' query.published_min = startTime query.published_max = endTime feed = self.service.Get(query.ToUri()) # should only have one entry. anyway we will only get the first entry. theEntry = feed.entry[0] theEntry.content = atom.Content(content_type='html', text=newContent) self.gdService.Put(theEntry, theEntry.GetEditLink().href)
def insertContact(self, _name, _email, _company, _title, _department, _phone, _street, _city, _state, _zip, _country, _notes): """Insert a Contact""" new_contact = gdata.contacts.ContactEntry(title=atom.Title(text=_name)) new_contact.email.append( gdata.contacts.Email(address=_email, primary='true', rel=gdata.contacts.REL_WORK)) if len(_company) > 0 or len(_title) > 0: org = gdata.contacts.Organization( org_name=gdata.contacts.OrgName(_company), org_title=gdata.contacts.OrgTitle(_title)) new_contact.organization = org if len(_phone) > 0: rel = gdata.contacts.PHONE_WORK new_contact.phone_number.append( gdata.contacts.PhoneNumber(rel=rel, text=_phone)) if len(_street) > 0 or len(_city) > 0 or len(_state) > 0 or len( _zip) > 0 or len(_country) > 0: addr = self.formatAddress(_street, _city, _state, _zip, _country) rel = gdata.contacts.REL_WORK new_contact.postal_address.append( gdata.contacts.PostalAddress(rel=rel, text=addr)) if len(_department) > 0: new_contact.extended_property.append( gdata.ExtendedProperty(name='Department', value=_department)) # new_contact.user_defined_field.append(gdata.UserDefinedField(key='Department', value=_department)) if len(_notes) > 0: new_contact.content = atom.Content(text=_notes) entry = self.gd_client.CreateContact(new_contact) if entry: print 'MSG: Creation successful!' else: print 'MSG: Upload error.' sys.exit(1)
def Run(self, title, content, where, all_day, start_date=None, end_date=None, start_time=None, end_time=None): """Inserts a basic event using either start_time/end_time definitions or gd:recurrence RFC2445 icalendar syntax. Specifying both types of dates is not valid. Note how some members of the CalendarEventEntry class use arrays and others do not. Members which are allowed to occur more than once in the calendar or GData "kinds" specifications are stored as arrays. Even for these elements, Google Calendar may limit the number stored to 1. The general motto to use when working with the Calendar data API is that functionality not available through the GUI will not be available through the API. Please see the GData Event "kind" document: http://code.google.com/apis/gdata/elements.html#gdEventKind for more information""" event = gdata.calendar.CalendarEventEntry() event.title = atom.Title(text=title) if content != 'no_data': print content event.content = atom.Content(text=content) if where != 'no_data': print where event.where.append(gdata.calendar.Where(value_string=where)) if all_day is 'Y': event.when.append( gdata.calendar.When(start_time=start_date, end_time=end_date)) else: start_time = time.strftime( '%Y-%m-%dT%H:%M:%S.000Z', time.strptime(start_time, '%Y-%m-%d-%H-%M')) end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.strptime(end_time, '%Y-%m-%d-%H-%M')) event.when.append( gdata.calendar.When(start_time=start_time, end_time=end_time)) new_event = self.cal_client.InsertEvent( event, '/calendar/feeds/default/private/full') return new_event
def applyToEntry(rv, diff, entry): for r in diff.inclusions: if isinstance(r, sharing.ItemRecord): if r.title not in NONCHANGES: if entry.title is None: entry.title = atom.Title(text=r.title) else: entry.title.text = r.title elif isinstance(r, sharing.NoteRecord): if r.body not in NONCHANGES: if entry.content is None: entry.content = atom.Content(text=r.body) else: entry.content.text = r.body elif isinstance(r, sharing.EventRecord): if r.location not in NONCHANGES: entry.where = [gdata.calendar.Where(value_string=r.location)] if r.dtstart not in NONCHANGES: if len(entry.when) == 0: entry.when.append(gdata.calendar.When()) if r.duration is NC: # start time changed, but duration didn't. However we # don't know the duration from the EIM record, so go back # to the the event entry and compute duration startTime = whenToDatetime(rv, entry.when[0].start_time) endTime = whenToDatetime(rv, entry.when[0].end_time) duration = endTime - startTime else: duration = sharing.fromICalendarDuration(r.duration) startTime, allDay, anyTime = sharing.fromICalendarDateTime( rv, r.dtstart) entry.when[0].start_time = startTime.isoformat() endTime = startTime + duration entry.when[0].end_time = endTime.isoformat() elif r.duration not in NONCHANGES: # Duration changed but start time didn't; get start time from # the entry and calculate new end time startTime = whenToDatetime(rv, entry.when[0].start_time) duration = sharing.fromICalendarDuration(r.duration) endTime = startTime + duration entry.when[0].end_time = endTime.isoformat()
def _add(self, calendar_service, username, title='', content='', where='', start_time=None, end_time=None): try: event = gdata.calendar.CalendarEventEntry() event.title = atom.Title(text=title) event.content = atom.Content(text=content) event.where.append(gdata.calendar.Where(value_string=where)) time_format = "%Y-%m-%d %H:%M:%S" if start_time: # convert event start date into gmtime format timestring = time.strftime( "%Y-%m-%d %H:%M:%S", time.gmtime( time.mktime( time.strptime(start_time, "%Y-%m-%d %H:%M:%S")))) starttime = time.strptime(timestring, time_format) start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', starttime) if end_time: # convert event end date into gmtime format timestring_end = time.strftime( "%Y-%m-%d %H:%M:%S", time.gmtime( time.mktime( time.strptime(end_time, "%Y-%m-%d %H:%M:%S")))) endtime = time.strptime(timestring_end, time_format) end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', endtime) if start_time is None: # Use current time for the start_time and have the event last 1 hour start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime()) 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)) cal_id = '/calendar/feeds/%s/private/full' % (username) new_event = calendar_service.InsertEvent(event, cal_id) return new_event except Exception, e: raise osv.except_osv('Error create !', e)
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()