PubSubHubbubを用いたGoogleへの更新通知の実装 - C#

PubSubHubbubを用いてGoogleに更新通知を送る方法とコードを紹介します。

更新情報配信の実装

サイトでどのような更新が何時に行われたかを配信する仕組みを実装する必要があります。配信フォーマットにはRSS,RSS2,Atomなどがあります。

RSS,AtomのPubSubHubbub対応

RSS,AtomがPubSubHubbubbに対応していることを示すタグを追記します。

RSS1.0の場合

先頭部分のrdfタグが下記のようになっていますが、
<rdf:RDF xmlns="http://purl.org/rss/1.0/"
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xml:lang="ja">

下記のようにxmlns:atomタグを追記します。
<rdf:RDF xmlns="http://purl.org/rss/1.0/"
  xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
  xmlns:atom="http://www.w3.org/2005/Atom"
  xmlns:dc="http://purl.org/dc/elements/1.1/"
  xml:lang="ja">

また、Channelタグ内に以下のコードを記述します。
<atom:link href="この更新情報配信フィードのURL" rel="self" type="application/rss+xml" /> 
<atom:link rel="hub" href="http://pubsubhubbub.appspot.com" /> 

RSS2.0の場合

RSS2.0の場合も同様にrssタグにxmlns:atomタグを追記します。
<rss version="2.0"
 xmlns:content="http://purl.org/rss/1.0/modules/content/"
 xmlns:wfw="http://wellformedweb.org/CommentAPI/"
 xmlns:dc="http://purl.org/dc/elements/1.1/"
 xmlns:atom="http://www.w3.org/2005/Atom">

また、Channelタグ内に以下のコードを記述します。
<atom:link href="この更新情報配信フィードのURL" rel="self" type="application/rss+xml" /> 
<atom:link rel="hub" href="http://pubsubhubbub.appspot.com" /> 

Atomの場合

feedタグ直下のtitleタグの直後に以下のタグを記述します。
<link href="この更新情報配信フィードのURL" rel="self" type="application/atom+xml" /> 
<link rel="hub" href="http://pubsubhubbub.appspot.com" /> 

Google Hub へのプッシュ送信

コンテンツ更新が行われたタイミングでGoogleのHub (http://pubsubhubbub.appspot.com)に通知します。
通知は "http://pubsubhubbub.appspot.com" に対してPOSTします。ポストするデータは
hub.mode=publish&hub.url=(URLエンコードされたフィード(RSS or Atom)のURL)
となります。
HubへポストするC#のコードは以下になります。
protected void Button_Submit_Click(object sender, EventArgs e)
{
  //PubSubHubBub Publish Push
  string param = string.Format("hub.mode=publish&hub.url={0:s}", 
    HttpUtility.UrlEncode("(フィードのURL)"));

  WebRequest request = WebRequest.Create("http://pubsubhubbub.appspot.com/");
  request.Method = "POST";
  request.ContentType = "application/x-www-form-urlencoded";
  request.ContentLength = param.Length;
  System.IO.Stream stream = request.GetRequestStream();
  System.IO.StreamWriter sw = new System.IO.StreamWriter(stream);
  sw.Write(param);
  sw.Close();
}

動作確認

Hubにポストを実行すると、しばらくしてGoogleクローラーがフィードのURLにアクセスします。
以下のようなログが記録されます。
2014-03-06 18:00:00 xxx.xxx.xxx.xxx GET /feed.ashx format=atom 80 - 8.35.201.45 AppEngine-Google;+(+http://code.google.com/appengine;+appid:+s~pubsubhubbub-hrd) - 200 0 0 325
UserAgentに"pubsubhubbub-hrd"があることからPubSubHubbubのクローラーであることがわかります。

Googleへのインデックス状況

以上の手順でPubSubHubbubを用いてGoogleクローラーにサイトの更新状況を通知できますが、インデックスされるまでの期間は今のところあまり変わらないような印象です。こちらはしばらく経過を観察したいと思います。-
著者
iPentec.com の代表。ハードウェア、サーバー投資、管理などを担当。
Office 365やデータベースの記事なども担当。
掲載日: 2014-03-07
iPentec all rights reserverd.