ニコ生アラート
- 2010年 1月 31日
- 投稿者 : rei
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using System.Threading; namespace NicoLive { public class Alert : IAlert { /// <summary>スレッド間同期に使用するロック用オブジェクト</summary> private object m_lock = new object(); /// <summary>最新のコメントサーバー情報</summary> private ServerInfo m_serverInfo = null; /// <summary>コメントサーバー接続用ソケット</summary> private Socket m_socket = null; /// <summary>送受信に使用するバッファのバイト数</summary> private const int m_bufferSize = 1024; /// <summary>送受信に使用するバッファ</summary> private byte[][] m_buffer = new byte[4][]{ new byte[1024],new byte[1024],new byte[1024],new byte[1024] }; private int m_buffer_id = 0; /// <summary>接続が完了するのを待機するためのシグナルイベント</summary> private ManualResetEvent m_connectSignal = new ManualResetEvent(false); public event EventHandler<AlertEventArgs> LiveStarted = delegate(object s, AlertEventArgs e) { }; /// <summary> /// 何らかのアクションが起こったときに通知するイベント /// 主にデバッグ用 /// </summary> public event EventHandler<DebugEventArgs> Log = delegate(object s, DebugEventArgs e) { }; /// <summary> /// コメントサーバーからデータを受信したときに発生するイベント /// リクエストに対するレスポンス、生放送開始の通知、ダミーデータ のいずれか(のはず) /// </summary> public event EventHandler<DebugEventArgs> Recieved = delegate(object s, DebugEventArgs e) { }; /// <summary> /// コメントサーバーに接続中かどうかを表すフラグを取得する /// </summary> public bool Connected { get { return (m_socket != null) && m_socket.Connected; } } /// <summary> /// デフォルトコンストラクタ /// </summary> public Alert() { Recieved += new EventHandler<DebugEventArgs>(Alert_Recieved); } ~Alert() { Disconnect(); } /// <summary> /// コメントサーバーに接続し、番組の開始を監視する /// </summary> /// <returns></returns> public bool Connect() { if (null != m_socket) { return false; } // サーバー情報を取得 m_serverInfo = GetServerInfo(); if (null == m_serverInfo || !m_serverInfo.Enabled) { return false; } OnLog("Request OK : " + OfficialApi.GetAlertInfo); OnLog("↪" + m_serverInfo.Addr + ":" + m_serverInfo.Port + " , " + m_serverInfo.Thread); StartRecieve(); return true; } private bool StartRecieve() { OnLog("Listen"); try { // ソケットの初期化 m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_connectSignal.Reset(); // 接続 IAsyncResult connectResult = m_socket.BeginConnect(m_serverInfo.Addr, m_serverInfo.Port, new AsyncCallback(ConnectCallback), m_socket); // 接続が成功するまで待機 if (!m_connectSignal.WaitOne(5000, false)) { // 失敗時 throw new Exception(); } // 受信を待機 RecieveBuffer reciever = new RecieveBuffer(1024); m_socket.BeginReceive(reciever.Buffer, 0, 1024, SocketFlags.None, new AsyncCallback(RecieveCallback), reciever); // リクエストを送信 byte[] senddata = Encoding.UTF8.GetBytes("<thread thread=\"" + m_serverInfo.Thread + "\" version=\"20061206\" res_from=\"-1\"/>"); m_socket.BeginSend(senddata, 0, senddata.Length, SocketFlags.None, new AsyncCallback(SendCallback), m_socket); m_socket.BeginSend(new byte[]{0}, 0, 1, SocketFlags.None, new AsyncCallback(SendCallback), m_socket); } catch{ // エラー時 OnLog("Socket error."); Disconnect(); return false; } return true; } /// <summary> /// コメントサーバーへの接続コールバック /// </summary> /// <param name="connectResult"></param> private void ConnectCallback(IAsyncResult connectResult) { Socket socket = (Socket)connectResult.AsyncState; if (socket != null) { OnLog("Connect OK."); // 接続の成功を通知 m_connectSignal.Set(); } } /// <summary> /// 受信コールバック /// </summary> /// <param name="readResult"></param> private void RecieveCallback(IAsyncResult readResult) { //readResult. Socket socket = m_socket; //int buffer_id = (int)readResult.AsyncState; RecieveBuffer reciever = readResult.AsyncState as RecieveBuffer; if (null == socket || !socket.Connected) { // 切断済みの場合 OnLog("Socket Already Disconnected."); return; } reciever.Bytes = socket.EndReceive(readResult); if (reciever.Bytes > 0) { OnLog("Recieved " + reciever.Bytes + "bytes. "); reciever.Analyze(); int i = 0; foreach (string r in reciever.LineString) { OnLog("Recieved("+ i++ +"):" + r); AlertEventArgs args = Analyze(r); OnRecieved(r); } // 引き続き受信を待機する RecieveBuffer nextreciever = new RecieveBuffer(1024); socket.BeginReceive(nextreciever.Buffer, 0, 1024, SocketFlags.None, new AsyncCallback(RecieveCallback), nextreciever); } else { OnLog("Recieve Failed."); Disconnect(); } } private AlertEventArgs Analyze(string xml) { AlertEventArgs args = new AlertEventArgs(); args.Original = xml; Match match = Regex.Match(xml, ">(.+),(.+),(.+)<"); if (match.Success) { args.LiveId = match.Groups[1].Value; args.Community = match.Groups[2].Value; args.User = match.Groups[3].Value; } return args; } /// <summary> /// 送信コールバック /// </summary> /// <param name="sendResult"></param> private void SendCallback(IAsyncResult sendResult) { Socket socket = (Socket)sendResult.AsyncState; try { int sendbytes = socket.EndSend(sendResult); if (sendbytes > 0) { OnLog("Send OK."); } else { throw new ApplicationException(); } } catch { OnLog("Send Error."); Disconnect(); } } /// <summary> /// コメントサーバーに接続中であれば切断する /// </summary> public void Disconnect() { if (null == m_socket) { return; } try { m_socket.Shutdown(SocketShutdown.Both); } finally { m_socket.Close(); m_socket = null; OnLog("Disconnected."); } } /// <summary> /// Logイベントを発行する /// </summary> /// <param name="log"></param> protected void OnLog(string log) { Log(this, new DebugEventArgs(log)); } /// <summary> /// Recievedイベントを発行する /// </summary> /// <param name="recievedString"></param> protected void OnRecieved(string recievedString) { Recieved(this, new DebugEventArgs(recievedString)); } /// <summary> /// Recievedイベントを発行する /// </summary> /// <param name="recievedData"></param> /// <param name="bytes"></param> protected void OnRecieved(byte[] recievedData, int bytes) { OnRecieved(Encoding.UTF8.GetString(recievedData, 0, bytes)); } /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Alert_Recieved(object sender, DebugEventArgs e) { AlertEventArgs args = Analyze(e.Text); if (args.LiveId != "") { LiveStarted(this, args); } } /// <summary> /// コメントサーバーの情報を取得する /// </summary> /// <returns></returns> private ServerInfo GetServerInfo() { var result = new ServerInfo(); try { WebRequest request = WebRequest.Create(OfficialApi.GetAlertInfo); WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); if (stream != null) { StreamReader reader = new StreamReader(stream, Encoding.UTF8); string data = reader.ReadToEnd(); stream.Close(); Match match = Regex.Match(data, "<addr>(.+)</addr>"); if (match.Success) { result.Addr = match.Groups[1].Value; } match = Regex.Match(data, "<port>(.+)</port>"); if (match.Success) { result.Port = int.Parse(match.Groups[1].Value); } match = Regex.Match(data, "<thread>(.+)</thread>"); if (match.Success) { result.Thread = match.Groups[1].Value; } } response.Close(); } catch { return null; } return result; } /// <summary> /// 指定された番組のURLを取得する /// </summary> /// <param name="liveId"></param> /// <returns></returns> public static Uri GetLiveUri(int liveId) { return GetLiveUri(liveId.ToString()); } /// <summary> /// 指定された番組のURLを取得する /// </summary> /// <param name="liveId"></param> /// <returns></returns> public static Uri GetLiveUri(string liveId) { // "lv"から始まっていない場合"lv"を付ける string livepart = liveId.StartsWith("lv") ? liveId : ("lv" + liveId); return new Uri("http://live.nicovideo.jp/watch/" + livepart + "?alert=2"); } } } |
コメントはまだありません。