using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Net;
using System.IO;
using System.Xml;
using PCScreenSavers.Model;
using log4net;
using PCScreenSavers.Common;
using Transitionals;
using Newtonsoft.Json;
using System.Windows;
namespace PCScreenSavers.Business
{
public class ItemInfo
{
public int id { get; set; }
public string img { get; set; }
public int time { get; set; }
public string effect { get; set; }
//public string text { get; set; }
public string screenmatch { get; set; }
public string launchtime { get; set; }
public string expirydate { get; set; }
public string code { get; set; }
public string duration { get; set; }
public ShopInfo shopInfo { get; set; }
}
public class Weathers
{
public string Status { get; set; }
public string Temperature_High { get; set; }
public string temperature_Now { get; set; }
public string Temperature_Low { get; set; }
}
public class ShopInfo {
public string FloorName { get; set; }
public string ShopName { get; set; }
public string LogoPath { get; set; }
public string Angle { get; set; }
public string Code { get; set; }
}
public class JService
{
App app = ((App)Application.Current);
//private string localIP = app.LocalIP;
//private string remoteAddress = ConfigurationManager.AppSettings["RemoteAddress"];
private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
Class_Log Mylog = new Class_Log();
/////
///// 绑定ip
/////
//public bool BindIp()
//{
// string urlString = string.Format("http://{0}/shanjing/interFace/kioskBinding.do?ip={1}", remoteAddress, localIP);
// string ret = GetHttpResponse(urlString);
// if (string.IsNullOrEmpty(ret))
// return false;
// else
// return true;
//}
public string WriteToConfig(List itemList, string code)
{
try
{
XmlDocument doc = new XmlDocument(); // 创建dom对象
XmlElement root = doc.CreateElement("root"); // 创建根节点
doc.AppendChild(root); // 加入到xml document
XmlElement FillItem; // 创建FillItem元素
FillItem = doc.CreateElement("code");
FillItem.InnerText = code;
root.AppendChild(FillItem); // 添加到xml document
FillItem = doc.CreateElement("items");
if (itemList != null && itemList.Count > 0)
{
for (int i = 0; i < itemList.Count; i++)
{
XmlElement Node = doc.CreateElement("item");
Node.SetAttribute("id", itemList[i].id.ToString());
Node.SetAttribute("code", itemList[i].code.ToString());
Node.SetAttribute("img", itemList[i].img);
Node.SetAttribute("time", itemList[i].time.ToString());
Node.SetAttribute("effect", itemList[i].effect);
Node.SetAttribute("screenmatch", itemList[i].screenmatch);
Node.SetAttribute("duration", itemList[i].duration);
Node.SetAttribute("launchtime", itemList[i].launchtime);
Node.SetAttribute("expirydate", itemList[i].expirydate);
Node.SetAttribute("floorName", itemList[i].shopInfo == null ? "" : itemList[i].shopInfo.FloorName);
Node.SetAttribute("shopName", itemList[i].shopInfo == null ? "" : itemList[i].shopInfo.ShopName);
Node.SetAttribute("logoPath", itemList[i].shopInfo == null ? "" : itemList[i].shopInfo.LogoPath);
Node.SetAttribute("angle", itemList[i].shopInfo == null ? "" : itemList[i].shopInfo.Angle);
Node.SetAttribute("shopCode", itemList[i].shopInfo == null ? "" : itemList[i].shopInfo.Code);
FillItem.AppendChild(Node);
}
}
root.AppendChild(FillItem);
MemoryStream stream = new MemoryStream();
XmlTextWriter writer = new XmlTextWriter(stream, null);
writer.Formatting = System.Xml.Formatting.Indented;
doc.Save(writer);
StreamReader sr = new StreamReader(stream, Encoding.UTF8);
stream.Position = 0;
string XMLString = sr.ReadToEnd();
Mylog.WriteLogFile(XMLString, "XMLString");
sr.Close();
writer.Flush();
writer.Close();
stream.Flush();
stream.Close();
return XMLString;
}
catch (Exception ex)
{
Mylog.WriteLogFile(ex.ToString(), "JServiceErrorLog");
return "";
}
}
///
/// 获取后台图片或视频资源地址
///
///
public ScreenSavers GetOutLineResource()
{
try
{
List> tpList = new List>();
string urlString = string.Format("http://{0}/API/Device/GetProgramList?ip={1}", app.HttpUrl, app.LocalIP);
string ret = GetHttpResponse(urlString);
Mylog.WriteLogFile(ret, "HttpClient");
if (!string.IsNullOrEmpty(ret))
{
Dictionary dic = JsonConvert.DeserializeObject>(ret);
if (!string.IsNullOrEmpty(dic["data"].ToString()) && dic["code"].ToString() == "200")
{
//Dictionary dicdata = JsonConvert.DeserializeObject>(dic["data"].ToString());
//if (!string.IsNullOrEmpty(dic["item"].ToString()))
//{
List itemList = JsonConvert.DeserializeObject>(dic["data"].ToString());
string xmlstring = WriteToConfig(itemList, "1");
if (!string.IsNullOrEmpty(xmlstring) && xmlstring != "")
{
ScreenSavers result = CommonMethod.DeserializeXML(xmlstring);
Mylog.WriteLogFile(result.ResList.ToString(), "HttpClient");
return result;
}
//}
}
//ScreenSavers result = CommonMethod.DeserializeXML(ret);
}
else
return null;
}
catch (Exception ex)
{
Mylog.WriteLogFile(ex.ToString(), "JServiceErrorLog");
return null;
}
return null;
}
///
/// 获取开始时间
///
///
public string GetStartTime()
{
try
{
string urlString = string.Format("http://{0}/api/device/GetNextTime?ip={1}", app.HttpUrl, app.LocalIP);
string ret = GetHttpResponse(urlString);
Mylog.WriteLogFile(ret, "HttpClient");
if (!string.IsNullOrEmpty(ret))
{
Dictionary dic = JsonConvert.DeserializeObject>(ret);
if (!string.IsNullOrEmpty(dic["data"].ToString()) && dic["code"].ToString() == "200")
{
string st = dic["data"].ToString();
log.Info(st);
return st;
}
}
}
catch (Exception ex)
{
Mylog.WriteLogFile(ex.ToString(), "HttpClient");
}
//return GetHttpResponse(urlString);
return "";
}
///
/// 获取开始时间
///
///
public bool GetIsSynDev()
{
bool flag = false;
try
{
string urlString = string.Format("http://{0}/api/device/IsSynDev?ip={1}", app.HttpUrl, app.LocalIP);
string ret = GetHttpResponse(urlString);
if (!string.IsNullOrEmpty(ret))
{
Dictionary dic = JsonConvert.DeserializeObject>(ret);
if (!string.IsNullOrEmpty(dic["data"].ToString()) && dic["code"].ToString() == "200")
{
flag = Convert.ToBoolean(dic["data"]);
}
}
}
catch (Exception ex)
{
Mylog.WriteLogFile(ex.ToString(), "HttpClient");
}
//return GetHttpResponse(urlString);
return flag;
}
///
/// 获取后台图片或视频资源地址
///
///
public List> GetResource()
{
List> tpList = new List>();
string urlString = string.Format("http://{0}/API/Device/GetProgramList?ip={1}", app.HttpUrl, app.LocalIP);
string ret = GetHttpResponse(urlString);
if (!string.IsNullOrEmpty(ret))
{
ScreenSavers result = CommonMethod.DeserializeXML(GetHttpResponse(urlString));
foreach (var item in result.ResList)
{
if (!string.IsNullOrEmpty(item.img))
{
item.img = "http://" + app.HttpUrl + "/screen" + item.img;
Transition t = CommonMethod.GetTransition(item.effect);
Tuple tp = new Tuple(item, t);
tpList.Add(tp);
}
}
}
return tpList;
}
/////
///// 获取屏保切换间隔
/////
/////
//public int GetInterval()
//{
// string urlString = string.Format("http://{0}/screen/interFace/getScreenParam.do?ip={1}", remoteAddress, localIP);
// string ret = GetHttpResponse(urlString);
// if (!string.IsNullOrEmpty(ret))
// {
// WaitInfo result = CommonMethod.DeserializeXML(ret);
// if (result != null && !string.IsNullOrEmpty(result.TimeInterval))
// {
// int temp = Convert.ToInt32(result.TimeInterval) * 1000;
// return temp > 30000 ? temp : 30000;
// }
// else
// return 30000;
// }
// else
// return 30000;
//}
///
/// 获取关机时间或重启指令
///
///
public string GetShutdown()
{
string urlString = string.Format("http://{0}/screen/interFace/shutdownTime_Windows.do?ip={1}", app.HttpUrl, app.LocalIP);
return GetHttpResponse(urlString);
}
///
/// 访问接口
///
///
///
private string GetHttpResponse(string urlString)
{
try
{
string result = string.Empty;
HttpWebRequest myReq = WebRequest.Create(urlString) as HttpWebRequest;
myReq.Timeout = 10000;
WebResponse wr = myReq.GetResponse();
using (Stream receiveStream = wr.GetResponseStream())
{
StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
result = reader.ReadToEnd();
reader.Close();
//receiveStream.Close();
}
return result;
}
catch (Exception ex)
{
Mylog.WriteLogFile(urlString + ex.Message + ex.StackTrace, "HttpMessageError");
return string.Empty;
}
}
public void GetSubTitle()
{
//string urlString = string.Format("http://192.168.0.128:8001/API/Subtitle/GetDevSubtitle?IP=192.168.1.104", app.HttpUrl, app.LocalIP);
string sendmsg = "{\"IP\":\"" + app.LocalIP + "\"}";
string urlString = string.Format("http://{0}/API/Subtitle/GetDevSubtitle", app.HttpUrl);
Mylog.WriteLogFile(urlString, "Subtitle");
try
{
string ret = PostMoths(sendmsg, urlString);
if (!string.IsNullOrEmpty(ret))
{
Mylog.WriteLogFile(ret, "Subtitle");
Dictionary dic = JsonConvert.DeserializeObject>(ret);
if (!string.IsNullOrEmpty(dic["data"].ToString()) && dic["code"].ToString() == "200")
{
Dictionary dicdata = JsonConvert.DeserializeObject>(dic["data"].ToString());
List itemList = JsonConvert.DeserializeObject>(dicdata["list"].ToString());
var groupList = itemList.GroupBy(i => i.location).Select(g => (new { Name = g.Key, List = g.Select(i => i.text) }));
app.TopSubTitle.Clear();
app.BottomSubTitle.Clear();
foreach (var item in groupList)
{
if (item.Name == "top")
{
app.TopSubTitle = item.List.ToList();
app.TopSubTitleIndex = 0;
}
else
{
app.BottomSubTitle = item.List.ToList();
app.BottomSubTitleIndex = 0;
}
}
}
else {
app.TopSubTitle.Clear();
app.BottomSubTitle.Clear();
}
}
else {
app.TopSubTitle.Clear();
app.BottomSubTitle.Clear();
}
}
catch (Exception e)
{
log.Info(e.Message + "字幕获取失败");
app.TopSubTitle.Clear();
app.BottomSubTitle.Clear();
}
}
public void SetPlayRecord()
{
//string urlString = string.Format("http://192.168.0.128:8001/API/Subtitle/GetDevSubtitle?IP=192.168.1.104", app.HttpUrl, app.LocalIP);
StringBuilder record =new StringBuilder();
string fpath = Directory.GetCurrentDirectory() + "\\record\\";
if (!Directory.Exists(fpath))
{
return;
}
string fname = Directory.GetCurrentDirectory() + "\\record\\Record.txt";
FileInfo finfo = new FileInfo(fname);
Mylog.WriteLogFile("文件地址" + fname, "UploadPlayRecord");
if (!finfo.Exists)
{
return;
}
else {
StreamReader sr = new StreamReader(fname, Encoding.Default);
String line;
while ((line = sr.ReadLine()) != null)
{
record.Append(line.ToString());
}
sr.Close();
if (!string.IsNullOrEmpty(record.ToString())) {
string sendmsg = "{\"IP\":\"" + app.LocalIP + "\",\"List\":[" + record + "]}";
string urlString = string.Format("http://{0}/API/ProgramStatistics/UploadPlayRecord", app.HttpUrl);
Mylog.WriteLogFile(sendmsg, "UploadPlayRecord");
try
{
string ret = PostMoths(sendmsg, urlString);
if (!string.IsNullOrEmpty(ret))
{
Dictionary dic = JsonConvert.DeserializeObject>(ret);
if (dic["code"].ToString() == "200")
{
File.Delete(fname);
}
else {
Mylog.WriteLogFile("上传节目播放统计错误" + ret, "UploadPlayRecordError");
}
}
}
catch (Exception e)
{
Mylog.WriteLogFile("上传节目播放统计错误" + e.Message, "UploadPlayRecordError");
}
}
}
}
///
/// Http post方法
///
/// json参数
/// 服务器地址
///
public string PostMoths(string param, string url)
{
string strURL = url;
System.Net.HttpWebRequest request;
request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
string paraUrlCoded = param;
byte[] payload;
payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
request.ContentLength = payload.Length;
Stream writer = request.GetRequestStream();
writer.Write(payload, 0, payload.Length);
writer.Close();
System.Net.HttpWebResponse response;
response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream s;
s = response.GetResponseStream();
string StrDate = "";
string strValue = "";
StreamReader Reader = new StreamReader(s, Encoding.UTF8);
while ((StrDate = Reader.ReadLine()) != null)
{
strValue += StrDate + "\r\n";
}
return strValue;
}
///
/// 获取天气
///
///
public Weathers GetWeather()
{
Weathers weather = new Weathers();
try
{
string urlString = string.Format("http://{0}/Api/Cdn/GetWeathers", app.KioskURL);
string ret = GetHttpResponse(urlString);
if (!string.IsNullOrEmpty(ret))
{
Dictionary dic = JsonConvert.DeserializeObject>(ret);
if (!string.IsNullOrEmpty(dic["data"].ToString()) && dic["code"].ToString() == "200")
{
Dictionary dicdata = JsonConvert.DeserializeObject>(dic["data"].ToString());
weather.Status = dicdata["status"].ToString();
weather.Temperature_High = dicdata["temperature_High"].ToString();
weather.temperature_Now = dicdata["temperature_Now"].ToString();
weather.Temperature_Low = dicdata["temperature_Low"].ToString();
}
}
}
catch (Exception ex)
{
Mylog.WriteLogFile("天气获取失败" + ex.ToString(), "JServiceErrorLog");
}
return weather;
}
//public void LoadProgramConfig()
//{
// try
// {
// string strConfigxml = AppDomain.CurrentDomain.BaseDirectory + "config//Program.xml";
// if (File.Exists(strConfigxml) == true)
// {
// XmlDocument doc = new XmlDocument();
// doc.Load(strConfigxml);
// XmlNode xnFirst = doc.SelectSingleNode("Config");
// XmlNode xnSecond = xnFirst.SelectSingleNode("Parameter");
// if (xnSecond == null)
// {
// this.TouchType = "";
// return;
// }
// else
// {
// if (xnSecond.SelectSingleNode("TouchType").InnerText != "" && isOnlyScreensaver == "0")
// this.TouchType = xnSecond.SelectSingleNode("TouchType").InnerText;
// }
// }
// }
// catch
// {
// this.TouchType = "";
// }
//}
}
}