Files
BeWoPlaner/BeWoPlanerMobil/Controllers/ChatController.cs

847 lines
32 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
using System.Web.Mvc;
using BeWo.Data.Access;
using BeWo.Data.Entities;
using BeWo.Service.ServiceImplementations;
using BeWoPlanerMobil.Service;
using BS.Shared;
using Newtonsoft.Json;
using System.ServiceModel.Syndication;
using System.Xml;
namespace BeWoPlanerMobil.Controllers
{
public class ChatController : Controller
{
protected static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public string Index()
{
return "Das ist die <b>Default</b> Aktion... Sie haben hier nix verloren;-)";
}
public String GetServerUrl(string k)
{
string url = "https://dict.ownchat.de/api/server/resolve/1/" + k;
WebRequest request = WebRequest.Create(url);
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = request.GetResponse();
string responseFromServer = ReadStreamForChatCode(response);
var definition = new { status = "", URL = "", SYNCTYPE = "" };
var jsondaten = JsonConvert.DeserializeAnonymousType(responseFromServer, definition);
string serverUrl = jsondaten.URL;
response.Close();
return serverUrl;
}
public ActionResult GetRssFeed()
{
try
{
string url = "https://apps.ownsoft.de/news/rss?evplaner[base_cat]=55";
WebRequest request = WebRequest.Create(url);
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = request.GetResponse();
string responseFromServer = ReadStreamForChatCode(response);
response.Close();
return this.Content(responseFromServer, "text/xml");
}
catch (Exception)
{
// throw(BeWo.Service.Core.Utils.ThrowBeWoFaultException(e));
return null;
}
}
private static bool convertInProgress = false;
public ActionResult UpdateFiles(String list, String pwd)
{
try
{
if (convertInProgress)
{
return this.Content("Schon gestartet");
}
convertInProgress = true;
//list = "7000000000";
//pwd = "34vteWVTwegvn9wz4vn9";
if (pwd == "34vteWVTwegvn9wz4vn9")
{
String[] nummern = list.Split(',');
foreach (var knr in nummern)
{
System.Web.HttpContext.Current.Items.Remove("hibernateSession");
MobileSessionFacade.Tenant = knr;
var isKundennummerVorhanden = ASPHibernateSessionManager.ConfigureHibernateSessionForWebService();
if (isKundennummerVorhanden)
{
Log.Debug($"Start UpdateFiles for {knr} -----------------------------------------------------------------------------------------------------------------------");
//var filePath = GetFilePath(12345678);
//Log.Debug($"File Path = {filePath}");
SaveAllFilesToDisk(knr);
Log.Debug($"Finished UpdateFiles for {knr} -----------------------------------------------------------------------------------------------------------------------");
//var os = new OperationsServiceImp();
//os.SaveAllFilesToDisk();
}
else
{
Log.Debug($"Kundennummer {knr} nicht vorhanden");
}
}
convertInProgress = false;
return this.Content("Erfolgreich 4");
}
convertInProgress = false;
return this.Content("Nicht authorisiert");
}
catch (Exception ex)
{
convertInProgress = false;
return this.Content("ERROR " + ex.Message);
// throw(BeWo.Service.Core.Utils.ThrowBeWoFaultException(e));
return null;
}
}
private void SaveAllFilesToDisk(String knr)
{
var oid = DAOFactory.SearchDAO.GetMaxOidFromFileAttachment();
for (int i = 1; i <= oid; i++)
{
var file = DAOFactory.GenericDAO.LoadByID<FileAttachment>(i);
try
{
if (file.Data != null)
{
Log.Debug($"Convert File {file.Oid}");
SaveFileToFileDirectory(knr, file);
}
else
{
Log.Debug($"Skip File {file.Oid}. Data = null");
}
}
catch (Exception ex)
{
if (!ex.Message.Contains("No row with the given identifier exists"))
{
Log.Debug($"!!!! Error in SaveAllFilesToDisk " + ex.Message);
}
//prüfe ob Datei existiert, sonst kommt ein Hibernate Fehler
}
}
}
private void SaveFileToFileDirectory(String knr, FileAttachment fileAttachment)
{
if (fileAttachment.Data != null)
{
CheckForFileRootDirectory(knr);
var filePath = GetFilePath(knr, fileAttachment.Oid.Value);
System.IO.File.WriteAllBytes(filePath, fileAttachment.Data);
if (System.IO.File.Exists(filePath) && fileAttachment.Data != null)
{
fileAttachment.Data = null;
DAOFactory.GenericDAO.Update(fileAttachment);
}
}
}
private void CheckForFileRootDirectory(String knr)
{
var fileRootDirectoryPath = GetFileRootDirectoryPath();
var tenantPath = GetTenantFilePath(knr);
if (!Directory.Exists(fileRootDirectoryPath))
{
Directory.CreateDirectory(fileRootDirectoryPath);
}
if (!Directory.Exists(tenantPath))
{
Directory.CreateDirectory(tenantPath);
}
}
private string GetFilePath(String knr, long fileAttachmentOid)
{
return Path.Combine(GetTenantFilePath(knr), fileAttachmentOid.ToString());
}
private string GetFileRootDirectoryPath()
{
var fileRootDirectoryPath = System.Configuration.ConfigurationManager.AppSettings.Get(BS.Shared.Core.SettingsKeys.FileRootDirectory);
return fileRootDirectoryPath;
}
private string GetTenantFilePath(String kundennummer)
{
var fileRootDirectoryPath = GetFileRootDirectoryPath();
return Path.Combine(fileRootDirectoryPath, kundennummer);
}
private static string ReadStreamForChatCode(WebResponse response)
{
try
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
dataStream.Dispose();
reader.Dispose();
dataStream.Close();
reader.Close();
return responseFromServer;
}
catch (Exception e)
{
return null;
}
}
[System.Web.Http.HttpPost]
public JsonResult LoginToken(string kundennummer, string typ)
{
var apikey = Request["API-KEY"];
#if DEBUG
kundennummer = "demo"; // Test mit Autismus Köln Bonn
apikey = "SfTexuvxVGhNNyASiy43AnWa97VDcDsULyRTfxuWNC3YbNyLhzk48O7Hfzs7PNiy";
typ = "clients";
#endif
if (kundennummer == null)
{
return Json("99", JsonRequestBehavior.AllowGet);
}
MobileSessionFacade.Tenant = kundennummer;
var isKundennummerVorhanden = ASPHibernateSessionManager.ConfigureHibernateSessionForWebService();
if (isKundennummerVorhanden)
{
var operationsServiceImp = new OperationsServiceImp();
var mandator = operationsServiceImp.GetMandator2(false);
if (mandator.Apikey == apikey) {
Response.AddHeader("Content-Type","application/json"); //; charset=utf8
#region Typ Verarbeitung
if (typ != null)
{
if (typ.Equals("clients"))
{
// Von Employee ausgehend -> Klienten, für die der Employee Hauptbetreuer ist oder wo die Rolle ownchat enthält
// Klientenbereich
var allCustomers = DAOFactory.GenericDAO.GetAllActive<Customer>();
var allCustomerChatCodes = DAOFactory.GenericDAO.GetAllActive<CustomerAPPCode>();
var input1 = new List<JsonInputKlient1>();
var appUser = DAOFactory.GenericDAO.GetAllActive<ApplicationUser>();
// input 2 als liste übergeben und für jeden Mitarbeiter dem Customer zugeteilt ist
foreach (var customer in allCustomers)
{
var chatcode = new CustomerAPPCode();
foreach (var code in allCustomerChatCodes)
{
if (customer.Oid == code.CustomerOid)
{
chatcode = code;
}
}
var inputList = new List<JsonInputKlient2>();
// TODO: alle oder bestimmte Betreuer mitgeben und per Enum markieren
foreach (var e2c in customer.Employee2CustomerList)
{
if ((!e2c.StartDate.HasValue || e2c.StartDate.Value.Date <= DateTime.Now.Date) && (!e2c.EndDate.HasValue || e2c.EndDate.Value.Date >= DateTime.Now.Date))
{
foreach (var v2o in e2c.ValueList)
{
if ((v2o.Entry.SystemEntryID.HasValue && v2o.Entry.SystemEntryID.Value == SystemEntryID.EmployeeRoleMainAttendant) || v2o.Entry.Value.ToLower().Contains("ownchat"))
{
foreach (var applicationUser in appUser)
{
if (e2c.EmployeeOid == applicationUser.Employee?.Oid)
{
string status;
switch (e2c.IsActive)
{
case ActivationTypeId.Deleted:
status = "3";
break;
case ActivationTypeId.Archived:
status = "2";
break;
default:
status = "1";
break;
}
var input2 = new JsonInputKlient2(status,
e2c.EmployeeOid.ToString());
inputList.Add(input2);
}
}
}
}
}
}
var mobilnummer = string.Empty;
foreach (var contact in customer.Person.Contacts)
{
if (contact.Type == ContactType.business_MobilePhone)
{
mobilnummer = contact.Value;
}
}
var input = new JsonInputKlient1(customer.Oid.ToString(),"1",
customer.Person.FirstName, customer.Person.LastName, customer.CustomerAlias, mobilnummer, chatcode.CustomerCode,chatcode.BenutzerName,chatcode.BCryptPassword, inputList);
if (customer.IsActive == ActivationTypeId.Deleted)
{
input.Status = "3";
}
if (customer.IsActive == ActivationTypeId.Archived)
{
input.Status = "2";
}
if (customer.TerminationDate != null && customer.TerminationDate.Value.Date < DateTime.Now.Date)
{
input.Status = "2";
}
input1.Add(input);
}
var result = new JsonRueckgabeKlient("0", input1);
return Json(result, JsonRequestBehavior.AllowGet);
}
if (typ.Equals("users"))
{
//Bitte alle Employees zurückgeben
var empChatCode = DAOFactory.GenericDAO.GetAllActive<EmployeeAPPCode>();
var allEmployees = DAOFactory.GenericDAO.GetAllActive<Employee>();
var applicationUser = DAOFactory.GenericDAO.GetAllActive<ApplicationUser>();
var miInputList = new List<JsonRueckgabeMitarbeiterInput>();
Dictionary<long?, ApplicationUser> applicationUsers = new Dictionary<long?, ApplicationUser>();
foreach (var au in applicationUser)
{
if (au.Employee != null && au.Employee.Oid.HasValue && !applicationUsers.ContainsKey(au.Employee.Oid))
{
applicationUsers.Add(au.Employee.Oid, au);
}
}
//var applicationUsers2 = applicationUser.Where(appUser => appUser.Employee != null).ToDictionary(appUser => appUser.Employee.Oid);
foreach (var employee in allEmployees)
{
var chatcode = new EmployeeAPPCode();
foreach (var code in empChatCode)
{
if (employee.Oid == code.EmployeeOid)
{
chatcode = code;
}
}
DateTime? insTs = null;
foreach (var img in employee.Person.Images)
{
insTs = img.InsTs;
}
JsonRueckgabeMitarbeiterInput miInput;
if (employee.IsActive == ActivationTypeId.Deleted)
{
miInput = new JsonRueckgabeMitarbeiterInput("", employee.Oid.ToString(), "3", "", "", "", "", "", "", "", "");
}
else if (employee.IsActive == ActivationTypeId.Archived)
{
miInput = new JsonRueckgabeMitarbeiterInput("", employee .Oid.ToString(), "2", "", "", "", "", "", "", "", "");
}
else
{
string handy = null;
foreach (var contact in employee.Person.Contacts)
{
if (contact.Type == ContactType.business_MobilePhone)
{
//das ist die Handynummer
handy = contact.Value;
}
}
var instsStr = string.Empty;
if (insTs.HasValue)
{
instsStr = insTs.Value.ToString("dd.MM.yyyy");
}
//if (employee.Person.LastName == "Rapko")
//{
// int test = 0;
//}
if (applicationUsers.ContainsKey(employee.Oid))
{
miInput = new JsonRueckgabeMitarbeiterInput(applicationUsers[employee.Oid].Oid.ToString(), employee.Oid.ToString(), "1", applicationUsers[employee.Oid].LoginName,
applicationUsers[employee.Oid].BCryptPassword, employee.Person.FirstName,
employee.Person.LastName,chatcode.EmployeeCode, handy, employee.Person.Oid.ToString(), instsStr);
}
else
{
miInput = new JsonRueckgabeMitarbeiterInput("",employee.Oid.ToString(), "1", "","", employee.Person.FirstName,employee.Person.LastName,
chatcode.EmployeeCode, handy, employee.Person.Oid.ToString(), instsStr);
}
if (insTs != null)
{
miInput.PictureId = insTs.ToString();
}
miInputList.Add(miInput);
}
}
var mi = new JsonRueckgabeMitarbeiter("0", miInputList);
return Json(mi, JsonRequestBehavior.AllowGet);
}
if (typ.Equals("teams"))
{
//Mitarbeiter Team Bereich
var allTeams = DAOFactory.GenericDAO.GetAllActive<Team>();
var jrtmi = new List<JsonRueckgabeTeamMitarbeiterInput>();
var applicationUser = DAOFactory.GenericDAO.GetAllActiveAndArchived<ApplicationUser>();
Dictionary<long?, ApplicationUser> employeeOid2AppUser = new Dictionary<long?, ApplicationUser>();
foreach (var au in applicationUser)
{
if (au.Employee != null && au.Employee.Oid.HasValue && !employeeOid2AppUser.ContainsKey(au.Employee.Oid))
{
employeeOid2AppUser.Add(au.Employee.Oid, au);
}
}
//var appUserOid2AppUser = applicationUser.Where(appUser => appUser.Employee != null).ToDictionary(appUser => appUser.Employee.Oid);
foreach (var team in allTeams)
{
var mtInputList = new List<JsonRueckgabeTeamMitarbeiterInput2>();
bool isReadOnly = false;
bool teamIsEmployee = true;
if (team.IsOwnChatTeam)
{
foreach (var p2t in team.OwnChatMember)
{
var isWriter = !p2t.OwnChatRole.HasValue || p2t.OwnChatRole.Value == 0;
if (!isWriter)
{
isReadOnly = true;
}
if (p2t.Person.Type == PersonType.Employee)
{
var emp = DAOFactory.SearchDAO.FindEmployeeWithPersonOid(p2t.Person.Oid.Value);
var mtInput2 = new JsonRueckgabeTeamMitarbeiterInput2("1", emp.Oid.ToString(), true, isWriter);
if (emp.IsActive == ActivationTypeId.Deleted)
{
mtInput2.Status = "3";
}
if (emp.IsActive == ActivationTypeId.Archived)
{
mtInput2.Status = "2";
}
mtInputList.Add(mtInput2);
}
else
{
teamIsEmployee = false;
var c = DAOFactory.SearchDAO.FindCustomerWithPersonOid(p2t.PersonOid.Value);
var mtInput2 = new JsonRueckgabeTeamMitarbeiterInput2("1", c.Oid.ToString(), false, isWriter);
if (c.IsActive == ActivationTypeId.Deleted)
{
mtInput2.Status = "3";
}
if (c.IsActive == ActivationTypeId.Archived)
{
mtInput2.Status = "2";
}
mtInputList.Add(mtInput2);
}
}
}
else
{
foreach (var member in team.MemberList.Where(teamMember => teamMember.Oid.HasValue))
{
var mtInput2 = new JsonRueckgabeTeamMitarbeiterInput2("1", member.Oid.ToString(), true, true);
if (member.IsActive == ActivationTypeId.Deleted)
{
mtInput2.Status = "3";
}
if (member.IsActive == ActivationTypeId.Archived)
{
mtInput2.Status = "2";
}
mtInputList.Add(mtInput2);
}
}
var mtInput1 = new JsonRueckgabeTeamMitarbeiterInput(team.Oid.ToString(),"1", team.Name, mtInputList);
if (team.IsActive == ActivationTypeId.Deleted)
{
mtInput1.Status = "3";
}
if (team.IsActive == ActivationTypeId.Archived)
{
mtInput1.Status = "2";
}
mtInput1.is_read_only = isReadOnly ? "1" : "0";
//mtInput1.isemployee = teamIsEmployee ? "1" : "0";
jrtmi.Add(mtInput1);
}
var mt = new JsonRueckgabeTeamMitarbeiter("0", jrtmi);
return Json(mt, JsonRequestBehavior.AllowGet);
}
// Falls typ nicht stimmt
System.Threading.Thread.Sleep(5000);
return Json(new Fehler("1"), JsonRequestBehavior.AllowGet);
}
#endregion
// Falls typ nicht vorhanden
System.Threading.Thread.Sleep(5000);
return Json(new Fehler("1"), JsonRequestBehavior.AllowGet);
}
// Gib json zurück {"STATE":1}
System.Threading.Thread.Sleep(5000);
return Json(new Fehler("1"), JsonRequestBehavior.AllowGet);
}
// Gib json zurück {"STATE":99}
return Json(new Fehler("99"), JsonRequestBehavior.AllowGet);
}
[System.Web.Mvc.HttpPost]
public JsonResult BildUrl()
{
var oid = Request["oid"];
var img = DAOFactory.GenericDAO.GetByID<Person>(Convert.ToInt64(oid));
if (img.Images.Count > 0)
{
return Json(img.Images[0].SmallThumbnail, JsonRequestBehavior.AllowGet);
}
System.Threading.Thread.Sleep(5000);
return Json(new Fehler("1"), JsonRequestBehavior.AllowGet);
}
}
#region Klient
public class JsonRueckgabeKlient
{
public string State { get; set; }
public List<JsonInputKlient1> Data { get; set; }
public JsonRueckgabeKlient(string state, List<JsonInputKlient1> data )
{
State = state;
Data = data;
}
}
//klienten input
public class JsonInputKlient1
{
public string Oid { get; set; }
public string Status { get; set; }
public string Firstname { get; set; }
public string LastName { get; set; }
public string Alias { get; set; }
public string Mobile { get; set; }
public string ChatCode { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public List<JsonInputKlient2> Guardians { get; set; }
public JsonInputKlient1(string oid,string status, string firstname, string lastname, string alias,string mobile,string chatCode,string login,string password, List<JsonInputKlient2> guardians)
{
Oid = "C"+oid;
Status = status;
Firstname = firstname;
LastName = lastname;
Alias = alias;
Mobile = mobile;
ChatCode = chatCode;
Login = login;
Password = password;
Guardians = guardians;
}
}
public class JsonInputKlient2
{
public string Status { get; set; }
public string EmployeeOid { get; set; }
public JsonInputKlient2(string status,string employeeOid)
{
Status = status;
EmployeeOid = "E"+employeeOid;
}
}
#endregion
#region Mitarbeiter
public class JsonRueckgabeMitarbeiter
{
public string State { get; set; }
public List<JsonRueckgabeMitarbeiterInput> Data { get; set; }
public JsonRueckgabeMitarbeiter(string state, List<JsonRueckgabeMitarbeiterInput> data)
{
State = state;
Data = data;
}
}
public class JsonRueckgabeMitarbeiterInput
{
public string EmployeeOid { get; set; }
public string Status { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string Firstname { get; set; }
public string LastName { get; set; }
public string ChatCode { get; set; }
public string Mobile { get; set; }
public string Picture { get; set; }
public string PictureId { get; set; }
public JsonRueckgabeMitarbeiterInput(string useroid, string employeeOid, string status, string login, string password,
string firstname, string lastname,string chatcode,string mobile,string picture,string pictureId)
{
EmployeeOid = "E"+employeeOid;
Status = status;
Login = login;
Password = password;
Firstname = firstname;
LastName = lastname;
ChatCode = chatcode;
Mobile = mobile;
Picture = picture;
PictureId = pictureId;
}
}
#endregion
#region TeamMitarbeiter
public class JsonRueckgabeTeamMitarbeiter
{
public string State { get; set; }
public List<JsonRueckgabeTeamMitarbeiterInput> Data { get; set; }
public JsonRueckgabeTeamMitarbeiter(string state, List<JsonRueckgabeTeamMitarbeiterInput> data)
{
State = state;
Data = data;
}
}
public class JsonRueckgabeTeamMitarbeiterInput
{
public string Oid { get; set; }
public string Status { get; set; }
public string Name { get; set; }
public string is_read_only { get; set; }
public List<JsonRueckgabeTeamMitarbeiterInput2> Members { get; set; }
public JsonRueckgabeTeamMitarbeiterInput(string oid,string status, string name,List<JsonRueckgabeTeamMitarbeiterInput2> members)
{
Oid = "T"+oid;
Name = name;
Members = members;
Status = status;
is_read_only = "0";
}
}
public class JsonRueckgabeTeamMitarbeiterInput2
{
public string Status { get; set; }
public string EmployeeOid { get; set; }
public string IsEmployee { get; set; }
public string is_writer { get; set; }
public JsonRueckgabeTeamMitarbeiterInput2(string status,string oid, bool isEmployee, bool isWriter)
{
Status = status;
if (isEmployee)
{
EmployeeOid = "E" + oid;
IsEmployee = "1";
}
else
{
EmployeeOid = "C" + oid;
IsEmployee = "0";
}
is_writer = isWriter ? "1" : "0";
}
}
#endregion
#region fehlermeldung
public class Fehler
{
public string STATE { get; set; }
public Fehler(string fehler)
{
STATE = fehler;
}
}
#endregion
//public class RssActionResult : ActionResult
//{
// public SyndicationFeed Feed { get; set; }
// public override void ExecuteResult(ControllerContext context)
// {
// context.HttpContext.Response.ContentType = "application/rss+xml";
// Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(Feed);
// using (XmlWriter writer = XmlWriter.Create(context.HttpContext.Response.Output))
// {
// rssFormatter.WriteTo(writer);
// }
// }
//}
}