Skip to content

Instantly share code, notes, and snippets.

@mizucoffee
Last active April 12, 2017 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizucoffee/2bae9e9fa3d07f67a3c0 to your computer and use it in GitHub Desktop.
Save mizucoffee/2bae9e9fa3d07f67a3c0 to your computer and use it in GitHub Desktop.
ニコメロガー。ニコニコ生放送のコメントを全てSlackへ転送します。尚、セッションの仕組みが変わっているようです。これからはこちらを御覧ください→https://github.com/KawakawaRitsuki/NicomeLogger
/*
* 参考にさせていただいたサイト・ツール
*
* http://c-loft.com/blog/?p=696
* http://dic.nicovideo.jp/a/%E3%83%8B%E3%82%B3%E7%94%9F%E3%82%A2%E3%83%A9%E3%83%BC%E3%83%88(%E6%9C%AC%E5%AE%B6)%E3%81%AE%E4%BB%95%E6%A7%98
*
* WireShark
*
*/
package com.kawakawaplanning.nicome_logger;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class Main {
//セッションID。クッキー。
public static String mUserSession;
//チケットって言うコメントするのに必要なもの
public static String mTicket;
//コメントサーバ用
public static String mComSrvAddr;
public static String mComSrvPort;
public static String mComSrvThread;
//コメントサーバ用
public static String mAlrSrvAddr;
public static String mAlrSrvPort;
public static String mAlrSrvThread;
//生開始時刻がUnixTimeで代入
public static String mStartTime;
//RawなユーザーID
public static String mUserId;
//コメントするために必要なキー
public static String mPostKey;
//生ID
public static String mLvId;
//メアド
public static String mailAddr;
//パスワード
public static String password;
public static String slackToken = "SlackToken";
public static void main(String[] args) {
try {
BufferedReader stdReader =
new BufferedReader(new InputStreamReader(System.in));
System.out.print("メールアドレス:");
mailAddr = stdReader.readLine();
System.out.print("パスワード:");
password = stdReader.readLine();
while ((line = stdReader.readLine()) != null) { // ユーザの一行入力を待つ
if (line.equals("")) line = "<空文字>";
System.out.print("OUTPUT: " + line);
System.out.print("\nINPUT : ");
}
stdReader.close();
System.out.println("\nPROGRAM END");
} catch (Exception e) {
e.getStackTrace();
System.exit(-1); // プログラムを終了
}
slackApi("NicomeLoggerを起動したよ!");
//起動引数
//メールアドレス パスワード
// mailAddr = args[0];
// password = args[1];
mailAddr = "mail@add.ress";
password = "password";
mLvId = "lv*********";
mUserSession = getUserSession();
mTicket = getTicket();
String status = getPlayerStatus();
mComSrvAddr = status.split(",")[0];
mComSrvPort = status.split(",")[1];
mComSrvThread = status.split(",")[2];
mStartTime = status.split(",")[3];
mUserId = status.split(",")[4];
mPostKey = getPostKey();
String alertInfo = getAlertInfo();
mAlrSrvAddr = alertInfo.split(",")[0];
mAlrSrvPort = alertInfo.split(",")[1];
mAlrSrvThread = alertInfo.split(",")[2];
System.out.println();
System.out.println("SessionID :" + mUserSession);
System.out.println("Ticket :" + mTicket);
System.out.println("ComAddr :" + mComSrvAddr);
System.out.println("ComPort :" + mComSrvPort);
System.out.println("ComThreadID :" + mComSrvThread);
System.out.println("AlrAddr :" + mAlrSrvAddr);
System.out.println("AlrPort :" + mAlrSrvPort);
System.out.println("AlrThreadID :" + mAlrSrvThread);
System.out.println("StartTime :" + mStartTime);
System.out.println("PostKey :" + mPostKey);
System.out.println("UserID :" + mUserId);
// getAlert();
connectCommentServer();
}
public static String getUserSession(){
try {
System.out.println("===== Get UserSession =====");
String httpsURL = "https://secure.nicovideo.jp/secure/login?site=nicolive";
URL myurl = new URL(httpsURL);
HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", "62");
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes("next_url=&mail=" + mailAddr + "&password=" + password);
output.close();
System.out.println("Resp Code:"+con .getResponseCode());
System.out.println("Resp Message:"+ con .getResponseMessage());
Map headers = con.getHeaderFields();
Iterator headerIt = headers.keySet().iterator();
String header = null;
while(headerIt.hasNext()){
String headerKey = (String)headerIt.next();
header += headerKey + ":" + headers.get(headerKey) + "\r\n";
}
String temp = header.substring(header.indexOf("user_session"));
System.out.println(temp.substring(temp.indexOf("=")+1,temp.indexOf(";")));
return temp.substring(temp.indexOf("=")+1,temp.indexOf(";"));
}catch (IOException e) {
e.printStackTrace();
return "";
}
}
public static String getTicket(){
try {
System.out.println("===== Get Ticket ==========");
String httpsURL = "https://secure.nicovideo.jp/secure/login?site=nicolive_antenna";
URL myurl = new URL(httpsURL);
HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-length", "62");
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setDoOutput(true);
con.setDoInput(true);
DataOutputStream output = new DataOutputStream(con.getOutputStream());
output.writeBytes("next_url=&mail=" + mailAddr + "&password=" + password);
output.close();
System.out.println("Resp Code:"+con .getResponseCode());
System.out.println("Resp Message:"+ con .getResponseMessage());
BufferedReader br
= new BufferedReader(
new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.substring(sb.indexOf("<ticket>")+8,sb.indexOf("</ticket>"));
}catch (IOException e) {
e.printStackTrace();
return "";
}
}
public static String getPlayerStatus(){
try {
System.out.println("===== Get Status ==========");
String httpsURL = "http://live.nicovideo.jp/api/getplayerstatus?v=" + mLvId;
URL myurl = new URL(httpsURL);
HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
con.setRequestMethod("GET");
con.addRequestProperty("Cookie", "user_session=" + mUserSession);
System.out.println("Resp Code:"+con .getResponseCode());
System.out.println("Resp Message:"+ con .getResponseMessage());
Map headers = con.getHeaderFields();
Iterator headerIt = headers.keySet().iterator();
String header = null;
while(headerIt.hasNext()){
String headerKey = (String)headerIt.next();
header += headerKey + ":" + headers.get(headerKey) + "\r\n";
}
BufferedReader br
= new BufferedReader(
new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
System.out.println(sb.toString());
String ms = sb.substring(sb.indexOf("<ms>")+4, sb.indexOf("</ms>"));//ms抜き出し
String addr = ms.substring(ms.indexOf("<addr>")+6 , ms.indexOf("</addr>"));//アドレス抜き出し
String port = ms.substring(ms.indexOf("<port>")+6 , ms.indexOf("</port>"));//ポート抜き出し
String thread = ms.substring(ms.indexOf("<thread>")+8 , ms.indexOf("</thread>"));//スレッド抜き出し
String start = sb.substring(sb.indexOf("<base_time>")+11, sb.indexOf("</base_time>"));//開始時刻抜き出し
String userid = sb.substring(sb.indexOf("<user_id>")+9, sb.indexOf("</user_id>"));//ユーザーID抜き出し
return addr + "," + port + "," + thread + "," + start + "," + userid;
}catch (IOException e) {
e.printStackTrace();
return "";
}
}
public static String getAlertInfo(){
try {
System.out.println("===== Get Alert Info ======");
String httpsURL = "http://live.nicovideo.jp/api/getalertinfo";
URL myurl = new URL(httpsURL);
HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
con.setRequestMethod("GET");
con.addRequestProperty("Cookie", "user_session=" + mUserSession);
System.out.println("Resp Code:"+con .getResponseCode());
System.out.println("Resp Message:"+ con .getResponseMessage());
Map headers = con.getHeaderFields();
Iterator headerIt = headers.keySet().iterator();
String header = null;
while(headerIt.hasNext()){
String headerKey = (String)headerIt.next();
header += headerKey + ":" + headers.get(headerKey) + "\r\n";
}
BufferedReader br
= new BufferedReader(
new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
String ms = sb.substring(sb.indexOf("<ms>")+4, sb.indexOf("</ms>"));//ms抜き出し
String addr = ms.substring(ms.indexOf("<addr>")+6 , ms.indexOf("</addr>"));//アドレス抜き出し
String port = ms.substring(ms.indexOf("<port>")+6 , ms.indexOf("</port>"));//ポート抜き出し
String thread = ms.substring(ms.indexOf("<thread>")+8 , ms.indexOf("</thread>"));//スレッド抜き出し
return addr + "," + port + "," + thread ;
}catch (IOException e) {
e.printStackTrace();
return "";
}
}
public static void getAlert(){
try {
Socket socket = new Socket(mAlrSrvAddr,Integer.parseInt(mAlrSrvPort));
PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);
pw.println("<thread thread=\"" + mAlrSrvThread + "\" version=\"20061206\" res_from=\"-1\"/>\0");
InputStream is1 = socket.getInputStream();
InputStreamReader ir1 = new InputStreamReader(is1,"UTF-8");
BufferedReader br1 = new BufferedReader(ir1);
while(is1.available() == 0);//一時停止
char[] cline = new char[is1.available()];
br1.read(cline);
String str = new String(cline);
System.out.println(str);
String temp = "";
while (true) {
while(is1.available() == 0);//一時停止
char[] cline2 = new char[is1.available()];
br1.read(cline2);
String str2 = new String(cline2);
System.out.println(str2);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void connectCommentServer(){
try {
Socket socket = new Socket(mComSrvAddr,Integer.parseInt(mComSrvPort));
PrintWriter pw = new PrintWriter(socket.getOutputStream(),true);
pw.println("<thread thread=\"" + mComSrvThread + "\" version=\"20061206\" res_from=\"-100\"/>\0");
// socket.setReceiveBufferSize(2048);
InputStream is1 = socket.getInputStream();
InputStreamReader ir1 = new InputStreamReader(is1,"UTF-8");
BufferedReader br1 = new BufferedReader(ir1);
while(is1.available() == 0);//一時停止
char[] cline = new char[is1.available()];
br1.read(cline);
String str = new String(cline);
String serverTimeTemp = str.substring(str.indexOf("server_time=\"") + 13);
int serverTime = Integer.parseInt(serverTimeTemp.substring(0,serverTimeTemp.indexOf("\"")));
int startTime = Integer.parseInt(mStartTime);
System.out.println("serverTime:" + serverTime );
int vpos = (serverTime - startTime) * 100;
String ticketTemp = str.substring(str.indexOf("ticket=\"") + 8);
String ticket = ticketTemp.substring(0,ticketTemp.indexOf("\""));
System.out.println("Ticket2 :" + ticket );
System.out.println("VPOS :" + vpos);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Integer.parseInt(mStartTime) * 1000L);
String message = "ログを開始したよ!これからコメントがログされていくよ!";
String time = cal.get(Calendar.YEAR) + "年" + cal.get(Calendar.MONTH) + "月" + cal.get(Calendar.DAY_OF_MONTH) + "日" + cal.get(Calendar.HOUR_OF_DAY) + "時" + cal.get(Calendar.MINUTE) + "分";
// pw.println("<chat thread=\"" + mComSrvThread + "\" ticket=\"" + ticket + "\" vpos=\"" + vpos + "\" postkey=\"" + mPostKey + "\" mail=\"\" user_id=\"" + mUserId + "\" premium=\"0\" locale=\"jp\">" + message +"</chat>\0");
slackApi(time + "開始");
slackApi("生放送ID" + mLvId + "が開始しました。");
String temp = "";
while (true) {
while(is1.available() == 0);//一時停止
char[] cline2 = new char[is1.available()];
br1.read(cline2);
String str2 = new String(cline2);
str2 = str2.replace('\0','\n');
String[] lines = str2.split("\n");
for (String st:lines){
// System.out.println(st);
try {
if (!st.equals("") && !st.endsWith(">")) {
temp = temp + st;
}else if (st.startsWith("<chat")) {//最後が>で且つ最初がchatなら
temp = temp + st;
slackApi(temp.substring(temp.indexOf(">") + 1,temp.indexOf("<",1)));
temp = "";
}
} catch (StringIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void slackApi(String message){
message = message.replace(" ", "%20");
try {
HttpURLConnection con = null;
URL url = new URL("https://slack.com/api/chat.postMessage"
+ "?token=" + slackToken
+ "&icon_url=https://pbs.twimg.com/profile_images/648778973615276032/4BVELIVH.png"
+ "&username=すわこ"
+ "&channel=C0B3WVDH9"
+ "&text=" + message);
con = (HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.connect();
con.getInputStream().close();
System.out.println("PostSlack...Complete!");
}catch(Exception e) {
System.out.println("PostSlack...Error!");
System.out.println("===== Error Message =======");
e.printStackTrace();
}
}
public static String getPostKey(){
try {
System.out.println("===== Get PostKey =========");
String httpsURL = "http://live.nicovideo.jp/api/getpostkey?thread=" + mComSrvThread;
URL myurl = new URL(httpsURL);
HttpURLConnection con = (HttpURLConnection)myurl.openConnection();
con.setRequestMethod("GET");
con.addRequestProperty("Cookie", "user_session=" + mUserSession);
System.out.println("Resp Code:"+con .getResponseCode());
System.out.println("Resp Message:"+ con .getResponseMessage());
Map headers = con.getHeaderFields();
Iterator headerIt = headers.keySet().iterator();
String header = null;
while(headerIt.hasNext()){
String headerKey = (String)headerIt.next();
header += headerKey + ":" + headers.get(headerKey) + "\r\n";
}
BufferedReader br
= new BufferedReader(
new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
String postkey = sb.substring(8);//ポストキー抜き出し
return postkey;
}catch (IOException e) {
e.printStackTrace();
return "";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment