import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.InternetAddress;
+import javax.activation.DataHandler;
+import javax.activation.DataSource;
+import javax.activation.FileDataSource;
+import javax.mail.BodyPart;
+import javax.mail.Multipart;
+import javax.mail.internet.MimeBodyPart;
+import javax.mail.internet.MimeMultipart;
+
import java.util.Date;
+
+import android.os.AsyncTask;
import android.os.StrictMode;
import java.io.File;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+import java.io.FileOutputStream;
+import java.io.FileInputStream;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.IOException;
public class LogUtil {
private static final String FILE_NAME = "log.txt";
private static final long MAX_SIZE = 1024 * 1024 * 10; // 10M
private static String logFile = "";
+ private static File DIR;
public static void config(File dir) {
try {
final LogConfigurator logConfigurator = new LogConfigurator();
//String fname = getExternalFilesDir(null) + File.separator + "log.txt";
+ DIR = dir;
logFile = dir + File.separator + FILE_NAME;
logConfigurator.setFileName(logFile);
logConfigurator.setRootLevel(Level.DEBUG);
logConfigurator.configure();
gLogger = Logger.getLogger("LogUtil");
gLogger.error("#######################################");
+ gLogger.error("RtmpClient by suanzi.ai");
gLogger.debug("Log file is located at: " + logFile);
} catch (Exception e){
+ gLogger.error("LogUtil.config error: " + e.getMessage());
e.printStackTrace();
}
- try {
+ }
+
+ public static void sendLogs (){
+
+ AsyncTask<Void, Integer, Boolean> mailTask = new AsyncTask<Void, Integer, Boolean>() {
+
+ private String zfile = DIR + File.separator + "log.zip";
- int SDK_INT = android.os.Build.VERSION.SDK_INT;
- if (SDK_INT > 8)
- {
- StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
- .permitAll().build();
- StrictMode.setThreadPolicy(policy);
- //your codes here
- MailUtil.sendMail();
+ @Override
+ protected Boolean doInBackground(Void... voids) {
+ // zip log.txt to log.zip
+ String[] s = new String[1];
+ s[0] = logFile;
+ gLogger.debug("zipLog - " + zfile);
+ try {
+ zip(s, zfile);
+ }catch (Exception e) {
+ gLogger.error("zipLog, error: " + e.getMessage());
+ e.printStackTrace();
+ return false;
+ }
+ sendMail(zfile);
+ return true;
}
- } catch (Exception e) {
- e.printStackTrace();
- }
+ @Override
+ protected void onPostExecute(Boolean result){
+ if(result) {
+ gLogger.debug("Zip file completed");
+ File zz = new File(zfile);
+ zz.delete();
+ } else {
+ gLogger.error("zip file error");
+ }
+ }
+ };
+ mailTask.execute();
+
}
-}
-
-
-//
-//
-// public void sendEmail()
-// {
-//
-// private static final int PICK_FROM_GALLERY = 101;
-// int columnIndex;
-// try
-// {
-//
-//
-//
-// final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
-// emailIntent.setType("plain/text");
-// emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,new String[] { "Email" });
-// emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Subject");
-// if (URI != null) {
-// emailIntent.putExtra(Intent.EXTRA_STREAM, URI);
-// }
-// emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "This is a message");
-// this.startActivity(Intent.createChooser(emailIntent,"Sending email..."));
-// }
-// catch (Throwable t)
-// {
-// Toast.makeText(this, "Request failed try again: " + t.toString(),Toast.LENGTH_LONG).show();
-// }
-// }
-// public void openFolder()
-// {
-// Intent intent = new Intent();
-// intent.setType("image/*");
-// intent.setAction(Intent.ACTION_GET_CONTENT);
-// intent.putExtra("return-data", true);
-// startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
-// }
-//
-// public static sendLogs(){
-//
-// }
-//
-// public void SendLoagcatMail(){
-//
-// // save logcat in file
-// /*File outputFile = new File(Environment.getExternalStorageDirectory(),
-// "logcat.txt");
-// try {
-// Runtime.getRuntime().exec(
-// "logcat -f " + outputFile.getAbsolutePath());
-// } catch (IOException e) {
-// // TODO Auto-generated catch block
-// e.printStackTrace();
-// }*/
-// String fname = getExternalFilesDir(null) + File.separator + "log.txt";
-//
-// File logfile = new File(fname);
-//
-// //send file using email
-// Intent emailIntent = new Intent(Intent.ACTION_SEND);
-// emailIntent.setType("vnd.android.cursor.dir/email");
-// String to[] = {"seudut@gmail.com"};
-// emailIntent.putExtra(Intent.EXTRA_EMAIL, to);
-// // the attachment
-// emailIntent.putExtra(Intent.EXTRA_STREAM, logfile.getAbsolutePath());
-// // the mail subject
-// emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
-// startActivity(Intent.createChooser(emailIntent , "Send email..."));
-// }
-
-//}
+ private static final String SMTP_SERVER = "smtp.exmail.qq.com";
+ private static final String USER = "support@suanzi.ai";
+ private static final String SENT_MAIL = "support@suanzi.ai";
+ private static final String PASSWORD = "oqiDX8fcWa58CmNf";
+ private static final String RECV_MAIL = "support@suanzi.ai";
+
+ private static boolean sendMail(String attachment){
+
+ String account = UserInfo.user;
+ String macAddr = UserInfo.macAddr;
+ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
+ StrictMode.setThreadPolicy(policy);
+
+ Properties props = new Properties();
+ props.setProperty("mail.transport.protocol", "smtp");
+ props.setProperty("mail.smtp.host", SMTP_SERVER);
+ props.setProperty("mail.smtp.auth", "true");
+ /*final String smtpPort = "465";
+ props.setProperty("mail.smtp.port", smtpPort);
+ props.setProperty("mail.smtp.socketFactory.class", "javax.NET.ssl.SSLSocketFactory");
+ props.setProperty("mail.smtp.socketFactory.fallback", "false");
+ props.setProperty("mail.smtp.socketFactory.port", smtpPort);*/
+ Session session = Session.getDefaultInstance(props);
+ session.setDebug(true);
+
+ MimeMessage message = new MimeMessage(session);
+ try {
+ message.setFrom(new InternetAddress(SENT_MAIL, account, "UTF-8"));
+ message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(RECV_MAIL, "support", "UTF-8"));
+ message.setSubject(macAddr, "UTF-8");
+ //message.setContent("hahaha", "text/html;charset=UTF-8");
+ message.setSentDate(new Date());
+
+
+ BodyPart messageBodyPart = new MimeBodyPart();
+ messageBodyPart.setText("This is message body");
+ Multipart multipart = new MimeMultipart();
+ multipart.addBodyPart(messageBodyPart);
+ messageBodyPart = new MimeBodyPart();
+ DataSource source = new FileDataSource(attachment);
+ messageBodyPart.setDataHandler(new DataHandler(source));
+
+ String fname = attachment.substring(attachment.lastIndexOf("/") + 1);
+ messageBodyPart.setFileName(fname);
+ multipart.addBodyPart(messageBodyPart);
+
+ // Send the complete message parts
+ message.setContent(multipart);
+ message.saveChanges();
+
+ Transport transport = session.getTransport();
+ transport.connect(USER, PASSWORD);
+ transport.sendMessage(message, message.getAllRecipients());
+ transport.close();
+ } catch (Exception e){
+ gLogger.error("send mail, error: " + e.getMessage());
+ e.printStackTrace();
+ return false;
+ }
+ return true;
+ }
+
+ private static final int BUFFER_SIZE = 8192;
+ private static void zip(String[] files, String zipFile) throws IOException {
+ BufferedInputStream origin = null;
+ ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
+
+ try {
+ byte data[] = new byte[BUFFER_SIZE];
+
+ for (int i = 0; i < files.length; i++) {
+ FileInputStream fi = new FileInputStream(files[i]);
+ origin = new BufferedInputStream(fi, BUFFER_SIZE);
+ try {
+ ZipEntry entry = new ZipEntry(files[i].substring(files[i].lastIndexOf("/") + 1));
+ out.putNextEntry(entry);
+ int count;
+ while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) {
+ out.write(data, 0, count);
+ }
+ }
+ finally {
+ origin.close();
+ }
+ }
+ }catch (Exception e){
+ e.printStackTrace();
+ } finally {
+ out.close();
+ }
+ }
+}
\ No newline at end of file
+++ /dev/null
-package ai.suanzi.rtmpclient;
-
-import java.util.Date;
-import java.util.Properties;
-
-import javax.mail.Session;
-import javax.mail.Transport;
-import javax.mail.internet.InternetAddress;
-import javax.mail.internet.MimeMessage;
-import android.util.Log;
-
-public class MailUtil {
-
- /**
- * 创建一封只包含文本的简单邮件
- *
- * @param session 和服务器交互的会话
- * @param sendMail 发件人邮箱
- * @param receiveMail 收件人邮箱
- * @return
- * @throws Exception
- */
- public static MimeMessage createMimeMessage(Session session, String sendMail, String receiveMail) throws Exception {
- // 1. 创建一封邮件
- MimeMessage message = new MimeMessage(session);
- // 2. From: 发件人
- message.setFrom(new InternetAddress(sendMail, "test", "UTF-8"));
- // 3. To: 收件人(可以增加多个收件人、抄送、密送)
- message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "test", "UTF-8"));
- // 4. Subject: 邮件主题
- message.setSubject("test", "UTF-8");
- // 5. Content: 邮件正文(可以使用html标签)
- message.setContent("hahaha", "text/html;charset=UTF-8");
- // 6. 设置发件时间
- message.setSentDate(new Date());
- // 7. 保存设置
- message.saveChanges();
- return message;
- }
-
- public static void sendMail() throws Exception{
- Log.e("MMMM", "sendMail");
- // 1. 创建参数配置, 用于连接邮件服务器的参数配置
- Properties props = new Properties(); // 参数配置
- props.setProperty("mail.transport.protocol", "smtp"); // 使用的协议(JavaMail规范要求)
- //props.setProperty("mail.smtp.host", "smtp.163.com"); // 发件人的邮箱的 SMTP 服务器地址
- props.setProperty("mail.smtp.host", "smtp.exmail.qq.com"); // 发件人的邮箱的 SMTP 服务器地址
-
- props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
- //如果遇到ssl类错误,请打开一下代码
- /*final String smtpPort = "465";
- props.setProperty("mail.smtp.port", smtpPort);
- props.setProperty("mail.smtp.socketFactory.class", "javax.NET.ssl.SSLSocketFactory");
- props.setProperty("mail.smtp.socketFactory.fallback", "false");
- props.setProperty("mail.smtp.socketFactory.port", smtpPort);*/
- // 2. 根据配置创建会话对象, 用于和邮件服务器交互
- Session session = Session.getDefaultInstance(props);
- // 设置为debug模式, 可以查看详细的发送 log
- session.setDebug(true);
- // 3. 创建一封邮件
- MimeMessage message = MailUtil.createMimeMessage(session, "support@suanzi.ai", "support@suanzi.ai");//我这里是以163邮箱为发信邮箱测试通过
- // 4. 根据 Session 获取邮件传输对象
- Transport transport = session.getTransport();
- transport.connect("support@suanzi.ai", "oqiDX8fcWa58CmNf");
- // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
- transport.sendMessage(message, message.getAllRecipients());
- // 7. 关闭连接
- transport.close();
- }
-
-
-}
//private static final String TAG = "MainActivity";
private Logger gLogger;
- private String mMacAddr = "";
+ //private String mMacAddr = "";
private NetworkMonitor networkMonitor;
private UsbMonitor mUsbMonitor;
private ServiceHealthMonitor mServiceHealthMonitor;
private CameraView mCameraView;
private void init(){
- // set config file
- UserInfo.setConfigPath(getExternalFilesDir(null) + File.separator + "config");
+ //UserInfo.setConfigPath(getExternalFilesDir(null) + File.separator + "config");
+ //UserInfo.readConfig(getExternalFilesDir(null) + File.separator + "config", getMacAddr());
- this.mMacAddr = getMacAddr();
+
+ //this.mMacAddr = getMacAddr();
mIntent = new Intent(this, MyService.class);
mUsbMonitor = new UsbMonitor(new UsbMonitor.UsbListener() {
LocalBinder mLocalBinder = (LocalBinder)service;
mServer = mLocalBinder.getServiceInstance();
mServer.setServiceEventListener(MainActivity.this);
- if(mServer.setRtmpUrl(UserInfo.getConfig().toUrl(mMacAddr))){
+ if(mServer.setRtmpUrl(UserInfo.toUrl())){
mServer.startPreview(mCameraView.getHolder());
Camera.Size cs = mServer.getBestPictureSize();
mCameraView.setLayout(cs.width, cs.height);
LogUtil.config(getExternalFilesDir(null));
gLogger = Logger.getLogger(getClass());
gLogger.error("#######################################");
- //configLog();
+ UserInfo.readConfig(getExternalFilesDir(null) + File.separator + "config", getMacAddr());
initCameraView();
init();
- loadConfig();
-
if(NetworkMonitor.isNetworkAvailable(this) && mUsbMonitor.hasUsbCamera()){
gLogger.error("Current network is available");
gLogger.debug("mServiceHealthMonitor start, interval " + INTERVAL);
mServiceHealthMonitor.start();
}
+ ////////// LogUtil.sendLogs(); /// Log test
}
@Override
return info.getMacAddress().replace(":", ""); //02:00:00:00:00:00 - 020000000000
}
- private void loadConfig() {
-// UserInfo info = UserInfo.getConfig();
-// gLogger.error("server is:" + info.server);
-// mTextServer.setText(info.server.equals("") ? "rtmp://gpussh.suanzi.ai:1935/myapp" : info.server);
-// mTextUser.setText(info.user);
-// //mMacAddr = info.macAddr.equals("") ? this.mMacAddr : info.macAddr;
-// gLogger.error("loadConfig - url is :" + info.toUrl(mMacAddr));
- }
-
- private void saveConfig() {
- UserInfo info = UserInfo.getConfig();
- //info.update(mTextServer.getText().toString(), mTextUser.getText().toString(), mMacAddr, mTextCamera.getText().toString());
- if(info.saveConfig()) {
- Toast.makeText(getApplicationContext(), "Config saved", Toast.LENGTH_LONG).show();
- } else {
- Toast.makeText(getApplicationContext(), "Error: config saved", Toast.LENGTH_LONG).show();
- }
- gLogger.error("saveConfig - url: " + info.toUrl(mMacAddr));
- }
-
private boolean canStartService(){
return mUsbMonitor.hasUsbCamera() && NetworkMonitor.isNetworkAvailable(this);
}
public class UserInfo {
- public String server = "";
- public String user = "";
- public String macAddr = "";
- public String cameraId = "";
- private static String configPath;
private static Logger gLogger = Logger.getLogger("UserInfo");
- private static String DEFAULT_SERVER = "rtmp://gpussh.suanzi.ai:1935/myapp";
- private static String DEFAULT_USER = "yunzhi";
+ public static String server = "rtmp://gpussh.suanzi.ai:1935/myapp";
+ public static String user = "yunzhi";
+ public static String macAddr = "";
+ public static String cameraId = "";
+ public static String configPath;
- private static UserInfo instance = null;
private UserInfo () {}
- public static void setConfigPath(String fname){
+ public static void readConfig(String fname, String addr){
+ gLogger.debug("readConfig - fname " + fname + ", macaddr " + addr);
configPath = fname;
- File file = new File(configPath);
- if(!file.exists()) {
- gLogger.error("Config file: " + configPath + " not exists! Create it");
- try {
- file.createNewFile();
- }catch (IOException e){
- gLogger.error("Create file error: " + e.getMessage());
- e.printStackTrace();
- }
- }
- }
- public static UserInfo getConfig() {
- if (instance != null) return instance;
-
- File file = new File(configPath);
- if (!file.exists()){
- gLogger.error("getConfig - file configpath: " + configPath + " not exists");
- return new UserInfo();
+ File file = new File (fname);
+ if(!file.exists()){
+ gLogger.debug(fname + " does not exist!.");
+ macAddr = addr;
+ return;
}
StringBuilder text = new StringBuilder();
}
String json = text.toString();
-
- UserInfo info = new UserInfo();
-
try {
JSONObject jobj = new JSONObject(json);
- info.server = jobj.getString("server");
- info.user = jobj.getString("user");
- info.macAddr = jobj.getString("macAddr");
- info.cameraId = jobj.getString("cameraId");
+ server = jobj.getString("server");
+ user = jobj.getString("user");
+ macAddr = jobj.getString("macAddr");
+ if(!macAddr.equals(addr)){
+ gLogger.debug("Mac address changed from " + macAddr + " to " + addr);
+ macAddr = addr;
+ }
+ cameraId = jobj.getString("cameraId");
} catch (JSONException e){
gLogger.error("getConfig - error: " + e.getMessage());
e.printStackTrace();
}
- instance = info;
- return info;
}
public boolean saveConfig() {
}
public void update(String server, String user, String macAddr, String cameraId) {
- this.server = server;
- this.user = user;
- this.macAddr = macAddr;
- this.cameraId = cameraId;
+ server = server;
+ user = user;
+ macAddr = macAddr;
+ cameraId = cameraId;
}
public String toString () {
private JSONObject toJsonObj () {
try {
JSONObject obj = new JSONObject();
- obj.put("server", this.server);
- obj.put("user", this.user);
- obj.put("macAddr", this.macAddr);
- obj.put("cameraId", this.cameraId);
+ obj.put("server", server);
+ obj.put("user", user);
+ obj.put("macAddr", macAddr);
+ obj.put("cameraId", cameraId);
return obj;
} catch (JSONException e) {
e.printStackTrace();
}
}
- public String toUrl (String mac) {
+ public static String toUrl () {
//rtmp://gpussh.suanzi.ai:1935/myapp/suanzi_ac83f34ead90_cameraid
//return server + "/" + user + "_" + macAddr + "_" + cameraId;
- return (server.equals("") ? DEFAULT_SERVER : server) + "/" + (user.equals("") ? DEFAULT_USER : user) + "_" + mac;
+ return server + "/" + user + "_" + macAddr;
+
}