вторник, 22 сентября 2015 г.

Google. Работа с блогом blogger.com из VB.NET

Данная программа на VB.NET позволяет вам прочитать сообщения из блога blogger.com компании google. Это может потребоваться для развития и рекламы вашего сайта. Гораздо удобнее вводить статьи в блоге, а потом отображать их на сайте.

Обратите внимание для получения записей конкретного блога достаточно знать его идентификатор. Справедливо для версии 2.0. Для редактирования сообщений потребуется пройти идентификацию. В новой версии библиотеки 3.0 эта идентификация требует ключевые слова и имеет ограничения 10000 записей в день.

Imports System.Text
Imports Google.GData.Client
Imports System.Net
Imports System.Xml
Imports System.Text.RegularExpressions
 
' https://developers.google.com/blogger/docs/2.0/developers_guide_dotnet
 
Namespace BloggerDevSample
 
    ' Это консольное приложение для тестирования работы с блогом blogger.com 
    ' Необходимо загрузить Nuget Google.GData.Blogger. Версия блога 2.0
    ' Проект доработан из C# под vb.net. http://google-gdata.googlecode.com/svn/trunk/clients/cs/samples/blogger/ConsoleSample.cs
    ' Автор: http://www.leadersoft.ru 22.09.2015
    
 
    Public Class ConsoleSample
 
        ' Главная программа для тестирования работы с блогом google.
        Public Shared Sub Main(args As String())
 
            ' 1. Вариант. Получаем список сообщений. Регистрация не нужна
            Dim blogId As String = "000000"
            GetListPost(blogId)
 
            ' 2. Вариант. Изменяем сообщения
            ' ClientLogin using username/password authentication
            Dim username As String
            Dim password As String
            If args.Length <> 2 Then
                Console.WriteLine("Usage: BloggerDevSample.exe <username> <password>")
                Return
            Else
                ' Запуск с параметрами
                username = args(0)
                password = args(1)
                ' Тестирование функции с регистрацией в google для обновления и удаления сообщений. 
                ' Не работают. Прекращена поддержка. Необходимо изучить новую систему регистрации
                funNonTesting(username, password)
            End If
 
 
            ' Остановка программы
            Console.WriteLine("Press enter to quit")
            Console.ReadLine()
        End Sub
 
        ' Список сообщений. Комментарии тоже можно получить отсюда
        Shared Sub GetListPost(blogId As StringOptional NumberToRetrieve As Integer = 5)
 
            Dim buffer As String = ""
 
            Try
                Dim feedQuery As FeedQuery = New FeedQuery
 
                feedQuery.Uri = New Uri("http://www.blogger.com/feeds/" + blogId + "/posts/default")
                feedQuery.NumberToRetrieve = NumberToRetrieve ' Максимальное число сообщений
                feedQuery.MinPublication = New DateTime(2015, 9, 21) ' Минимальная дата публикации
                feedQuery.MaxPublication = New DateTime(2015, 9, 22) ' Максимальная дата публикации
 
 
                Dim googleService As Service = New Service("blogger""blog.leadersoft.ru")
                Dim atomFeed As AtomFeed = googleService.Query(feedQuery)
 
                Try
 
                    Dim entry As AtomEntry
 
                    For Each entry In atomFeed.Entries
                        'content = entry.Content
                        buffer += "Категории ="
                        For Each cat As AtomCategory In entry.Categories
                            buffer += cat.Term & ","
                        Next
                        buffer += vbNewLine
                        buffer += "Ссылка='" & entry.AlternateUri.ToString & vbNewLine & _
                            "Заголовок =" & entry.Title.Text & vbNewLine & _
                            "Содержание =" & entry.Content.Content & vbNewLine & _
                            ""
                    Next
 
 
                Catch feedEx As Exception
                    buffer = "<p>Ошибка получения сообющения из Blogger.</p>"
                End Try
 
            Catch ex As Exception
                buffer = "<p><strong>Проблема с Blogger API: </strong>" & ex.Message & "</p>"
            End Try
 
            ' Отображаем содержимое
            MsgBox(buffer)
 
        End Sub
 
        '  ----- Данные функции не тестировались, т.к. не прошли идентификацию ---
        Shared Sub funNonTesting(username As String, password As String)
 
            Dim service As New Service("blogger""blogger-example")
            service.Credentials = New GDataCredentials(username, password)
 
            ListUserBlogs(service)
 
            ' Упарвление сообщениями
            Dim blogPostUri As Uri = SelectUserBlog(service)
            Dim createdEntry As AtomEntry = PostNewEntry(service, blogPostUri)
            PostAndDeleteNewDraftEntry(service, blogPostUri)
            ListBlogEntries(service, blogPostUri)
            ListBlogEntriesInDateRange(service, blogPostUri)
            Dim editedEntry As AtomEntry = EditEntry(createdEntry)
            DeleteEntry(editedEntry)
 
            ' Управление комментариями
            Dim commentPostUri As Uri = SelectBlogEntry(service, blogPostUri)
            Dim commentEntry As AtomEntry = PostNewComment(service, commentPostUri)
            ListEntryComments(service, commentPostUri)
            DeleteComment(commentEntry)
 
        End Sub
 
 
 
        '* Lists the user's blogs. 
        ' Список блогов
 
        Public Shared Sub ListUserBlogs(service As Service)
            Console.WriteLine(vbLf & "Retrieving a list of blogs")
            Dim query As New FeedQuery()
            ' Retrieving a list of blogs
            query.Uri = New Uri("http://www.blogger.com/feeds/default/blogs")
            Dim feed As AtomFeed = Nothing
            feed = service.Query(query)
            For Each entry As AtomEntry In feed.Entries
                Console.WriteLine("  Blog title: " + entry.Title.Text)
            Next
        End Sub
 
        '* Lists the user's blogs and returns the URI for posting new entries
        '         * to the blog which the user selected.
        '         
 
        Private Shared Function SelectUserBlog(service As ServiceAs Uri
            Console.WriteLine(vbLf & "Please select a blog on which to post.")
            Dim query As New FeedQuery()
            ' Retrieving a list of blogs
            query.Uri = New Uri("http://www.blogger.com/feeds/default/blogs")
            Dim feed As AtomFeed = service.Query(query)
 
            ' Publishing a blog post
            Dim blogPostUri As Uri = Nothing
            If feed IsNot Nothing Then
                For Each entry As AtomEntry In feed.Entries
                    ' Print out the title of the Blog
                    Console.WriteLine("  Blog name: " + entry.Title.Text)
                    Console.Write("  Post to this blog? (y/n): ")
                    If Console.ReadLine().Equals("y"Then
                        ' find the href in the link with a rel pointing to the blog's feed
                        For i As Integer = 0 To entry.Links.Count - 1
                            If entry.Links(i).Rel.Equals("http://schemas.google.com/g/2005#post"Then
                                blogPostUri = New Uri(entry.Links(i).HRef.ToString())
                                Console.WriteLine("  Your new posts will be sent to " + blogPostUri.AbsoluteUri.ToString())
                            End If
                        Next
                        Return blogPostUri
                    End If
                Next
            End If
            Return blogPostUri
        End Function
 
        '* Creates a new blog entry and sends it to the specified Uri 
 
        Private Shared Function PostNewEntry(service As Service, blogPostUri As UriAs AtomEntry
            Console.WriteLine(vbLf & "Publishing a blog post")
            Dim createdEntry As AtomEntry = Nothing
            If blogPostUri IsNot Nothing Then
                ' construct the new entry
                Dim newPost As New AtomEntry()
                newPost.Title.Text = "Marriage!"
                newPost.Content = New AtomContent()
                newPost.Content.Content = "<div xmlns='http://www.w3.org/1999/xhtml'>" + "<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>" + "<p>He is the last man on earth I would ever desire to marry.</p>" + "<p>Whatever shall I do?</p>" + "</div>"
                newPost.Content.Type = "xhtml"
                newPost.Authors.Add(New AtomPerson())
                newPost.Authors(0).Name = "Elizabeth Bennet"
                newPost.Authors(0).Email = "liz@gmail.com"
 
                createdEntry = service.Insert(blogPostUri, newPost)
                If createdEntry IsNot Nothing Then
                    Console.WriteLine("  New blog post created with title: " + createdEntry.Title.Text)
                End If
            End If
            Return createdEntry
        End Function
 
        '* Creates a new blog entry and sends it to the specified Uri 
 
        Private Shared Sub PostAndDeleteNewDraftEntry(service As Service, blogPostUri As Uri)
            Console.WriteLine(vbLf & "Creating a draft blog post")
            Dim draftEntry As AtomEntry = Nothing
            If blogPostUri IsNot Nothing Then
                ' construct the new entry
                Dim newPost As New AtomEntry()
                newPost.Title.Text = "Marriage! (Draft)"
                newPost.Content = New AtomContent()
                newPost.Content.Content = "<div xmlns='http://www.w3.org/1999/xhtml'>" + "<p>Mr. Darcy has <em>proposed marriage</em> to me!</p>" + "<p>He is the last man on earth I would ever desire to marry.</p>" + "<p>Whatever shall I do?</p>" + "</div>"
                newPost.Content.Type = "xhtml"
                newPost.Authors.Add(New AtomPerson())
                newPost.Authors(0).Name = "Elizabeth Bennet"
                newPost.Authors(0).Email = "liz@gmail.com"
                newPost.IsDraft = True
 
                draftEntry = service.Insert(blogPostUri, newPost)
                If draftEntry IsNot Nothing Then
                    Console.WriteLine("  New draft post created with title: " + draftEntry.Title.Text)
                    ' Delete the newly created draft entry
                    Console.WriteLine("  Press enter to delete the draft blog post")
                    Console.ReadLine()
                    draftEntry.Delete()
                End If
            End If
        End Sub
 
        '* Display the titles for all entries in the previously selected blog. 
 
        Private Shared Sub ListBlogEntries(service As Service, blogUri As Uri)
            If blogUri IsNot Nothing Then
                Console.WriteLine(vbLf & "Retrieving all blog posts")
                ' Retrieve all posts in a blog
                Dim query As New FeedQuery()
                Console.WriteLine("  Query URI: " + blogUri.ToString())
                query.Uri = blogUri
                Dim feed As AtomFeed = service.Query(query)
                For Each entry As AtomEntry In feed.Entries
                    Console.WriteLine("  Entry Title: " + entry.Title.Text)
                Next
            End If
        End Sub
 
        '* Display title for entries in the blog in the hard coded date range. 
 
        Private Shared Sub ListBlogEntriesInDateRange(service As Service, blogUri As Uri)
            Console.WriteLine(vbLf & "Retrieving posts using query parameters")
            ' Retrieve all posts in a blog between Jan 1, 2006 and Apr 12, 2007
            Dim query As New FeedQuery()
            query.Uri = blogUri
            query.MinPublication = New DateTime(2006, 1, 1)
            query.MaxPublication = New DateTime(2007, 4, 12)
            Dim feed As AtomFeed = service.Query(query)
            For Each entry As AtomEntry In feed.Entries
                Console.WriteLine("  Entry Title: " + entry.Title.Text)
            Next
        End Sub
 
        '* Change the contents of the newly created blog entry. 
 
        Private Shared Function EditEntry(toEdit As AtomEntryAs AtomEntry
            Console.WriteLine(vbLf & "Updating post")
            ' Edit the new entry
            If toEdit IsNot Nothing Then
                toEdit.Title.Text = "Marriage Woes!"
                Console.WriteLine("  Press enter to update")
                Console.ReadLine()
                toEdit = toEdit.Update()
            End If
            Return toEdit
        End Function
 
        '* Delete the specified blog entry. 
 
        Private Shared Sub DeleteEntry(toDelete As AtomEntry)
            Console.WriteLine(vbLf & "Deleting post")
            ' Delete the edited entry
            If toDelete IsNot Nothing Then
                Console.WriteLine("  Press enter to delete the new blog post")
                Console.ReadLine()
                toDelete.Delete()
            End If
        End Sub
 
        '* Get the comments feed URI for the desired blog entry. 
 
        Private Shared Function SelectBlogEntry(service As Service, blogPostUri As UriAs Uri
            Console.WriteLine(vbLf & "Please select a blog entry on which to comment.")
            Dim query As New FeedQuery()
            query.Uri = blogPostUri
            Dim feed As AtomFeed = service.Query(query)
            Dim commentPostUri As Uri = Nothing
 
            If feed IsNot Nothing Then
                For Each entry As AtomEntry In feed.Entries
                    ' Print out the title of the Blog
                    Console.WriteLine("  Blog entry title: " + entry.Title.Text)
                    Console.Write("  Post a comment on this entry? (y/n): ")
 
                    If Console.ReadLine().Equals("y"Then
                        ' Create the Post URL for adding a comment by finding this entry's id number.
 
                        ' Find the href in the link with a rel pointing to the blog's feed.
                        For i As Integer = 0 To entry.Links.Count - 1
 
                            If entry.Links(i).Rel = "edit" Then
                                Dim commentUriStart As String = Regex.Replace(blogPostUri.ToString(), "/posts/default""")
                                Dim selfLink As String = entry.Links(i).HRef.ToString()
                                Dim entryId As String = Regex.Replace(selfLink, blogPostUri.ToString() + "/""")
                                ' Build the comment URI from the blog id in and the entry id.
                                commentPostUri = New Uri((Convert.ToString(commentUriStart & Convert.ToString("/")) & entryId) + "/comments/default")
                                Console.WriteLine("  Your new comments will be sent to " + commentPostUri.ToString())
                                Return commentPostUri
                            End If
                        Next
                    End If
                Next
            End If
 
            Return commentPostUri
        End Function
 
        Private Shared Function PostNewComment(service As Service, commentPostUri As UriAs AtomEntry
            Console.WriteLine(vbLf & "Commenting on a blog post")
            Dim postedComment As AtomEntry = Nothing
            If commentPostUri IsNot Nothing Then
                ' Add a comment.
                Dim comment As AtomEntry
                comment = New AtomEntry()
                comment.Title.Text = "This is my first comment"
                comment.Content.Content = "This is my first comment"
                comment.Authors.Add(New AtomPerson())
                comment.Authors(0).Name = "Blog Author Name"
                postedComment = service.Insert(commentPostUri, comment)
                Console.WriteLine("  Result's title: " + postedComment.Title.Text)
            End If
            Return postedComment
        End Function
 
        Private Shared Sub ListEntryComments(service As Service, commentUri As Uri)
            If commentUri IsNot Nothing Then
                Console.WriteLine(vbLf & "Retrieving all blog post comments")
                ' Retrieve all comments on a blog entry
                Dim query As New FeedQuery()
                Console.WriteLine("  Query URI: " + commentUri.ToString())
                query.Uri = commentUri
                Dim feed As AtomFeed = service.Query(query)
                For Each entry As AtomEntry In feed.Entries
                    Console.WriteLine("  Comment Title: " + entry.Title.Text)
                Next
            End If
        End Sub
 
        Private Shared Sub DeleteComment(commentEntry As AtomEntry)
            Console.WriteLine(vbLf & "Deleting the comment")
            If commentEntry IsNot Nothing Then
                ' Delete the comment.
                Console.WriteLine("  Press enter to delete the new comment post")
                Console.ReadLine()
                commentEntry.Delete()
            End If
        End Sub
 
        ' Регистрация в другом сервисе Google.
        Shared Sub Blogger_NewLogin()
            Dim p_service As Google.GData.Client.Service = New Google.GData.Blogger.BloggerService("MyTest")
            Dim p_parameters As New Google.GData.Client.OAuth2Parameters()
            Try
 
                'validate token is still good.. 
                'quick dirty way for now... 
                If (p_parameters.AccessCode Is NothingThen
 
                    'STEP 1 - configure how to use OAuth 2.0
                    Dim CLIENT_ID As String = "clientid"
                    Dim CLIENT_SECRET As String = "clientsecret"
                    Dim SCOPE As String = "https://spreadsheets.google.com/feeds"
                    Dim REDIRECT_URI As String = "urn:ietf:wg:oauth:2.0:oob"
 
                    'STEP 2 - set up the OAuth 2.0 object
                    p_parameters.ClientId = CLIENT_ID
                    p_parameters.ClientSecret = CLIENT_SECRET
                    p_parameters.RedirectUri = REDIRECT_URI
                    p_parameters.Scope = SCOPE
 
                    'STEP 3 - get the authorization url
                    Dim authorizationUrl As String = Google.GData.Client.OAuthUtil.CreateOAuth2AuthorizationUrl(p_parameters)
 
                    'must be logged in as the gmail_account you want to use. 
                    'with the default broswer that launches or will need to login first.
                    Process.Start(authorizationUrl)
 
                    'wait until user has entered the code
                    Dim authCode As String = InputBox("Authorisation code""Authorisation Code""")
 
                    'user will need to get the access token for us from a web page. automate..
                    p_parameters.AccessCode = authCode
 
 
                    'STEP 4 - get access token
                    Google.GData.Client.OAuthUtil.GetAccessToken(p_parameters)
                    Dim accessToken = p_parameters.AccessToken
 
 
                    'step 5 - make an OAuth authorized request to google
                    Dim p_application_name As String = "test"
                    Dim requestFactory As New Google.GData.Client.GOAuth2RequestFactory(Nothing, p_application_name, p_parameters)
 
 
                    p_service.RequestFactory = requestFactory 'once set we dont need to do OAuth until expires
 
                End If
 
                'process request as usual here...
 
                Dim query As New Google.GData.Blogger.BloggerQuery
                Dim feed = p_service.Query(query)
                Debug.Print(feed.TotalResults)
 
 
            Catch ex As Exception
 
                MsgBox(ex.Message)
 
 
            End Try
        End Sub
 
 
    End Class
End Namespace

Комментариев нет: