Advertisement
Guest User

Untitled

a guest
Mar 7th, 2017
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 38.61 KB | None | 0 0
  1. using System;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4.  
  5. public class AAAA
  6. {
  7. public string CheckHash(params string[] values)
  8. {
  9. //i parametri devono essere ordinati allo stesso modo altrimenti l'hash viene fuori diverso
  10. string secret = "secret123!";
  11.  
  12. //https://msdn.microsoft.com/it-it/library/system.security.cryptography.sha1managed.computehash(v=vs.110).aspx
  13. using (SHA1Managed sha1 = new SHA1Managed())
  14. {
  15. var hashNew = sha1.ComputeHash(Encoding.UTF8.GetBytes(string.Join("", values) + secret)); //Calcola il valore hash della matrice di byte
  16. var sb = new StringBuilder(hashNew.Length * 2);
  17.  
  18. foreach (byte b in hashNew)
  19. {
  20. // "x2" restituisce una stringa lowercase
  21. sb.Append(b.ToString("x2"));
  22. }
  23.  
  24. return sb.ToString();
  25. }
  26. }
  27. }
  28. private const int RESULT_OK = 0;
  29. private const int RESULT_ERROR = 1;
  30. private const int RESULT_CUSTOM = 2;
  31.  
  32. /*
  33. Codici errori
  34. -1 -> Errore del server
  35. 0 -> OK
  36. 1 -> Invalid Hash!
  37. 2 -> User not found
  38. 3 -> Too many attempts
  39. 4 -> SMS Send error
  40. 5 -> Numero non validato
  41. 6 -> Utente già esistente
  42. 7 -> Errore MOR
  43. 8 -> Impossibile verificare la transazione
  44. 9 -> Impossibile ricaricare il conto (payment non scritto su MOR)
  45. 10 -> No did available
  46. 11 -> Voucher Redeem error MOR
  47. 12 -> Impossibile rimuovere la deviazione
  48. 13 -> Impossibile impostare la deviazione
  49. */
  50.  
  51. private static bool SMSEnabled
  52. {
  53. get { return bool.Parse(ConfigurationManager.AppSettings["sms_enabled"]); }
  54. }
  55.  
  56. public List<CountryResult> GetCountries(Stream data)
  57. {
  58. string param = string.Empty;
  59. try
  60. {
  61. param = new StreamReader(data).ReadToEnd();
  62. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  63.  
  64. string prefix = nv["prefix"];
  65. string hash = nv["hash"];
  66. bool loadPrefix = prefix == "1";
  67.  
  68. if (!CheckHash(hash, prefix))
  69. return null;
  70.  
  71. using (DbEntities db = new DbEntities())
  72. {
  73. return db.Countries.OrderBy(c => c.CountryName).Select(c =>
  74. new CountryResult
  75. {
  76. Id = c.CountryId,
  77. Name = c.CountryName,
  78. Prefix = loadPrefix ? "+" + c.Prefix : ""
  79. }).ToList();
  80. }
  81. }
  82. catch (Exception ex)
  83. {
  84. MailSender.InviaErrore(ex, "GetCountries", param);
  85. return null;
  86. }
  87. }
  88.  
  89. public RegisterResult Register(Stream data)
  90. {
  91. string param = string.Empty;
  92. try
  93. {
  94. param = new StreamReader(data).ReadToEnd();
  95. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  96.  
  97. string number = nv["number"];
  98. string prefix = nv["prefix"];
  99. string hash = nv["hash"];
  100.  
  101. if (!CheckHash(hash, number, prefix))
  102. return new RegisterResult { Result = RESULT_ERROR, Message = 1 };
  103.  
  104. int codice = GeneraCodice();
  105. string token;
  106. using (DbEntities db = new DbEntities())
  107. {
  108. Users u = db.Users.FirstOrDefault(c => c.Prefix == prefix && c.Number == number);
  109. if (u == null)
  110. {
  111. u = new Users();
  112. u.UserId = Guid.NewGuid();
  113. u.Prefix = prefix;
  114. u.Number = number;
  115. u.OTPRequest = 1;
  116. u.CreatedDate = DateTime.Now.ToCentralEuropeTime();
  117. u.IsActive = false;
  118. db.Users.Add(u);
  119. }
  120. else
  121. {
  122. u.OTPRequest++;
  123. if (u.OTPRequest > 5 && SMSEnabled)
  124. {
  125. MailSender.InviaErrore("Superati i 5 tentativi di invio SMS di registrazione", "Register", string.Format("Numero: {0}-{1}", prefix, number));
  126. return new RegisterResult { Result = RESULT_ERROR, Message = 3 };
  127. }
  128. }
  129.  
  130. u.OTP = codice;
  131.  
  132. db.SaveChanges();
  133. token = u.UserId.ToString();
  134.  
  135. if (SMSEnabled && !SMSSender.Send(u.UserId, db, prefix + number, codice))
  136. return new RegisterResult { Result = RESULT_ERROR, Message = 4 };
  137. }
  138.  
  139. RegisterResult result = new RegisterResult();
  140. result.Result = RESULT_OK;
  141. result.Message = 0;
  142. result.Token = token;
  143. result.Number = "+" + prefix + number;
  144. result.Prefix = "+" + prefix;
  145.  
  146. return result;
  147. }
  148. catch (Exception ex)
  149. {
  150. MailSender.InviaErrore(ex, "Register", param);
  151. return new RegisterResult { Result = RESULT_ERROR, Message = -1 };
  152. }
  153. }
  154.  
  155. public GenericResult ReSendSMS(Stream data)
  156. {
  157. string param = string.Empty;
  158. try
  159. {
  160. param = new StreamReader(data).ReadToEnd();
  161. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  162.  
  163. string token = nv["token"];
  164. string hash = nv["hash"];
  165.  
  166. if (!CheckHash(hash, token))
  167. return new GenericResult { Result = RESULT_ERROR, MessageCode = 1 };
  168.  
  169. int codice = GeneraCodice();
  170. Guid userId = Guid.Parse(token);
  171. using (DbEntities db = new DbEntities())
  172. {
  173. Users u = db.Users.FirstOrDefault(c => c.UserId.Equals(userId));
  174. if (u == null)
  175. return new GenericResult { Result = RESULT_ERROR, MessageCode = 2 };
  176.  
  177. if (u.OTPRequest >= 5 && SMSEnabled)
  178. {
  179. MailSender.InviaErrore("Superati i 5 tentativi di reinvio SMS di registrazione", "ReSendSMS", string.Format("Numero: {0}-{1}", u.Prefix, u.Number));
  180. return new GenericResult { Result = RESULT_ERROR, MessageCode = 3 };
  181. }
  182.  
  183. u.OTPRequest++;
  184. u.OTP = codice;
  185.  
  186. db.SaveChanges();
  187.  
  188. if (SMSEnabled && !SMSSender.Send(u.UserId, db, u.Prefix + u.Number, codice))
  189. return new GenericResult { Result = RESULT_ERROR, MessageCode = 4 };
  190. }
  191.  
  192. GenericResult result = new GenericResult();
  193. result.Result = RESULT_OK;
  194. result.Message = "";
  195. return result;
  196. }
  197. catch (Exception ex)
  198. {
  199. MailSender.InviaErrore(ex, "ReSendSMS", param);
  200. return new GenericResult { Result = RESULT_ERROR, MessageCode = -1 };
  201. }
  202. }
  203.  
  204. public RegistrationCompleteResult ConfirmCode(Stream data)
  205. {
  206. string param = string.Empty;
  207. try
  208. {
  209. param = new StreamReader(data).ReadToEnd();
  210. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  211.  
  212. string token = nv["token"];
  213. string code = nv["code"];
  214. string hash = nv["hash"];
  215.  
  216. if (!CheckHash(hash, token, code))
  217. return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 1 };
  218.  
  219. Guid userId = Guid.Parse(token);
  220. using (DbEntities db = new DbEntities())
  221. {
  222. Users u = db.Users.Include("UserInfo").FirstOrDefault(c => c.UserId.Equals(userId));
  223. if (u == null)
  224. return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 2 };
  225.  
  226. if (SMSEnabled && u.OTP != int.Parse(code))
  227. return new RegistrationCompleteResult { Result = RESULT_CUSTOM };
  228.  
  229. u.NumberConfirmedDate = DateTime.Now.ToCentralEuropeTime();
  230. db.SaveChanges();
  231.  
  232. RegistrationCompleteResult result = new RegistrationCompleteResult();
  233. result.Result = RESULT_OK;
  234. result.IsActive = u.IsActive;
  235.  
  236. if (result.IsActive)
  237. {
  238. //è vero in caso di re-registrazione, in tal caso mando questi dati e salto la richiesta dei dati personaliabtoPhone
  239. result.Secret = u.UserInfo.DevicePassword.DecryptFromStorage().EncryptForPhone();
  240. result.Extension = u.UserInfo.DeviceExtension;
  241. result.Domain = ConfigurationManager.AppSettings["sip_domain"];
  242. result.DevicePin = u.UserInfo.DevicePin.EncryptForPhone();
  243. result.FreeCall = u.UserInfo.FreeCall;
  244. }
  245.  
  246. return result;
  247. }
  248. }
  249. catch (Exception ex)
  250. {
  251. MailSender.InviaErrore(ex, "ConfirmCode", param);
  252. return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = -1 };
  253. }
  254. }
  255.  
  256. public RegistrationCompleteResult SetUserInfo(Stream data)
  257. {
  258. string param = string.Empty;
  259. try
  260. {
  261. param = new StreamReader(data).ReadToEnd();
  262. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  263.  
  264. string token = nv["token"];
  265. string nome = nv["nome"];
  266. string cognome = nv["cognome"];
  267. string email = nv["email"];
  268. string nazione = nv["nazione"]; //id numerico
  269. string citta = nv["citta"];
  270. string cap = nv["cap"];
  271. string codiceAffiliazione = nv["codice"];
  272. string hash = nv["hash"];
  273.  
  274. if (!CheckHash(hash, token, nome, cognome, email, nazione, citta, cap))
  275. return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 1 };
  276.  
  277. Guid userId = Guid.Parse(token);
  278. using (DbEntities db = new DbEntities())
  279. {
  280. Users u = db.Users.FirstOrDefault(c => c.UserId.Equals(userId));
  281. if (u == null)
  282. return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 2 };
  283.  
  284. if (!u.NumberConfirmedDate.HasValue)
  285. return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 5 };
  286.  
  287. if (u.IsActive)
  288. return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 6 };
  289.  
  290. //creo l'utente su MOR
  291. MOR.User morUser = new MOR.User(u.Prefix + u.Number, email, nome, cognome, nazione, citta, cap, true);
  292. MOR mor = new MOR(u.UserId);
  293. if (!mor.CreateUser(morUser))
  294. return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = 7 };
  295.  
  296. u.IsActive = true;
  297. u.RegistrationCompletedDate = DateTime.Now.ToCentralEuropeTime();
  298. u.UserInfo = new UserInfo();
  299. u.UserInfo.MorUserId = int.Parse(morUser.UserId);
  300. u.UserInfo.City = citta;
  301. u.UserInfo.CountryId = int.Parse(nazione);
  302. u.UserInfo.Email = email;
  303. u.UserInfo.FirstName = nome;
  304. u.UserInfo.LastName = cognome;
  305. u.UserInfo.Zip = cap;
  306. u.UserInfo.Username = morUser.username;
  307. u.UserInfo.Password = morUser.password.EncryptForStorage();
  308. u.UserInfo.DeviceId = morUser.device.id;
  309. u.UserInfo.DeviceExtension = morUser.device.extension;
  310. u.UserInfo.DevicePassword = morUser.device.secret.EncryptForStorage();
  311. u.UserInfo.DevicePin = morUser.device.pin;
  312. u.UserInfo.FreeCall = codiceAffiliazione == "FREE";
  313.  
  314. db.SaveChanges();
  315.  
  316. var result = new RegistrationCompleteResult();
  317. result.Secret = morUser.device.secret.EncryptForPhone();
  318. result.DevicePin = morUser.device.pin.EncryptForPhone();
  319. result.Extension = morUser.device.extension;
  320. result.Domain = ConfigurationManager.AppSettings["sip_domain"];
  321. result.Result = RESULT_OK;
  322. result.FreeCall = u.UserInfo.FreeCall;
  323.  
  324. return result;
  325. }
  326. }
  327. catch (DbEntityValidationException dbEx)
  328. {
  329. string errorMessage = "";
  330. foreach (var validationErrors in dbEx.EntityValidationErrors)
  331. foreach (var validationError in validationErrors.ValidationErrors)
  332. errorMessage += string.Format("Property: {0} Error: {1}<br>", validationError.PropertyName, validationError.ErrorMessage);
  333.  
  334. MailSender.InviaErrore(new Exception(errorMessage), "SetUserInfo", param);
  335. return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = -1 };
  336. }
  337.  
  338. catch (Exception ex)
  339. {
  340. MailSender.InviaErrore(ex, "SetUserInfo", param);
  341. return new RegistrationCompleteResult { Result = RESULT_ERROR, Message = -1 };
  342. }
  343. }
  344.  
  345. public List<CallHistoryResult> CallHistory(Stream data)
  346. {
  347. string param = string.Empty;
  348. try
  349. {
  350. param = new StreamReader(data).ReadToEnd();
  351. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  352.  
  353. string token = nv["token"];
  354. string hash = nv["hash"];
  355.  
  356. if (!CheckHash(hash, token))
  357. return null;
  358.  
  359. int morUserId;
  360. string myNumber;
  361. Guid userId = Guid.Parse(token);
  362. using (DbEntities db = new DbEntities())
  363. {
  364. UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
  365. if (u == null)
  366. return null;
  367.  
  368. morUserId = u.MorUserId;
  369. myNumber = u.DeviceExtension;
  370. }
  371.  
  372. MOR mor = new MOR(userId);
  373. List<MOR.Call> calls = mor.GetUserCalls(morUserId);
  374. if (calls == null)
  375. return null;
  376.  
  377. List<CallHistoryResult> result = new List<CallHistoryResult>(calls.Count);
  378. foreach (MOR.Call call in calls)
  379. {
  380. bool isOutgoing = call.Source == myNumber;
  381.  
  382. CallHistoryResult c = new CallHistoryResult();
  383. c.Datetime = call.CallDate.ToString("yyyy-MM-dd HH:mm:ss");
  384. c.IsOutgoing = isOutgoing;
  385. c.Number = isOutgoing ? call.Destination : call.Source;
  386.  
  387. result.Add(c);
  388. }
  389.  
  390. return result;
  391. }
  392. catch (Exception ex)
  393. {
  394. MailSender.InviaErrore(ex, "CallHistory", param);
  395. return null;
  396. }
  397. }
  398.  
  399. public GenericResult UserCredit(Stream data)
  400. {
  401. string param = string.Empty;
  402. try
  403. {
  404. SchedulerManager scheduler = new SchedulerManager();
  405. scheduler.Start();
  406.  
  407. param = new StreamReader(data).ReadToEnd();
  408. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  409.  
  410. string token = nv["token"];
  411. string hash = nv["hash"];
  412.  
  413. if (!CheckHash(hash, token))
  414. return new GenericResult { Result = RESULT_ERROR, Message = "-" };
  415.  
  416. Guid userId = Guid.Parse(token);
  417. using (DbEntities db = new DbEntities())
  418. {
  419. UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
  420. if (u == null)
  421. return new GenericResult { Result = RESULT_ERROR, Message = "-" };
  422.  
  423. MOR mor = new MOR(u.UserId);
  424. string balance = mor.GetUserBalance(u.Username);
  425.  
  426. return new GenericResult { Result = RESULT_OK, Message = balance ?? "-" };
  427. }
  428. }
  429. catch (Exception ex)
  430. {
  431. MailSender.InviaErrore(ex, "UserCredit", param);
  432. return new GenericResult { Result = RESULT_ERROR, Message = "-" };
  433. }
  434. }
  435.  
  436.  
  437.  
  438. public GenericResult PaypalPayment(Stream data)
  439. {
  440. string param = string.Empty;
  441. try
  442. {
  443. param = new StreamReader(data).ReadToEnd();
  444. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  445.  
  446. string token = nv["token"];
  447. string currencyCode = nv["code"];
  448. string amount = nv["amount"];
  449. string paymentId = nv["transaction"];
  450. string createDate = nv["date"];
  451. string type = nv["type"];
  452. string hash = nv["hash"];
  453. string did_durata = nv["durata"]; //no hash
  454. string did_country_prefix = nv["country"]; //no hash
  455.  
  456. if (!CheckHash(hash, token, currencyCode, amount, paymentId, createDate, type))
  457. return new GenericResult { Result = RESULT_ERROR, MessageCode = 1 };
  458.  
  459. Guid userId = Guid.Parse(token);
  460. using (DbEntities db = new DbEntities())
  461. {
  462. UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
  463. if (u == null)
  464. return new GenericResult { Result = RESULT_ERROR, MessageCode = 2 };
  465.  
  466. Transazioni t = new Transazioni();
  467. t.PaymentId = paymentId;
  468. t.CreateTime = createDate;
  469. t.UserId = u.UserId;
  470. t.Amount = amount;
  471. t.Currency = currencyCode;
  472. t.Type = type;
  473. t.Verified = false;
  474. db.Transazioni.Add(t);
  475. db.SaveChanges();
  476.  
  477. if (!VerificaTransazione(paymentId))
  478. return new GenericResult { Result = RESULT_ERROR, MessageCode = 8 };
  479.  
  480. MOR mor = new MOR(u.UserId);
  481. if (type == "credit")
  482. {
  483. //ricarico il conto
  484. if (!mor.UpdateUserBalance(u.Username, u.MorUserId.ToString(), currencyCode, amount, "paypal", paymentId))
  485. return new GenericResult { Result = RESULT_ERROR, MessageCode = 9 };
  486. }
  487. else
  488. {
  489. //associo un did del paese scelto all'utente
  490. string did = mor.AssignDidToDevice(did_country_prefix, u.DeviceId.ToString(), u.Username);
  491. if (did == null)
  492. return new GenericResult { Result = RESULT_ERROR, MessageCode = 10 };
  493.  
  494. DateTime date = DateTime.Now.ToCentralEuropeTime();
  495. Did d = new Did();
  496. d.Number = did;
  497. d.Enabled = true;
  498. d.EndDate = date.Date.AddDays(double.Parse(did_durata) + 1).AddMinutes(-1);
  499. d.PaymentId = paymentId;
  500. d.StartDate = date;
  501. d.UserId = userId;
  502. d.Prefix = did_country_prefix;
  503. db.Did.Add(d);
  504. db.SaveChanges();
  505. }
  506.  
  507. return new GenericResult { Result = RESULT_OK, Message = "" };
  508. }
  509. }
  510. catch (Exception ex)
  511. {
  512. MailSender.InviaErrore(ex, "PaypalPayment", param);
  513. return new GenericResult { Result = RESULT_ERROR, MessageCode = -1 };
  514. }
  515. }
  516.  
  517.  
  518. public GenericResult RedeemVoucher(Stream data)
  519. {
  520. string param = string.Empty;
  521. try
  522. {
  523. param = new StreamReader(data).ReadToEnd();
  524. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  525.  
  526. string token = nv["token"];
  527. string code = nv["code"];
  528. string hash = nv["hash"];
  529.  
  530. if (!CheckHash(hash, token, code))
  531. return new GenericResult { Result = RESULT_ERROR, MessageCode = 1 };
  532.  
  533. Guid userId = Guid.Parse(token);
  534. using (DbEntities db = new DbEntities())
  535. {
  536. UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
  537. if (u == null)
  538. return new GenericResult { Result = RESULT_ERROR, MessageCode = 2 };
  539.  
  540. MOR mor = new MOR(u.UserId);
  541. //ricarico il conto
  542. string voucher_amount;
  543. if (!mor.UseVoucher(u.MorUserId.ToString(), code, out voucher_amount))
  544. return new GenericResult { Result = RESULT_ERROR, MessageCode = 11 };
  545.  
  546. string balance = mor.GetUserBalance(u.Username);
  547. return new GenericResult { Result = RESULT_OK, Message = voucher_amount + "|" + balance };
  548. }
  549. }
  550. catch (Exception ex)
  551. {
  552. MailSender.InviaErrore(ex, "RedeemVoucher", param);
  553. return new GenericResult { Result = RESULT_ERROR, MessageCode = -1 };
  554. }
  555. }
  556.  
  557. public List<FreeDidResult> FreeDidList(Stream data)
  558. {
  559. string param = string.Empty;
  560. try
  561. {
  562. param = new StreamReader(data).ReadToEnd();
  563. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  564.  
  565. string token = nv["token"];
  566. string hash = nv["hash"];
  567.  
  568. if (!CheckHash(hash, token))
  569. return null;
  570.  
  571. Guid userId = Guid.Parse(token);
  572. using (DbEntities db = new DbEntities())
  573. {
  574. Users u = db.Users.FirstOrDefault(c => c.UserId.Equals(userId));
  575. if (u == null)
  576. return null;
  577.  
  578. MOR mor = new MOR(userId);
  579. List<string> dids = mor.GetFreeDid();
  580.  
  581. List<Countries> filteredCountries = new List<Countries>();
  582. List<Countries> countries = db.Countries.ToList();
  583. foreach (string did in dids)
  584. {
  585. var temp = countries.FirstOrDefault(c => did.StartsWith(c.Prefix));
  586. if (temp != null && filteredCountries.All(c => c.CountryId != temp.CountryId))
  587. filteredCountries.Add(temp);
  588. }
  589.  
  590. if (filteredCountries.Count == 0)
  591. return null;
  592.  
  593. return filteredCountries.Select(c => new FreeDidResult { CountryId = c.CountryId, CountryName = c.CountryName, Prefix = c.Prefix }).ToList();
  594. }
  595. }
  596. catch (Exception ex)
  597. {
  598. MailSender.InviaErrore(ex, "FreeDidList", param);
  599. return null;
  600. }
  601. }
  602.  
  603. public List<DidListResult> UserDidList(Stream data)
  604. {
  605. string param = string.Empty;
  606. try
  607. {
  608. param = new StreamReader(data).ReadToEnd();
  609. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  610.  
  611. string token = nv["token"];
  612. string hash = nv["hash"];
  613.  
  614. if (!CheckHash(hash, token))
  615. return null;
  616.  
  617. Guid userId = Guid.Parse(token);
  618. using (DbEntities db = new DbEntities())
  619. {
  620. var result = (from did in db.Did
  621. join country in db.Countries on did.Prefix equals country.Prefix
  622. where did.Enabled && did.UserId.Equals(userId)
  623. select new { did.Number, did.EndDate, country.CountryName }).ToList();
  624.  
  625. return result.Select(c => new DidListResult { Number = c.Number, Scadenza = c.EndDate.ToString("yyyy-MM-dd HH:mm"), Country = c.CountryName }).ToList();
  626. }
  627. }
  628. catch (Exception ex)
  629. {
  630. MailSender.InviaErrore(ex, "UserDidList", param);
  631. return null;
  632. }
  633. }
  634.  
  635.  
  636.  
  637. public SettingsResult Settings(Stream data)
  638. {
  639. string param = string.Empty;
  640. try
  641. {
  642. param = new StreamReader(data).ReadToEnd();
  643. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  644.  
  645. string token = nv["token"];
  646. string hash = nv["hash"];
  647.  
  648. if (!CheckHash(hash, token))
  649. return new SettingsResult { Result = RESULT_ERROR, Message = 1 };
  650.  
  651. Guid userId = Guid.Parse(token);
  652. int deviceId;
  653. bool didsAvailable;
  654. string myNumber;
  655. using (DbEntities db = new DbEntities())
  656. {
  657. var u = db.Users.Where(c => c.UserId.Equals(userId) && c.IsActive).Select(c => new { c.UserInfo.DeviceId, c.Prefix, c.Number }).FirstOrDefault();
  658. if (u == null)
  659. return new SettingsResult { Result = RESULT_ERROR, Message = 2 };
  660.  
  661. deviceId = u.DeviceId;
  662. myNumber = u.Prefix + u.Number;
  663. didsAvailable = db.Did.Any(c => c.Enabled && c.UserId.Equals(userId));
  664. }
  665.  
  666. MOR mor = new MOR(userId);
  667. string forwardNumber = mor.GetCallFlowNumber(deviceId.ToString());
  668.  
  669. SettingsResult result = new SettingsResult();
  670. result.Result = RESULT_OK;
  671. result.DeviazioneStandard = !string.IsNullOrEmpty(forwardNumber);
  672. if (result.DeviazioneStandard)
  673. result.DeviazioneNumero = forwardNumber.StartsWith("+") ? forwardNumber : "+" + forwardNumber;
  674. result.DidEnabled = didsAvailable && forwardNumber.Replace("+", "") == myNumber;
  675. result.DidAvailable = didsAvailable;
  676.  
  677. return result;
  678. }
  679. catch (Exception ex)
  680. {
  681. MailSender.InviaErrore(ex, "Settings", param);
  682. return new SettingsResult { Result = RESULT_ERROR, Message = -1 };
  683. }
  684. }
  685.  
  686.  
  687. public GenericResult EditCallFlow(Stream data)
  688. {
  689. string param = string.Empty;
  690. try
  691. {
  692. param = new StreamReader(data).ReadToEnd();
  693. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  694.  
  695. string token = nv["token"];
  696. string forward = nv["number"];
  697. string hash = nv["hash"];
  698.  
  699. if (!CheckHash(hash, token, forward))
  700. return new GenericResult { Result = RESULT_ERROR, MessageCode = 1 };
  701.  
  702. Guid userId = Guid.Parse(token);
  703. int deviceId;
  704. using (DbEntities db = new DbEntities())
  705. {
  706. UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
  707. if (u == null)
  708. return new GenericResult { Result = RESULT_ERROR, MessageCode = 2 };
  709.  
  710. deviceId = u.DeviceId;
  711. }
  712.  
  713. MOR mor = new MOR(userId);
  714. if (string.IsNullOrEmpty(forward))
  715. {
  716. //rimuovo la deviazione
  717. if (!mor.RemoveForward(deviceId.ToString()))
  718. return new GenericResult { Result = RESULT_ERROR, MessageCode = 12 };
  719. }
  720. else
  721. {
  722. //aggiungo la deviazione
  723. if (!mor.SetForward(deviceId.ToString(), forward))
  724. return new GenericResult { Result = RESULT_ERROR, MessageCode = 13 };
  725. }
  726.  
  727. return new GenericResult { Result = RESULT_OK, Message = forward };
  728. }
  729. catch (Exception ex)
  730. {
  731. MailSender.InviaErrore(ex, "EditCallFlow", param);
  732. return new GenericResult { Result = RESULT_ERROR, MessageCode = -1 };
  733. }
  734. }
  735.  
  736. public GenericResult VerifyNumber(Stream data)
  737. {
  738. //per i quickforward
  739. string param = string.Empty;
  740. try
  741. {
  742. param = new StreamReader(data).ReadToEnd();
  743. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  744.  
  745. string token = nv["token"];
  746. string number = nv["number"];
  747. string code = nv["code"];
  748. string hash = nv["hash"];
  749. bool firstStep = string.IsNullOrEmpty(code);
  750.  
  751. bool isValidHash = firstStep ? CheckHash(hash, token, number) : CheckHash(hash, token, code);
  752.  
  753. if (!isValidHash)
  754. return new GenericResult { Result = RESULT_ERROR, MessageCode = 1 };
  755.  
  756. Guid userId = Guid.Parse(token);
  757. using (DbEntities db = new DbEntities())
  758. {
  759. if (firstStep)
  760. {
  761. UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
  762. if (u == null)
  763. {
  764. MailSender.InviaErrore("Uso senza essere registrati del metodo di invio codice conferma su inserimento Deviazioni", "VerifyNumber", token, number, code);
  765. return new GenericResult { Result = RESULT_ERROR, MessageCode = 2 };
  766. }
  767.  
  768. int codice = GeneraCodice();
  769. NumberVerified num = new NumberVerified();
  770. num.CreatedDate = DateTime.Now.ToCentralEuropeTime();
  771. if (number.StartsWith("+"))
  772. num.Number = number.Replace("+", "");
  773. else
  774. num.Number = number;
  775. num.OTP = codice;
  776. num.Used = false;
  777. num.UserId = userId;
  778.  
  779. if (SMSEnabled)
  780. {
  781. //controllo che per la giornata odierna non ci siano troppi tentativi
  782. DateTime now = DateTime.Now.ToCentralEuropeTime();
  783. int day = now.Day;
  784. int month = now.Month;
  785. int year = now.Year;
  786. if (db.NumberVerified.Count(c => c.UserId.Equals(userId) && c.CreatedDate.Day == day && c.CreatedDate.Month == month && c.CreatedDate.Year == year) >= 5)
  787. return new GenericResult { Result = RESULT_ERROR, MessageCode = 3 };
  788.  
  789. if (!SMSSender.Send(u.UserId, db, number, codice))
  790. return new GenericResult { Result = RESULT_ERROR, MessageCode = 4 };
  791. }
  792.  
  793. db.NumberVerified.Add(num);
  794. db.SaveChanges();
  795. }
  796. else
  797. {
  798. int otp = int.Parse(code);
  799. NumberVerified num = SMSEnabled ?
  800. db.NumberVerified.FirstOrDefault(c => c.UserId.Equals(userId) && c.OTP == otp && !c.Used) :
  801. db.NumberVerified.OrderByDescending(c => c.Progressivo).FirstOrDefault(c => c.UserId.Equals(userId));
  802.  
  803. if (num == null)
  804. return new GenericResult { Result = RESULT_CUSTOM };
  805.  
  806. num.Used = true;
  807. db.SaveChanges();
  808.  
  809. return new GenericResult { Result = RESULT_OK, Message = "+" + num.Number };
  810. }
  811. }
  812.  
  813. return new GenericResult { Result = RESULT_OK, Message = "" };
  814. }
  815. catch (Exception ex)
  816. {
  817. MailSender.InviaErrore(ex, "VerifyNumber", param);
  818. return new GenericResult { Result = RESULT_ERROR, MessageCode = -1 };
  819. }
  820. }
  821.  
  822.  
  823.  
  824. public RatesResult Rates(Stream data)
  825. {
  826. string param = string.Empty;
  827. try
  828. {
  829. param = new StreamReader(data).ReadToEnd();
  830. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  831.  
  832. string token = nv["token"];
  833. string number = nv["number"];
  834. string hash = nv["hash"];
  835.  
  836. if (!CheckHash(hash, token, number))
  837. return new RatesResult { Result = RESULT_ERROR };
  838.  
  839. Guid userId = Guid.Parse(token);
  840. using (DbEntities db = new DbEntities())
  841. {
  842. UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
  843. if (u == null)
  844. return new RatesResult { Result = RESULT_ERROR };
  845.  
  846. MOR mor = new MOR(userId);
  847. string result = mor.GetRates(u.Username, number);
  848. if (result == null)
  849. return new RatesResult { Result = RESULT_ERROR };
  850.  
  851. //0.987#Lithuania#370->prefix con altre cifre
  852. string[] rate = result.Split('#');
  853.  
  854. return new RatesResult { Result = RESULT_OK, Cost = rate[0].FormatCurrency(), CountryName = rate[1] };
  855. }
  856. }
  857. catch (Exception ex)
  858. {
  859. MailSender.InviaErrore(ex, "Rates", param);
  860. return new RatesResult { Result = RESULT_ERROR };
  861. }
  862. }
  863.  
  864.  
  865. public GenericResult MatchContact(Stream data)
  866. {
  867. string param = string.Empty;
  868. try
  869. {
  870. param = new StreamReader(data).ReadToEnd();
  871. NameValueCollection nv = HttpUtility.ParseQueryString(param);
  872.  
  873. string token = nv["token"];
  874. string prefix = nv["prefix"];
  875. string ids = nv["ids"];
  876. string numbers = nv["numbers"];
  877. string hash = nv["hash"];
  878.  
  879. if (!CheckHash(hash, token, prefix))
  880. return new GenericResult { Result = RESULT_ERROR, MessageCode = 1 };
  881.  
  882. prefix = prefix.Replace("+", "");
  883. Guid userId = Guid.Parse(token);
  884. using (DbEntities db = new DbEntities())
  885. {
  886. UserInfo u = db.UserInfo.FirstOrDefault(c => c.UserId.Equals(userId));
  887. if (u == null)
  888. return new GenericResult { Result = RESULT_ERROR, MessageCode = 2 };
  889.  
  890. string[] _ids = ids.Split(',');
  891. string[] temp = numbers.Split(','); //devo ripulire i numeri da * + () e spazi
  892. List<string> _numbers = new List<string>(temp.Length);
  893. foreach (var num in temp)
  894. {
  895. _numbers.Add(new string(num.Where(char.IsDigit).ToArray()));
  896. }
  897.  
  898. List<Contact> contatti = new List<Contact>();
  899. for (int i = 0; i < _ids.Length; i++)
  900. {
  901. var contatto = contatti.FirstOrDefault(c => c.Id.Equals(_ids[i]));
  902. if (contatto != null)
  903. contatto.Number.Add(_numbers[i]);
  904. else
  905. contatti.Add(new Contact(_ids[i], _numbers[i]));
  906. }
  907.  
  908. List<string> dbNumber = db.Users.Select(c => c.Prefix + c.Number).ToList();
  909.  
  910. foreach (var contact in contatti)
  911. {
  912. if (dbNumber.Any(c => contact.Number.Contains(c) || contact.Number.Select(d => prefix + d).Contains(c)))
  913. contact.Matched = true;
  914. }
  915.  
  916. if (contatti.Count == 0)
  917. return new GenericResult { Result = RESULT_OK, Message = "" };
  918.  
  919. return new GenericResult { Result = RESULT_OK, Message = string.Join(",", contatti.Where(c => c.Matched).Select(c => c.Id)) };
  920. }
  921. }
  922. catch (Exception ex)
  923. {
  924. MailSender.InviaErrore(ex, "MatchContact", param);
  925. return new GenericResult { Result = RESULT_ERROR, MessageCode = -1 };
  926. }
  927. }
  928.  
  929. private class Contact
  930. {
  931. public string Id { get; private set; }
  932. public List<string> Number { get; private set; }
  933. public bool Matched { get; set; }
  934.  
  935. public Contact(string id, string number)
  936. {
  937. Id = id;
  938. Number = new List<string>();
  939. Number.Add(number);
  940. }
  941. }
  942.  
  943.  
  944. private bool VerificaTransazione(string paymentId)
  945. {
  946. //todo: verificare pagamento
  947. //https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
  948. return true;
  949. /* try
  950. {
  951.  
  952. //salvo la transazione prima della verifica
  953. Transazioni tr = new Transazioni();
  954. tr.UserId = userId;
  955. tr.Codice = response_id;
  956. tr.Response = paypalResponse;
  957. tr.Data = DateTime.Now;
  958. tr.Verificata = false;
  959. tr.CreditPackId = creditPackId;
  960. db.AddToTransazioni(tr);
  961. db.SaveChanges();
  962.  
  963. //chiedo a paypal i dati della transazione e verifico le condizioni di cui sopra
  964. // Get a reference to the config section in Web.Config
  965. var config = ConfigManager.Instance.GetProperties();
  966. // Use OAuthTokenCredential to request an access token from PayPal
  967. var accessToken = new OAuthTokenCredential(config).GetAccessToken();
  968. var apiContext = new APIContext(accessToken);
  969. // Initialize the apiContext's configuration with the default configuration for this application.
  970. apiContext.Config = ConfigManager.Instance.GetProperties();
  971.  
  972. var payment = Payment.Get(apiContext, response_id); //response_id è il codice della transazione
  973.  
  974. bool state = payment.state == "approved";
  975. string totale_da_pagare = db.Crediti.First(c => c.CreditPackId == creditPackId).CreditPrice;
  976. var transaction = payment.transactions.FirstOrDefault(c => c.amount != null && c.amount.total == totale_da_pagare && c.amount.currency == "EUR");
  977. string transactionId = null;
  978. bool related_resources = false;
  979.  
  980. if (transaction != null)
  981. {
  982. tr.Amount = transaction.amount.total;
  983. tr.Currency_code = transaction.amount.currency;
  984.  
  985. var rr = transaction.related_resources.FirstOrDefault(c => c.sale != null && c.sale.state == "completed");
  986. if (rr != null)
  987. {
  988. related_resources = true;
  989. transactionId = rr.sale.id;
  990. }
  991. }
  992.  
  993. bool verificata = state && transaction != null && related_resources;
  994.  
  995. tr.PaymentJson = payment.ConvertToJson();
  996. tr.Timestamp = payment.create_time;
  997. tr.Token = transactionId;
  998. tr.Verificata = verificata;
  999. db.SaveChanges();
  1000.  
  1001. return verificata;
  1002. }
  1003. catch (PayPal.PayPalException ex)
  1004. {
  1005. MailSender.InoltraErrore(ex, "VerificaTransazione", String.Format("response_id: {0} - fullResponse: {1}", response_id, paypalResponse));
  1006. return false;
  1007. }*/
  1008. }
  1009.  
  1010. private int GeneraCodice()
  1011. {
  1012. Random r = new Random();
  1013. return r.Next(10000, 99999);
  1014. }
  1015.  
  1016.  
  1017. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement