Advertisement
Guest User

Untitled

a guest
Jul 17th, 2017
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 61.00 KB | None | 0 0
  1. import com.bitstep.BitStep;
  2. import com.bitstep.database.classes.dbShop;
  3. import com.bitstep.database.classes.dbUser;
  4. import com.bitstep.utils.EmailFactory;
  5. import com.liqpay.LiqPay;
  6. import org.apache.log4j.Logger;
  7. import org.json.simple.JSONArray;
  8. import org.json.simple.JSONObject;
  9. import ru.tsyklop.web.WebCookies;
  10. import ru.tsyklop.web.WebHashes;
  11. import ru.tsyklop.web.WebRequest;
  12. import ru.tsyklop.web.WebSession;
  13.  
  14. import java.io.File;
  15. import java.sql.SQLException;
  16. import java.text.SimpleDateFormat;
  17. import java.util.Calendar;
  18. import java.util.Date;
  19. import java.util.HashMap;
  20.  
  21. import static com.bitstep.BitStep.*;
  22.  
  23. /**
  24.  * Created by sloyev_php on 23.05.2017.
  25.  */
  26. public class UserModel implements Model {
  27.  
  28.     private int ID;
  29.     private String HASH;
  30.  
  31.     private String MESSAGE;
  32.  
  33.     private boolean AUTH;
  34.     private boolean ADMIN;
  35.  
  36.     private boolean ERROR = false;
  37.     private boolean SUCCESS = false;
  38.     private boolean MOBILE = false;
  39.     private boolean PARAMETERS = false;
  40.     private boolean VERIFICATION = false;
  41.     private boolean AUTHENTICATION = false;
  42.  
  43.     private dbUser dbUser;
  44.     private dbShop dbShop;
  45.  
  46.     private WebRequest UTILS;
  47.     private WebSession SESSION;
  48.     private WebCookies COOKIES;
  49.     private WebHashes HASHES;
  50.  
  51.     private EmailFactory EMAIL;
  52.  
  53.     private JSONObject result = new JSONObject();
  54.  
  55.     public static final int USER_ACTION_CONNECT = 0;
  56.     public static final int USER_ACTION_LOGIN = 1;
  57.     public static final int USER_ACTION_REGISTER = 2;
  58.     public static final int USER_ACTION_FACEBOOK = 3;
  59.     public static final int USER_ACTION_LOGOUT = 4;
  60.     public static final int USER_ACTION_FORGOT = 5;
  61.     public static final int USER_ACTION_GET_INFO = 6;
  62.     public static final int USER_ACTION_GET_DATE = 7;
  63.     public static final int USER_ACTION_GET_DAY = 8;
  64.     public static final int USER_ACTION_GET_WEEK = 9;
  65.     public static final int USER_ACTION_GET_MONTH = 10;
  66.     public static final int USER_ACTION_UPDATE_INFO = 11;
  67.     public static final int USER_ACTION_UPDATE_PASSWORD = 12;
  68.     public static final int USER_ACTION_ADD_STEPS = 13;
  69.     public static final int USER_ACTION_UPDATE_STEPS = 14;
  70.     public static final int USER_ACTION_GET_PARTNERS = 15;
  71.     public static final int USER_ACTION_GET_WEB = 16;
  72.     public static final int USER_ACTION_GET_RESULTS = 17;
  73.  
  74.     public static final int USER_ACTION_SHOP_BUY = 50;
  75.     public static final int USER_ACTION_SHOP_GET_ALL_LIST = 51;
  76.     public static final int USER_ACTION_SHOP_GET_USER_LIST = 52;
  77.     public static final int USER_ACTION_SHOP_GET_CLOTH_LIST = 53;
  78.     public static final int USER_ACTION_SHOP_GET_PERSON_LIST = 54;
  79.     public static final int USER_ACTION_SHOP_GET_WEEKENDS_PRODUCTS = 55;
  80.     public static final int USER_ACTION_SHOP_GET_COINS_PRODUCTS = 56;
  81.     public static final int USER_ACTION_SHOP_GET_VIP_PRODUCT = 57;
  82.     public static final int USER_ACTION_SHOP_BUY_CLOTH= 58;
  83.     public static final int USER_ACTION_SHOP_BUY_PERSON= 59;
  84.  
  85.     public static final int USER_ACTION_ERROR = -1;
  86.     public static final int USER_ACTION_PARAMETERS = -2;
  87.     public static final int USER_ACTION_VERIFICATION = -3;
  88.  
  89.     private static final Logger LOGGER = Logger.getLogger(UserModel.class);
  90.  
  91.     public UserModel(WebRequest UTILS) {
  92.         if (UTILS != null) {
  93.  
  94.             this.UTILS = UTILS;
  95.  
  96.             SESSION = UTILS.getSession();
  97.             COOKIES = UTILS.getCookies();
  98.             HASHES = UTILS.getHashes();
  99.  
  100.             this.AUTH = SESSION.getBoolean("AUTH");
  101.             this.ADMIN = SESSION.getBoolean("ADMIN");
  102.  
  103.             MOBILE = UTILS.containsHeader("mobile");
  104.  
  105.             if (!this.MOBILE) {
  106.                 this.ID = SESSION.getInt(BitStep.SESSION_USER_ID);
  107.                 this.HASH = SESSION.getString(BitStep.SESSION_USER_HASH);
  108.             } else if(UTILS.containsHeader("key")) {
  109.                 String [] sKey = UTILS.getHeaderString("key").split(BitStep.USER_HASH_SPLITTER);
  110.                 if(sKey.length > 0) {
  111.                     if(sKey[0]!=null&&sKey[1]!=null) {
  112.                         this.ID = Integer.parseInt(sKey[0]);
  113.                         this.HASH = sKey[1];
  114.                     }
  115.                 }
  116.             } else {
  117.                 this.ID = 0;
  118.                 this.HASH = "";
  119.             }
  120.  
  121.             this.EMAIL = new EmailFactory(UTILS.getRoot());
  122.             dbUser = new dbUser();
  123.             dbShop = new dbShop();
  124.         }
  125.     }
  126.  
  127.     public int getID() {
  128.         return this.ID;
  129.     }
  130.  
  131.     public String getHASH() {
  132.         return this.HASH;
  133.     }
  134.  
  135.     public boolean isAuth() {
  136.         return this.AUTH;
  137.     }
  138.  
  139.     public boolean isAdmin() {
  140.         return this.ADMIN;
  141.     }
  142.  
  143.     public EmailFactory getEMAIL() {
  144.         return EMAIL;
  145.     }
  146.  
  147.     public void Error() {
  148.         ERROR = true;
  149.         MESSAGE = "Error! Please try again";
  150.     }
  151.  
  152.     public void Error(String mgs) {
  153.         ERROR = true;
  154.         MESSAGE = mgs;
  155.     }
  156.  
  157.     public void Success() {
  158.         SUCCESS = true;
  159.         MESSAGE = "Успех.";
  160.     }
  161.  
  162.     public void Success(String mgs) {
  163.         SUCCESS = true;
  164.         MESSAGE = mgs;
  165.     }
  166.  
  167.     public void Parameters() {
  168.         PARAMETERS = true;
  169.     }
  170.  
  171.     public void Verification() {
  172.         VERIFICATION = true;
  173.     }
  174.  
  175.     public void Authentication() {
  176.         AUTHENTICATION = true;
  177.     }
  178.  
  179.     public JSONObject Execute(int type) throws Exception {
  180.         if(type >= 0) {
  181.             result.clear();
  182.             //System.out.println(UTILS.getParams().toJSONString());
  183.             switch (type) {
  184.                 case USER_ACTION_ERROR:
  185.                     Error();
  186.                     break;
  187.                 case USER_ACTION_PARAMETERS:
  188.                     Parameters();
  189.                     break;
  190.                 case USER_ACTION_VERIFICATION:
  191.                     Verification();
  192.                     break;
  193.                 case USER_ACTION_CONNECT:
  194.                     Connect();
  195.                     break;
  196.                 case USER_ACTION_LOGIN:
  197.                     Login(UTILS.getParams(), false);
  198.                     break;
  199.                 case USER_ACTION_REGISTER:
  200.                     Register(false);
  201.                     break;
  202.                 case USER_ACTION_FACEBOOK:
  203.                     Facebook();
  204.                     break;
  205.                 case USER_ACTION_LOGOUT:
  206.                     Logout();
  207.                     break;
  208.                 case USER_ACTION_FORGOT:
  209.                     Forgot();
  210.                     break;
  211.                 case USER_ACTION_GET_INFO:
  212.                     GetInfo();
  213.                     break;
  214.                 case USER_ACTION_GET_DATE:
  215.                     GetDate();
  216.                     break;
  217.                 case USER_ACTION_GET_WEEK:
  218.                     GetWeek(UTILS.getParamString("date"));
  219.                     break;
  220.                 case USER_ACTION_GET_DAY:
  221.                     GetDay(UTILS.getParamString("date"));
  222.                     break;
  223.                 case USER_ACTION_GET_MONTH:
  224.                     GetMonth(UTILS.getParamString("date"));
  225.                     break;
  226.                 case USER_ACTION_UPDATE_INFO:
  227.                     UpdateInfo();
  228.                     break;
  229.                 case USER_ACTION_UPDATE_PASSWORD:
  230.                     UpdatePassword();
  231.                     break;
  232.                 case USER_ACTION_ADD_STEPS:
  233.                     AddSteps();
  234.                     break;
  235.                 case USER_ACTION_UPDATE_STEPS:
  236.                     UpdateSteps();
  237.                     break;
  238.                 case USER_ACTION_SHOP_BUY:
  239.                     ShopBuy();
  240.                     break;
  241.                 case USER_ACTION_SHOP_GET_ALL_LIST:
  242.                     //ShopGetAllProducts();
  243.                     break;
  244.                 case USER_ACTION_SHOP_GET_USER_LIST:
  245.                     ShopGetUserProducts();
  246.                     break;
  247.                 case USER_ACTION_SHOP_GET_CLOTH_LIST:
  248.                     ShopGetClothProducts();
  249.                     break;
  250.                 case USER_ACTION_SHOP_GET_PERSON_LIST:
  251.                     ShopGetPersonProducts();
  252.                     break;
  253.                 case USER_ACTION_SHOP_GET_WEEKENDS_PRODUCTS:
  254.                     ShopGetWeekendsProducts();
  255.                     break;
  256.                 case USER_ACTION_SHOP_GET_COINS_PRODUCTS:
  257.                     ShopGetCoinsProducts();
  258.                     break;
  259.                 case USER_ACTION_SHOP_GET_VIP_PRODUCT:
  260.                     ShopGetVipProduct();
  261.                     break;
  262.                 case USER_ACTION_SHOP_BUY_CLOTH:
  263.                     ShopBuyCloth();
  264.                     break;
  265.                 case USER_ACTION_SHOP_BUY_PERSON:
  266.                     ShopBuyPerson();
  267.                     break;
  268.                 case USER_ACTION_GET_PARTNERS:
  269.                     GetPartners();
  270.                     break;
  271.                 case USER_ACTION_GET_WEB:
  272.                     GetWeb();
  273.                     break;
  274.                 case USER_ACTION_GET_RESULTS:
  275.                     GetResults();
  276.                     break;
  277.                 default:
  278.                     break;
  279.             }
  280.         } else {
  281.             Error();
  282.         }
  283.  
  284.         if (SUCCESS) {
  285.             result.put(BitStep.TYPE_STATUS, BitStep.TYPE_SUCCESS);
  286.             result.put(BitStep.TYPE_MESSAGE, MESSAGE);
  287.         }
  288.  
  289.         if (ERROR) {
  290.             result.clear();
  291.             result.put(BitStep.TYPE_STATUS, BitStep.TYPE_ERROR);
  292.             result.put(BitStep.TYPE_MESSAGE, MESSAGE);
  293.         }
  294.  
  295.         if(PARAMETERS) {
  296.             result.clear();
  297.             result.put(BitStep.TYPE_STATUS, BitStep.TYPE_ERROR);
  298.             result.put(BitStep.TYPE_MESSAGE, "Input data not received");
  299.         }
  300.  
  301.         if(AUTHENTICATION) {
  302.             result.clear();
  303.             result.put(BitStep.TYPE_AUTHENTICATION, BitStep.TYPE_ERROR);
  304.             result.put(BitStep.TYPE_MESSAGE, "Server authentication error");
  305.         }
  306.  
  307.         dbUser.close();
  308.         dbShop.close();
  309.  
  310.         return result;
  311.     }
  312.  
  313.     /* METHODS */
  314.  
  315.     private void Connect() {
  316.         boolean user = false;
  317.         try {
  318.             String hKey = UTILS.getHeaderString("key");
  319.             if (hKey != null && !hKey.isEmpty()) {
  320.                 String[] res = hKey.split(BitStep.USER_HASH_SPLITTER);
  321.                 if (res.length > 0 && res[0]!=null&&res[1]!=null) {
  322.                     int id = Integer.parseInt(res[0]);
  323.                     String hash = res[1];
  324.                     if (id > 0 && !hash.isEmpty()) {
  325.                         if (dbUser.CheckAuthUser(id, hash)) {
  326.                             String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
  327.  
  328.                             dbUser.SetVisited(id, date);
  329.                             user = true;
  330.                             GetInfo();
  331.  
  332.                             UserUpdateDeviceAndPush(id);
  333.  
  334.                             result.put("coin", dbUser.GetUserCoinOnDate(id, date));
  335.                         }
  336.                     }
  337.                 }
  338.             }
  339.             if (user) {
  340.                 result.put("user", true);
  341.             } else {
  342.                 result.put("user", false);
  343.             }
  344.         } catch (Exception e) {
  345.             e.printStackTrace();
  346.             result.put("user", false);
  347.         }
  348.         //result.put(BitStep.TYPE_STATUS, BitStep.TYPE_SUCCESS);
  349.         Success();
  350.     }
  351.  
  352.     private JSONObject Login(JSONObject data, boolean fb) throws Exception {
  353.         if(!isAuth()) {
  354.             if ((!fb&&data.containsKey("email")&&data.containsKey("password"))||(fb&&data.containsKey("email"))) {
  355.                 data = CheckAuthData(data, fb);
  356.  
  357.                 if (!data.containsKey(BitStep.TYPE_TEXT_ERROR)) {
  358.  
  359.                     if(!fb) {
  360.                         data.replace("password", HASHES.hashPassword(data.getString("email"), data.getString("password")));
  361.                         System.out.println(data.getString("password"));
  362.                         data.put("hash", HASHES.generate((data.getString("email")+data.getString("password")+HASHES.generate(10)), 64));
  363.                     }
  364.  
  365.                     data = dbUser.Login(data, fb);
  366.  
  367.                     if (data.getString(BitStep.TYPE_STATUS).equals(BitStep.TYPE_TEXT_SUCCESS)) {
  368.  
  369.                         AUTH = true;
  370.  
  371.                         dbUser.SetVisited(data.getInt("id"), new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
  372.  
  373.                         if(data.containsKey("mail")) {
  374.                             EMAIL.Send(data.getString("email"), 5, UTILS.BuildUrl(UTILS.getHeaderString("host"), "confirm", HASHES.generateToken(UTILS.getRequest())));
  375.                         }
  376.  
  377.                         result.put(BitStep.TYPE_STATUS, BitStep.TYPE_SUCCESS);
  378.                         result.put(BitStep.TYPE_MESSAGE, "Вы успешно авторизовались");
  379.  
  380.                         if(MOBILE) {
  381.                             ID = data.getInt("id");
  382.  
  383.                             UserUpdateDeviceAndPush(ID);
  384.  
  385.                             result.put("id", data.getInt("id"));
  386.                             result.put("key", data.getInt("id")+BitStep.USER_HASH_SPLITTER +data.getString("hash"));
  387.  
  388.                             GetInfo();
  389.                             GetMonth(new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime()));
  390.                         } else {
  391.                             result.put("url", "/account");
  392.                             result.put("id", data.getInt("id"));
  393.                             result.put("hash", data.getString("hash"));
  394.  
  395.                             SESSION.set("AUTH", true);
  396.                             SESSION.set(BitStep.SESSION_USER_ID, data.getInt("id"));
  397.                             SESSION.set(BitStep.SESSION_USER_HASH, data.getString("hash"));
  398.  
  399.                             JSONObject u = new JSONObject();
  400.                             u.put("id", data.getInt("id"));
  401.                             u.put("hash", data.getString("hash"));
  402.                             u.put("remember", true);
  403.                             COOKIES.create("/", "user", u, BitStep.COOKIES_AGE);
  404.                         }
  405.  
  406.                     } else {
  407.                         result.put(BitStep.TYPE_STATUS, BitStep.TYPE_ERROR);
  408.                         if (data.getString(BitStep.TYPE_STATUS).equals(BitStep.TYPE_EMPTY)) {
  409.                             result.put(BitStep.TYPE_MESSAGE, "E-Mail или пароль неверны");
  410.                         } else if (data.getString(BitStep.TYPE_STATUS).equals(BitStep.TYPE_ALREADY)) {
  411.                             result.put(BitStep.TYPE_MESSAGE, "Вы уже авторизованы");
  412.                         } else if(data.getString(BitStep.TYPE_STATUS).equals(BitStep.TYPE_CONFIRM)) {
  413.                             result.put(BitStep.TYPE_MESSAGE, "E-Mail не подтвержден");
  414.                         } else {
  415.                             Error();
  416.                         }
  417.                     }
  418.                 } else {
  419.                     result.put(BitStep.TYPE_STATUS, BitStep.TYPE_ERROR);
  420.  
  421.                     JSONObject error = (JSONObject) data.get(BitStep.TYPE_TEXT_ERROR);
  422.  
  423.                     if (error.containsKey("email")) {
  424.                         result.put("email", error.getString("email"));
  425.                     }
  426.  
  427.                     if (error.containsKey("password")) {
  428.                         result.put("password", error.getString("password"));
  429.                     }
  430.  
  431.                     if (error.containsKey("error")) {
  432.                         result.put(BitStep.TYPE_MESSAGE, error.getString("error"));
  433.                     }
  434.                 }
  435.             } else {
  436.                 Error();
  437.             }
  438.         } else {
  439.             Error();
  440.         }
  441.         return result;
  442.     }
  443.  
  444.     private JSONObject Register(boolean fb) throws Exception {
  445.  
  446.         if(!AUTH) {
  447.  
  448.             JSONObject data = UTILS.getParamJSONObject("data");
  449.  
  450.             if (!data.isEmpty()) {
  451.                 data = CheckRegisterData(data, fb);
  452.                 if (!data.containsKey(BitStep.TYPE_TEXT_ERROR)) {
  453.                     if (!fb) {
  454.                         data.put("confirm", 0);
  455.                         data.replace("p1", HASHES.hashPassword(data.getString("email"), data.getString("p1")));
  456.                     } else {
  457.                         data.put("confirm", 1);
  458.                         data.put("np", HASHES.generate(10));
  459.                         data.put("p1", HASHES.hashPassword(data.getString("email"), data.getString("np")));
  460.                     }
  461.                     data = dbUser.Register(data);
  462.                     if (!data.containsKey(BitStep.TYPE_TEXT_ERROR)) {
  463.  
  464.                         result.put("id", data.getInt("id"));
  465.                         result.put(BitStep.TYPE_STATUS, BitStep.TYPE_SUCCESS);
  466.                         result.put(BitStep.TYPE_MESSAGE, "Вы успешно зарегистрировались");
  467.  
  468.                         String token = HASHES.generateToken(UTILS.getRequest());
  469.  
  470.                         if (!fb && dbUser.AddConfirmRegister(data.getString("email"), token)) {
  471.                             EMAIL.Send(data.getString("email"), 1, UTILS.BuildUrl(UTILS.getHeaderString("host"), "confirm", token));
  472.                         }
  473.  
  474.                         if (fb) {
  475.                             result.put("data", data);
  476.                             EMAIL.Send(data.getString("email"), 4, data.getString("np"));
  477.                         }
  478.  
  479.                         JSONObject adt = new JSONObject();
  480.  
  481.                         if (data.containsKey("additions")) {
  482.                             adt = CheckAddition(((JSONObject) data.get("additions")), (data.getString("gender").equals("male")?1:2));
  483.                         } else {
  484.                             adt = GetEmptyAdditions((data.getString("gender").equals("male")?1:2));
  485.                         }
  486.  
  487.                         dbUser.AddAdditions(data.getInt("id"), adt);
  488.  
  489.                         if (!MOBILE) {
  490.                             result.put("url", "/");
  491.                         }
  492.  
  493.                     } else {
  494.                         result.put(BitStep.TYPE_STATUS, BitStep.TYPE_ERROR);
  495.  
  496.                         JSONObject error = (JSONObject) data.get(BitStep.TYPE_TEXT_ERROR);
  497.  
  498.                         String status = error.getString(BitStep.TYPE_STATUS);
  499.  
  500.                         if (status.equals(BitStep.TYPE_EXIST)) {
  501.                             result.put(BitStep.TYPE_MESSAGE, "Этот E-Mail адресс уже существует");
  502.                         } else {
  503.                             Error();
  504.                         }
  505.                     }
  506.                 } else {
  507.                     result.put(BitStep.TYPE_STATUS, BitStep.TYPE_ERROR);
  508.                     JSONObject error = (JSONObject) data.get("error");
  509.                     if (error.containsKey("firstname")) {
  510.                         result.put("firstname", error.get("firstname"));
  511.                     }
  512.                     if (error.containsKey("lastname")) {
  513.                         result.put("lastname", error.get("lastname"));
  514.                     }
  515.                     if (error.containsKey("email")) {
  516.                         result.put("email", error.get("email"));
  517.                     }
  518.                     if (error.containsKey("p1")) {
  519.                         result.put("p1", error.get("p1"));
  520.                     }
  521.                     if (error.containsKey("p2")) {
  522.                         result.put("p2", error.get("p2"));
  523.                     }
  524.                     if (error.containsKey("gender")) {
  525.                         result.put("gender", error.get("gender"));
  526.                     }
  527.  
  528.                 }
  529.             } else {
  530.                 Parameters();
  531.             }
  532.         } else {
  533.             Error();
  534.         }
  535.  
  536.         return result;
  537.     }
  538.  
  539.     private void Logout() throws Exception {
  540.         if(AUTH) {
  541.             if(ID > 0) {
  542.                 if(dbUser.Logout(ID)) {
  543.                     if (!MOBILE) {
  544.                         SESSION.remove("ID");
  545.                         SESSION.remove("HASH");
  546.                         COOKIES.remove("user");
  547.                     }
  548.                     result.put(BitStep.TYPE_STATUS, BitStep.TYPE_SUCCESS);
  549.                     result.put(BitStep.TYPE_MESSAGE, "Вы успешно вышли");
  550.                 }
  551.             } else {
  552.                 Parameters();
  553.             }
  554.         } else {
  555.             Authentication();
  556.         }
  557.     }
  558.  
  559.     private void Forgot() throws Exception {
  560.         if(!AUTH) {
  561.             if(UTILS.containsParam("email")) {
  562.                 String email = UTILS.getParamString("email");
  563.                 if(!email.isEmpty()) {
  564.                     if(email.matches(BitStep.EMAIL_REGEXP)) {
  565.                         int id = dbUser.CheckUserByEmail(email);
  566.                         if(id > 0) {
  567.                             String token = HASHES.generateToken(UTILS.getRequest());
  568.                             if(dbUser.ConfirmForgetAdd(email, token)) {
  569.                                 EMAIL.Send(email, 2, UTILS.BuildUrl(UTILS.getHeaderString("host"), "confirm", token));
  570.                                 result.put(BitStep.TYPE_STATUS, BitStep.TYPE_SUCCESS);
  571.                             } else {
  572.                                 Error();
  573.                             }
  574.                         } else {
  575.                             Error();
  576.                         }
  577.                     } else {
  578.                         Error();
  579.                     }
  580.                 } else {
  581.                     Error();
  582.                 }
  583.             } else {
  584.                 Parameters();
  585.             }
  586.         } else {
  587.             Error();
  588.         }
  589.     }
  590.  
  591.     private void Facebook() throws Exception {
  592.         if(!AUTH) {
  593.             JSONObject data = UTILS.getParamJSONObject("data");
  594.             if (!data.isEmpty()) {
  595.                 if (data.containsKey("email")) {
  596.                     if (dbUser.CheckUserByEmail(data.getString("email")) <= 0) {
  597.                         result = Register(true);
  598.                         if(result.containsKey("id")) {
  599.                             result = Login((JSONObject) result.get("data"), true);
  600.                         }
  601.                     } else {
  602.                         result = Login(data, true);
  603.                     }
  604.                 } else {
  605.                     Parameters();
  606.                 }
  607.             } else {
  608.                 Parameters();
  609.             }
  610.         } else {
  611.             Error();
  612.         }
  613.     }
  614.  
  615.     private void GetInfo() throws Exception {
  616.         if(AUTH) {
  617.             if (ID > 0) {
  618.                 result.put(BitStep.TYPE_STATUS, BitStep.TYPE_SUCCESS);
  619.                 result.put("info", dbUser.GetUserInfo(ID));
  620.             } else {
  621.                 Parameters();
  622.             }
  623.         } else {
  624.             Authentication();
  625.         }
  626.     }
  627.  
  628.     private void GetDate() throws Exception {
  629.         if(AUTH) {
  630.             if (ID > 0) {
  631.                 String date = UTILS.getParamString("date");
  632.  
  633.                 if(!date.isEmpty()) {
  634.  
  635.                     result.put("coins", dbUser.GetUserCoins(ID));
  636.                     result.put("cday", dbUser.GetUserCoinsOnDay(ID, date));
  637.                     result.put("data", dbUser.GetUserTableDataOnDate(ID, date));
  638.  
  639.                     //GetWebDateData(date);
  640.                     //GetWebPerson(dbUser.GetUserGender(ID));
  641.  
  642.                     ShopGetUserProducts();
  643.  
  644.                 } else {
  645.                     Parameters();
  646.                 }
  647.             } else {
  648.                 Parameters();
  649.             }
  650.         } else {
  651.             Authentication();
  652.         }
  653.     }
  654.  
  655.     private void GetDay(String date) throws Exception {
  656.         if (AUTH) {
  657.             if (!date.isEmpty()) {
  658.                 GetWebDateData(date);
  659.             } else {
  660.                 Parameters();
  661.             }
  662.         } else {
  663.             Authentication();
  664.         }
  665.     }
  666.  
  667.     private void GetWeek(String start) throws Exception {
  668.         if (AUTH) {
  669.             Calendar c = Calendar.getInstance();
  670.             c.add(Calendar.DAY_OF_MONTH, -7);
  671.  
  672.             String end = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
  673.  
  674.             if (!start.isEmpty() && !end.isEmpty()) {
  675.                 result.put("data", ConvertTableDataToObject(dbUser.GetUserTableDataOnWeek(ID, start, end)));
  676.             } else {
  677.                 Parameters();
  678.             }
  679.         } else {
  680.             Authentication();
  681.         }
  682.     }
  683.  
  684.     private void GetMonth(String start) throws Exception {
  685.         if (AUTH) {
  686.             Calendar c = Calendar.getInstance();
  687.             c.add(Calendar.DAY_OF_MONTH, -30);
  688.  
  689.             String end = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
  690.  
  691.             if (!start.isEmpty() && !end.isEmpty()) {
  692.                 result.put("data", ConvertTableDataToObject(dbUser.GetUserTableDataOnMonth(ID, start, end)));
  693.             } else {
  694.                 Parameters();
  695.             }
  696.         } else {
  697.             Authentication();
  698.         }
  699.     }
  700.  
  701.     private void GetInventory() throws Exception {
  702.         ShopGetUserProducts();
  703.  
  704.     }
  705.  
  706.     private void GetCurrentClothes() throws Exception {
  707.  
  708.     }
  709.  
  710.     private void UpdateInfo() throws Exception {
  711.         if(AUTH) {
  712.             JSONObject data = UTILS.getParamJSONObject("data");
  713.             if(!data.isEmpty()) {
  714.                 boolean success = false;
  715.                 if(data.containsKey("additions")) {
  716.                     JSONObject additions = (JSONObject) data.get("additions");
  717.                     data.remove("additions");
  718.  
  719.                     String values = "";
  720.                     for (Object o : data.keySet()) {
  721.                         String key = (String) o;
  722.                         values += key + "='" + data.get(key) + "',";
  723.                     }
  724.                     values = values.substring(0, values.lastIndexOf(","));
  725.                     //System.out.println(values);
  726.                     LOGGER.info(values);
  727.                     dbUser.UpdateUserInfo(ID, values);
  728.  
  729.                     JSONObject last = dbUser.GetLastUserRow(ID);
  730.                     last.remove("id");
  731.  
  732.                     if(!last.isEmpty()) {
  733.                         //int gender = ;
  734.                         boolean change = false;
  735.                         CheckAddition(additions, dbUser.GetUserGender(ID));
  736.                         for (Object o : additions.keySet()) {
  737.                             String key = (String) o;
  738.                             if(last.containsKey(key)) {
  739.                                 if(!last.getString(key).equals(additions.getString(key))) {
  740.                                     last.replace(key, additions.getString(key));
  741.                                     change=true;
  742.                                 }
  743.                             }
  744.                         }
  745.                         if(change) {
  746.                             dbUser.AddAdditions(ID, last);
  747.                         }
  748.                     }
  749.  
  750.                     result.put(BitStep.TYPE_STATUS, BitStep.TYPE_SUCCESS);
  751.                     result.put(BitStep.TYPE_MESSAGE, "Информация успешно обновлена");
  752.                 } else {
  753.                     Parameters();
  754.                 }
  755.             } else {
  756.                 Parameters();
  757.             }
  758.         } else {
  759.             Authentication();
  760.         }
  761.     }
  762.  
  763.     private void UpdatePassword() throws Exception {
  764.         if(AUTH) {
  765.             JSONObject data = UTILS.getParamJSONObject("data");
  766.             if (!data.isEmpty()) {
  767.                 /*if (data.containsKey("p0") && data.containsKey("p1") && data.containsKey("p2")) {
  768.                     String p0 = data.getString("p0");
  769.                     String p1 = data.getString("p1");
  770.                     String p2 = data.getString("p2");
  771.                     if (!p0.isEmpty()) {
  772.                         if (!p1.isEmpty()) {
  773.                             if (!p2.isEmpty()) {
  774.                                 if (p0.matches(BitStep.PASSWORD_REGEXP)) {
  775.                                     if (p1.matches(BitStep.PASSWORD_REGEXP)) {
  776.                                         if (p1.equals(p2)) {
  777.                                             String email = dbUser.GetUserField(ID, "email");
  778.                                             if(!email.isEmpty()) {
  779.                                                 p0 = HASHES.hashPassword(email, p0);
  780.                                                 p1 = HASHES.hashPassword(email, p1);
  781.                                                 if (dbUser.CheckPassword(ID, p0, p1)) {
  782.                                                     result.put(BitStep.TYPE_STATUS, BitStep.TYPE_SUCCESS);
  783.                                                     result.put(BitStep.TYPE_MESSAGE, "Пароль успешно обновлен");
  784.                                                 } else {
  785.                                                     Error();
  786.                                                 }
  787.                                             } else {
  788.                                                 Error();
  789.                                             }
  790.                                         } else {
  791.                                             result.put("p2", "Пароли не совпадают");
  792.                                         }
  793.                                     } else {
  794.                                         result.put("p1", "Пароль не соответствует требованиям");
  795.                                     }
  796.                                 } else {
  797.                                     result.put("p20", "Пароль не соответствует требованиям");
  798.                                 }
  799.                             } else {
  800.                                 result.put("p2", "Поле не может быть пустым");
  801.                             }
  802.                         } else {
  803.                             result.put("p1", "Поле не может быть пустым");
  804.                         }
  805.                     } else {
  806.                         result.put("p0", "Поле не может быть пустым");
  807.                     }
  808.                 }*/
  809.             } else {
  810.                 Parameters();
  811.             }
  812.         } else {
  813.             Authentication();
  814.         }
  815.     }
  816.  
  817.     private void AddSteps() throws Exception {
  818.         if (MOBILE) {
  819.             if(AUTH) {
  820.  
  821.                 JSONObject data = UTILS.getParamJSONObject("data");
  822.  
  823.                 /*System.out.println("execute - Add steps");
  824.                 System.out.println();*/
  825.  
  826.                 LOGGER.info("Execute - Add steps");
  827.                 LOGGER.info("USERID - "+ID);
  828.                 LOGGER.info("data - " + data.toString());
  829.  
  830.                 if (data.size() > 0) {
  831.  
  832.                     JSONObject output = new JSONObject();
  833.  
  834.                     JSONObject cPerson = dbUser.GetCurrentPerson(ID);
  835.                     JSONObject nPerson = dbUser.GetUserNextPerson(ID);
  836.  
  837.                     String cDate = BitStep.GetDateMySql(Calendar.getInstance());
  838.  
  839.                     dbUser.RemoveAdditions(ID, cDate);
  840.  
  841.                     int coins = dbUser.GetUserCoins(ID)/*, weight = dbUser.GetUserWeight(ID)*/;
  842.  
  843.                     //String gender = dbUser.GetUserField(ID, "gender");
  844.  
  845.                     JSONObject last = dbUser.GetLastUserRow(ID);
  846.                     last.remove("id");
  847.  
  848.                     if(!last.isEmpty()) {
  849.  
  850.                         for (Object date : data.keySet()) {
  851.  
  852.                             int maxsteps = cPerson.getInt("maxcoin")*BitStep.USER_STEPS_ONE_COIN;
  853.  
  854.                             JSONArray aDate = (JSONArray) data.get(date);
  855.  
  856.                             JSONArray toOut = new JSONArray();
  857.  
  858.                             int dCoins = dbUser.GetUserCoinsOnDay(ID, date.toString());
  859.  
  860.                             if(coins > 0) {
  861.                                 coins -= dCoins;
  862.                             }
  863.  
  864.                             int tCoins=0;
  865.  
  866.                             for (Object day : aDate) {
  867.  
  868.                                 JSONObject oDay = (JSONObject) day;
  869.  
  870.                                 int lSteps = last.getInt("steps");
  871.                                 int steps = oDay.getInt("steps");
  872.  
  873.                                 last.replace("coin", CountCoins(steps, maxsteps));
  874.  
  875.                                 last.replace("date", date);
  876.                                 last.replace("time", oDay.getString("time"));
  877.                                 last.replace("steps", steps);
  878.                                 last.replace("calories", oDay.getInt("calories"));
  879.  
  880.                                 last.replace("complete", Complete(steps, (nPerson.getInt("steps")/nPerson.getInt("days"))));
  881.  
  882.                                 /*System.out.println("last - "+last.toJSONString());
  883.                                 System.out.println("coin - "+coins+" lSteps - "+lSteps+" steps - "+steps+"\n");*/
  884.  
  885.                                 LOGGER.info("last - "+last.toJSONString());
  886.                                 LOGGER.info("coin - "+coins+" lSteps - "+lSteps+" steps - "+steps);
  887.  
  888.                                 JSONObject row = dbUser.GetUserRowByDateTime(ID, date.toString(), oDay.getString("time"));
  889.  
  890.                                 LOGGER.info("Existing row - "+row.toJSONString());
  891.                                 //System.out.println("Existing row - "+row.toJSONString());
  892.  
  893.                                 if(row.isEmpty()) {
  894.                                     LOGGER.info("Add row");
  895.                                     //System.out.println("Add row");
  896.                                     if(dbUser.AddAdditions(ID, last)) {
  897.                                         toOut.add(last.clone());
  898.                                     }
  899.                                 } else {
  900.                                     LOGGER.info("Update row");
  901.                                     //System.out.println("Update row");
  902.                                     if(dbUser.UpdateUserRow(ID, row.getInt("id"), last)){
  903.                                         toOut.add(last.clone());
  904.                                     }
  905.                                 }
  906.  
  907.                                 tCoins = last.getInt("coin");
  908.  
  909.                             }
  910.  
  911.                             coins+=tCoins;
  912.  
  913.                             if(CheckPerson(cPerson, nPerson)) {
  914.                                 //System.out.println("next person");
  915.                                 cPerson = dbUser.GetCurrentPerson(ID);
  916.                                 nPerson = dbUser.GetUserNextPerson(ID);
  917.                                 result.put("person", cPerson.getInt("id"));
  918.                                 last.replace("person_id", dbUser.GetUserPersonID(ID));
  919.                             } else {
  920.                                 //System.err.println("Conditions, for new person, do not fit\n");
  921.                                 LOGGER.error("Conditions, for new person, do not fit");
  922.                             }
  923.  
  924.                             output.put(date, toOut);
  925.  
  926.                         }
  927.                         if(dbUser.SetUserCoins(ID, coins)) {
  928.                             result.put(BitStep.TYPE_STATUS, BitStep.TYPE_SUCCESS);
  929.                             result.put("formatted", output);
  930.                             result.put("coins", coins);
  931.                             result.put("weekends", dbUser.GetUserWeekends(ID));
  932.                             result.put("tcoins", dbUser.GetUserCoinOnDate(ID, BitStep.GetDateMySql(Calendar.getInstance())));
  933.                             //result.replace("person", dbUser.GetUserPersonData(result.getInt("person")));
  934.  
  935.                             result.put("cPerson", cPerson);
  936.                             result.put("nPerson", nPerson);
  937.  
  938.                             ShopGetUserProducts();
  939.                         } else {
  940.                             Error();
  941.                         }
  942.                     } else {
  943.                         Error();
  944.                     }
  945.                 } else {
  946.                     Parameters();
  947.                 }
  948.                 LOGGER.error("Execute end - Add steps");
  949.                 //System.out.println("execute end - Add steps");
  950.             } else {
  951.                 Authentication();
  952.             }
  953.         } else {
  954.             Error();
  955.         }
  956.     }
  957.  
  958.     private void UpdateSteps() throws Exception {
  959.         if (MOBILE) {
  960.             if (AUTH) {
  961.  
  962.                 JSONObject data = UTILS.getParamJSONObject("data");
  963.  
  964.                 LOGGER.info("USERID - "+ID);
  965.                 LOGGER.info(data.toJSONString());
  966.                 //System.out.println(data.toString());
  967.  
  968.                 if (!data.isEmpty()) {
  969.  
  970.                     boolean exist = true;
  971.  
  972.                     int coins = dbUser.GetUserCoins(ID);
  973.  
  974.                     JSONObject cPerson = dbUser.GetCurrentPerson(ID);
  975.                     JSONObject nPerson = dbUser.GetUserNextPerson(ID);
  976.  
  977.                     JSONObject cDate = dbUser.GetUserRowByDateTime(ID, data.getString("date"), data.getString("time"));
  978.  
  979.                     if (cDate.isEmpty()) {
  980.                         LOGGER.info("Row not found. Get last row");
  981.                         exist = false;
  982.                         cDate = dbUser.GetLastUserRow(ID);
  983.                     }
  984.  
  985.                     coins -= cDate.getInt("coin");
  986.  
  987.                     int row_id = cDate.getInt("id");
  988.                     cDate.remove("id");
  989.  
  990.                     for (Object o : data.keySet()) {
  991.                         cDate.replace(o, data.get(o));
  992.                     }
  993.  
  994.                     cDate.replace("coin", CountCoins(data.getInt("steps"), cPerson.getInt("maxcoin") * BitStep.USER_STEPS_ONE_COIN));
  995.  
  996.                     coins += cDate.getInt("coin");
  997.  
  998.                     cDate.replace("complete", Complete(data.getInt("steps"), (nPerson.getInt("steps") / nPerson.getInt("days"))));
  999.  
  1000.                     cDate.replace("calories", data.getInt("calories"));
  1001.  
  1002.                     if (exist?dbUser.UpdateUserRow(ID, row_id, cDate):dbUser.AddAdditions(ID, cDate)) {
  1003.                         if (dbUser.SetUserCoins(ID, coins)) {
  1004.                             result.put(BitStep.TYPE_STATUS, BitStep.TYPE_SUCCESS);
  1005.                             result.put("coins", coins);
  1006.                             result.put("formatted", cDate);
  1007.                             result.put("weekends", dbUser.GetUserWeekends(ID));
  1008.                             result.put("tcoins", dbUser.GetUserCoinOnDate(ID, BitStep.GetDateMySql(Calendar.getInstance())));
  1009.  
  1010.                             CheckPerson(cPerson, nPerson);
  1011.  
  1012.                             ShopGetUserProducts();
  1013.  
  1014.                             result.put("cPerson", cPerson);
  1015.                             result.put("nPerson", nPerson);
  1016.  
  1017.                         } else {
  1018.                             Error();
  1019.                         }
  1020.                     } else {
  1021.                         Error();
  1022.                     }
  1023.                     /*} else {
  1024.                         Error("Row not found");
  1025.                     }*/
  1026.                 } else {
  1027.                     Error();
  1028.                 }
  1029.             } else {
  1030.                 Authentication();
  1031.             }
  1032.         } else {
  1033.             Error();
  1034.         }
  1035.     }
  1036.  
  1037.     private void ShopBuy() {
  1038.         if(AUTH) {
  1039.  
  1040.         } else {
  1041.             Authentication();
  1042.         }
  1043.     }
  1044.  
  1045.     /*private void ShopGetAllProducts() throws Exception {
  1046.         if(AUTH) {
  1047.             result.put("products", dbShop.GetAllClothList(dbUser.GetUserGender(ID)));
  1048.             GetProductsImages((JSONArray) result.get("products"));
  1049.         } else {
  1050.             Authentication();
  1051.         }
  1052.     }*/
  1053.  
  1054.     private void ShopGetUserProducts() throws Exception {
  1055.         if(AUTH) {
  1056.             result.put("person", dbUser.GetUserPersonID(ID));
  1057.             result.put("clothes", dbShop.GetUserList(ID));
  1058.             GetProductsImages((JSONArray) result.get("clothes"));
  1059.         } else {
  1060.             Authentication();
  1061.         }
  1062.     }
  1063.  
  1064.     private void ShopGetClothProducts() throws Exception {
  1065.         if(isAuth()) {
  1066.             result.put("products", dbShop.GetAllClothList(/*dbUser.GetUserGender(ID))*/));
  1067.             GetProductsImages((JSONArray) result.get("products"));
  1068.         } else {
  1069.             Authentication();
  1070.         }
  1071.     }
  1072.  
  1073.     private void ShopGetPersonProducts() throws Exception {
  1074.         if(isAuth()) {
  1075.             result.put("products", dbShop.GetAllPersonList());
  1076.         } else {
  1077.             Authentication();
  1078.         }
  1079.     }
  1080.  
  1081.     private void ShopGetWeekendsProducts() throws Exception {
  1082.         if(isAuth()) {
  1083.             result.put("products", dbShop.GetAllPersonList());
  1084.         } else {
  1085.             Authentication();
  1086.         }
  1087.     }
  1088.  
  1089.     private void ShopGetCoinsProducts() throws Exception {
  1090.         if(isAuth()) {
  1091.             result.put("products", dbShop.GetAllPersonList());
  1092.         } else {
  1093.             Authentication();
  1094.         }
  1095.     }
  1096.  
  1097.     private void ShopGetVipProduct() throws Exception {
  1098.         if(isAuth()) {
  1099.             result.put("products", dbShop.GetAllPersonList());
  1100.         } else {
  1101.             Authentication();
  1102.         }
  1103.     }
  1104.  
  1105.     private void ShopBuyCloth() throws SQLException {
  1106.         if(isAuth()) {
  1107.  
  1108.             int CLOTHID = UTILS.getParamInt("id");
  1109.  
  1110.             if(CLOTHID > 0) {
  1111.                 JSONObject product = dbShop.GetClothData(CLOTHID);
  1112.                 if(!product.isEmpty()) {
  1113.                     if(!dbShop.CheckClothIsBought(ID, CLOTHID)) {
  1114.                         int orderid = dbShop.AddOrder(ID, CLOTHID, "cloth", "Покупка вещи");
  1115.                         if(orderid > 0) {
  1116.                             HashMap params = new HashMap();
  1117.                             params.put("action", "pay");
  1118.                             params.put("amount", product.getInt("price"));
  1119.                             params.put("currency", BitStep.SHOP_CURRENCY);
  1120.                             params.put("language", "ru");
  1121.                             params.put("sandbox", "1");
  1122.                             params.put("server_url", UTILS.getDomain()+"/liqpay");
  1123.                             params.put("description", "Покупка товара "+product.getString("label"));
  1124.                             params.put("order_id", orderid);
  1125.                             params.put("version", "3");
  1126.  
  1127.                             params.put("sender_first_name", dbUser.GetUserField(ID, "firstname"));
  1128.                             params.put("sender_last_name", dbUser.GetUserField(ID, "lastname"));
  1129.  
  1130.                             params.put("product_name", product.getString("label"));
  1131.                             params.put("customer", ID);
  1132.  
  1133.                             LiqPay liqpay = new LiqPay(BitStep.SHOP_PUBLIC_KEY, BitStep.SHOP_PRIVATE_KEY);
  1134.  
  1135.                             result.put("html", liqpay.cnb_form(params));
  1136.                         } else {
  1137.                             Error();
  1138.                         }
  1139.                     } else {
  1140.                         Error("Вещь уже куплена.");
  1141.                     }
  1142.                 } else {
  1143.                     Parameters();
  1144.                 }
  1145.             } else {
  1146.                 Error();
  1147.             }
  1148.         } else {
  1149.             Authentication();
  1150.         }
  1151.     }
  1152.  
  1153.     private void ShopBuyPerson() throws SQLException {
  1154.         if(isAuth()) {
  1155.  
  1156.             int PRODUCTID = UTILS.getParamInt("id");
  1157.  
  1158.             if(PRODUCTID>0) {
  1159.                 JSONObject product = dbShop.GetPersonData(PRODUCTID);
  1160.                 if(!product.isEmpty()) {
  1161.  
  1162.                     boolean access = true;
  1163.  
  1164.                     if(product.getString("name").equals("vip")) {
  1165.                         if(dbUser.UserIsVip(ID)) {
  1166.                             access = false;
  1167.                         }
  1168.                     }
  1169.  
  1170.                     if(access) {
  1171.                         int orderid = dbShop.AddOrder(ID, PRODUCTID, "person", ("Покупка "+product.getString("label")));
  1172.  
  1173.                         if(orderid > 0) {
  1174.                             HashMap params = new HashMap();
  1175.                             params.put("action", "pay");
  1176.                             params.put("amount", product.getInt("price"));
  1177.                             params.put("currency", BitStep.SHOP_CURRENCY);
  1178.                             params.put("language", "ru");
  1179.                             params.put("sandbox", "1");
  1180.                             params.put("server_url", UTILS.getDomain()+"/liqpay");
  1181.                             params.put("description", "Покупка товара "+product.getString("label")+". Количество "+product.getInt("count"));
  1182.                             params.put("order_id", orderid);
  1183.                             params.put("version", "3");
  1184.  
  1185.                             params.put("sender_first_name", dbUser.GetUserField(ID, "firstname"));
  1186.                             params.put("sender_last_name", dbUser.GetUserField(ID, "lastname"));
  1187.  
  1188.                             params.put("product_name", product.getString("label"));
  1189.                             params.put("customer", ID);
  1190.  
  1191.                             LiqPay liqpay = new LiqPay(BitStep.SHOP_PUBLIC_KEY, BitStep.SHOP_PRIVATE_KEY);
  1192.  
  1193.                             result.put("html", liqpay.cnb_form(params));
  1194.                         } else {
  1195.                             Error();
  1196.                         }
  1197.                     } else {
  1198.                         Error("Пользователь уже имеет статус vip");
  1199.                     }
  1200.                 } else {
  1201.                     Error();
  1202.                 }
  1203.             } else {
  1204.                 Error();
  1205.             }
  1206.         } else {
  1207.             Authentication();
  1208.         }
  1209.     }
  1210.  
  1211.     private void GetPartners() throws Exception {
  1212.         if(isAuth()) {
  1213.             JSONArray parners = dbUser.GetAllPartners();
  1214.  
  1215.             for(Object p: parners) {
  1216.                 JSONObject partner = (JSONObject) p;
  1217.  
  1218.                 String name = partner.getString("company");
  1219.  
  1220.                 if(!name.isEmpty()) {
  1221.  
  1222.                     File image = FindFile(new File(UTILS.getRoot()+SEPARATOR+ PARTNERS_DIR+SEPARATOR), name);
  1223.  
  1224.                     if(image!=null) {
  1225.                         partner.replace("company", UTILS.getLocalIp()+SEPARATOR+ PARTNERS_DIR+SEPARATOR+image.getName());
  1226.                     }
  1227.                 }
  1228.  
  1229.             }
  1230.  
  1231.             result.put("partners", parners);
  1232.  
  1233.         } else {
  1234.             Error();
  1235.         }
  1236.     }
  1237.  
  1238.     private void GetWeb() throws Exception {
  1239.         if(isAuth()) {
  1240.  
  1241.             int GENDER = dbUser.GetUserGender(ID);
  1242.  
  1243.             GetWebPerson(GENDER);
  1244.  
  1245.             result.put("coins", dbUser.GetUserCoins(ID));
  1246.  
  1247.             result.put("tCoins", dbUser.GetUserCoinOnDate(ID, BitStep.GetDateMySql(Calendar.getInstance())));
  1248.  
  1249.             GetWebDateData(BitStep.GetDateMySql(Calendar.getInstance()));
  1250.  
  1251.             String path = SEPARATOR+PERSON_DIR+SEPARATOR+((JSONObject)result.get("person")).getInt("id")+SEPARATOR+PARTNERS_DIR+SEPARATOR+GENDER;
  1252.  
  1253.             JSONArray partners = new JSONArray();
  1254.             File pFiels = new File(UTILS.getRoot()+path);
  1255.  
  1256.             if(pFiels.exists()&&pFiels.isDirectory()) {
  1257.                 for(File p: pFiels.listFiles()) {
  1258.                     partners.add(path+SEPARATOR+p.getName());
  1259.                 }
  1260.             }
  1261.  
  1262.             result.put("pPartners", partners);
  1263.             GetPartners();
  1264.  
  1265.             GetResults();
  1266.  
  1267.         } else {
  1268.             Authentication();
  1269.         }
  1270.     }
  1271.  
  1272.     private void GetResults() throws Exception {
  1273.         if(isAuth()) {
  1274.  
  1275.             result.put("wins", 0);
  1276.             result.put("wUsed", dbUser.GetUserUsedWeekends(ID));
  1277.  
  1278.             JSONArray dates = dbUser.GetUserDates(ID);
  1279.  
  1280.             SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
  1281.  
  1282.             Calendar calendar = Calendar.getInstance();
  1283.             calendar.setTime(simpleDateFormat.parse(dates.get(0).toString()));
  1284.  
  1285.             int count = 0;
  1286.  
  1287.             for (int i=1; i<dates.size(); i++) {
  1288.                 calendar.add(Calendar.DATE, -1);
  1289.                 String currentDate = simpleDateFormat.format(calendar.getTime());
  1290.                 //System.out.println(currentDate+" -> "+dates.get(i));
  1291.                 if (currentDate.equals(dates.get(i))) {
  1292.                     count++;
  1293.                 }
  1294.             }
  1295.  
  1296.             result.put("days", count);
  1297.  
  1298.             CheckAchievements();
  1299.  
  1300.             result.put("achievements", dbUser.GetAchievements(ID));
  1301.  
  1302.             if(!MOBILE) {
  1303.  
  1304.                 SimpleDateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd");
  1305.  
  1306.                 Calendar c = Calendar.getInstance();
  1307.  
  1308.                 String start = dFormat.format(c.getTime());
  1309.  
  1310.                 c.add(Calendar.DATE, -6);
  1311.  
  1312.                 dates = dbUser.GetMiddleTableData(ID, start, dFormat.format(c.getTime()));
  1313.  
  1314.                 int mSteps=0, mCalories=0, mCoins=0;
  1315.  
  1316.                 for(Object d: dates) {
  1317.                     JSONObject date = (JSONObject) d;
  1318.                     mSteps+=date.getInt("steps");
  1319.                     mCalories+=date.getInt("calories");
  1320.                     mCoins+=date.getInt("coin");
  1321.                 }
  1322.  
  1323.                 //result.put("data", dates);
  1324.  
  1325.                 result.put("mSteps", dates.size() > 0 ?(mSteps/dates.size()): 0);
  1326.                 result.put("mCalories", dates.size() > 0 ?(mCalories/dates.size()): 0);
  1327.                 result.put("mCoins", dates.size() > 0 ?(mCoins/dates.size()): 0);
  1328.             }
  1329.         } else {
  1330.             Authentication();
  1331.         }
  1332.     }
  1333.  
  1334.     /* STATIC METHODS */
  1335.  
  1336.     private void CheckAchievements() throws Exception {
  1337.  
  1338.         JSONArray all = dbUser.GetAllAchievements();
  1339.  
  1340.         if(!all.isEmpty()) {
  1341.             boolean set = false;
  1342.             int steps = dbUser.GetUserAllCountSteps(ID);
  1343.  
  1344.             for(Object a: all) {
  1345.                 JSONObject ach = (JSONObject) a;
  1346.  
  1347.                 if(ach.getString("type").equals("s")) {
  1348.                     if(steps>=ach.getInt("value")&&!set) {
  1349.                         set=true;
  1350.                         dbUser.SetUserAchievement(ID, ach.getString("type"), ach.getInt("id"));
  1351.                     }
  1352.                 }
  1353.  
  1354.             }
  1355.  
  1356.         }
  1357.  
  1358.     }
  1359.  
  1360.     private void UserUpdateDeviceAndPush(int USERID) throws Exception {
  1361.         String device = UTILS.getHeaderString("user-agent");
  1362.         //System.out.println("Headers - "+UTILS.getHeaders().toJSONString());
  1363.         if(device.contains("iOS")) {
  1364.             device = "iOS";
  1365.         } else if(device.contains("Android")){
  1366.             device = "Android";
  1367.         }
  1368.  
  1369.         dbUser.UserUpdateDeviceAndPush(USERID, device, UTILS.getParamString("push"));
  1370.     }
  1371.  
  1372.     private void GetWebPerson(int GENDER) throws SQLException {
  1373.         JSONObject person = dbUser.GetUserPersonData(dbUser.GetUserPersonID(ID));
  1374.  
  1375.         result.put("person", person);
  1376.         result.put("pImage", SEPARATOR+PERSON_DIR+SEPARATOR+person.getInt("id")+SEPARATOR+GENDER+SEPARATOR+"person.png");
  1377.     }
  1378.  
  1379.     private void GetWebDateData(String DATE) throws SQLException {
  1380.         JSONArray dataOnDate = dbUser.GetUserTableDataOnDate(ID, DATE);
  1381.  
  1382.         JSONObject gSteps = new JSONObject();
  1383.         JSONObject gCalories = new JSONObject();
  1384.         JSONObject gCoins = new JSONObject();
  1385.  
  1386.         for(Object d: dataOnDate) {
  1387.             JSONObject date = (JSONObject) d;
  1388.             gSteps.put(date.getString("time"), date.getString("steps"));
  1389.             gCalories.put(date.getString("time"), date.getString("calories"));
  1390.             gCoins.put(date.getString("time"), date.getString("coin"));
  1391.         }
  1392.  
  1393.         result.put("gSteps", gSteps);
  1394.         result.put("gCalories", gCalories);
  1395.         result.put("gCoins", gCoins);
  1396.  
  1397.         JSONObject lastOnDate = new JSONObject();
  1398.  
  1399.         if(dataOnDate.size() > 0) {
  1400.             lastOnDate = (JSONObject) dataOnDate.get(dataOnDate.size()-1);
  1401.         }
  1402.  
  1403.         JSONObject circle = new JSONObject();
  1404.  
  1405.         circle.put("steps", !lastOnDate.isEmpty() ? lastOnDate.getInt("steps"):0);
  1406.         circle.put("calories", !lastOnDate.isEmpty() ? lastOnDate.getInt("calories"):0);
  1407.         circle.put("coin", !lastOnDate.isEmpty() ? lastOnDate.getInt("coin"):0);
  1408.  
  1409.         result.put("circle", circle);
  1410.  
  1411.         GetWebPerson(dbUser.GetUserGender(ID));
  1412.  
  1413.     }
  1414.  
  1415.     private JSONObject CheckAuthData(JSONObject data, boolean fb) {
  1416.  
  1417.         JSONObject errors = new JSONObject();
  1418.  
  1419.         String e = data.getString("email");
  1420.         String p = data.getString("password");
  1421.  
  1422.         if (e == null || e.isEmpty()) {
  1423.             errors.put("email", "Поле не может быть пустым");
  1424.         }
  1425.  
  1426.         if(!fb) {
  1427.             if (p == null || p.isEmpty()) {
  1428.                 errors.put("password", "Поле не может быть пустым");
  1429.             }
  1430.         }
  1431.  
  1432.         if (errors.isEmpty()) {
  1433.             if (!e.matches(BitStep.EMAIL_REGEXP) || (!fb&&!p.matches(BitStep.PASSWORD_REGEXP))) {
  1434.                 errors.put("error", "E-Mail или пароль неверны");
  1435.             }
  1436.         }
  1437.  
  1438.         if(!errors.isEmpty()) {
  1439.             data.put(BitStep.TYPE_TEXT_ERROR, errors);
  1440.         }
  1441.  
  1442.         return data;
  1443.  
  1444.     }
  1445.  
  1446.     private JSONObject CheckRegisterData(JSONObject data, boolean fb) {
  1447.  
  1448.         JSONObject error = new JSONObject();
  1449.  
  1450.         String email = data.getString("email");
  1451.         String p1 = data.getString("p1");
  1452.         String p2 = data.getString("p2");
  1453.  
  1454.         if (!data.containsKey("firstname") || data.getString("firstname").isEmpty()) {
  1455.             error.put("firstname", "Поле не может быть пустым");
  1456.         }
  1457.  
  1458.         if (!data.containsKey("lastname") || data.getString("lastname").isEmpty()) {
  1459.             error.put("lastname", "Поле не может быть пустым");
  1460.         }
  1461.  
  1462.         if (email == null || email.isEmpty()) {
  1463.             error.put("email", "Поле не может быть пустым");
  1464.         }
  1465.  
  1466.         if(!fb) {
  1467.             if (p1 == null || p1.isEmpty()) {
  1468.                 error.put("p1", "Поле не может быть пустым");
  1469.             }
  1470.  
  1471.             if (p2 == null || p2.isEmpty()) {
  1472.                 error.put("p2", "Поле не может быть пустым");
  1473.             }
  1474.         }
  1475.  
  1476.         if (error.isEmpty()) {
  1477.             if (!email.matches(BitStep.EMAIL_REGEXP)) {
  1478.                 error.put("email", "Пожалуйста, введите корректный Email");
  1479.             }
  1480.             if(!fb) {
  1481.                 if (!p1.matches(BitStep.PASSWORD_REGEXP)) {
  1482.                     error.put("p1", "Пароль не соотвецтвует требованиям");
  1483.                 }
  1484.  
  1485.                 if (!p2.equals(p1)) {
  1486.                     error.put("p2", "Пароли не совпадают");
  1487.                 }
  1488.             }
  1489.         }
  1490.  
  1491.         if(!data.containsKey("gender") || data.getString("gender").isEmpty()) {
  1492.             error.put("gender", "Пол не задан");
  1493.         }
  1494.  
  1495.         if(!error.isEmpty()) {
  1496.             data.put(BitStep.TYPE_TEXT_ERROR, error);
  1497.         }
  1498.         return data;
  1499.     }
  1500.  
  1501.     private JSONObject CheckAddition(JSONObject data, int gender) {
  1502.  
  1503.         if(data.containsKey("weight") && data.containsKey("growth")) {
  1504.             if(data.getInt("weight") <= 0) {
  1505.                 if(gender==1) {
  1506.                     data.replace("weight", BitStep.DEFAULT_USER_WEIGHT_MALE);
  1507.                 } else if(gender==2) {
  1508.                     data.replace("weight", BitStep.DEFAULT_USER_WEIGHT_FEMALE);
  1509.                 }
  1510.             }
  1511.  
  1512.             if(data.getInt("growth") <= 0) {
  1513.                 if(gender==1) {
  1514.                     data.replace("growth", BitStep.DEFAULT_USER_GROWTH_MALE);
  1515.                 } else if(gender==2) {
  1516.                     data.replace("growth", BitStep.DEFAULT_USER_GROWTH_FEMALE);
  1517.                 }
  1518.             }
  1519.         }
  1520.  
  1521.         /*String[] time = ;
  1522.  
  1523.         if(Integer.parseInt(time[1])<=30) {
  1524.             time[1] = "00";
  1525.         } else if(Integer.parseInt(time[1])>30) {
  1526.             int i = Integer.parseInt(time[0]);
  1527.             time[0] = String.valueOf(++i);
  1528.             time[1] = "00";
  1529.         }*/
  1530.  
  1531.         data.replace("time", data.getString("time").split(":")[0]+":00:00");
  1532.  
  1533.         return data;
  1534.     }
  1535.  
  1536.     private JSONObject GetEmptyAdditions(int gender) {
  1537.         JSONObject additions = new JSONObject();
  1538.  
  1539.         additions.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
  1540.         additions.put("time", new SimpleDateFormat("HH:mm:ss").format(new Date()));
  1541.         additions.put("calories", 0);
  1542.         additions.put("steps", 0);
  1543.         additions.put("coin", 0);
  1544.         additions.put("visited", 0);
  1545.         additions.put("complete", 0);
  1546.         additions.put("weekend", 0);
  1547.  
  1548.         additions = CheckAddition(additions, gender);
  1549.  
  1550.         return additions;
  1551.     }
  1552.  
  1553.     private int CountCoins(int steps, int maxsteps) {
  1554.         return steps <= maxsteps?Math.round(steps/2000):0;
  1555.     }
  1556.  
  1557.     private int Complete(int steps, int dSteps) {
  1558.         return steps >= dSteps?1:0;
  1559.     }
  1560.  
  1561.     private boolean CheckPerson(JSONObject cPerson, JSONObject nPerson) throws Exception {
  1562.         //System.out.println();
  1563.         LOGGER.info("Start Check Person");
  1564.         boolean status = false;
  1565.  
  1566.         JSONArray dates = dbUser.GetUserPersonDates(ID, cPerson.getInt("id"));
  1567.  
  1568.         if(!dates.isEmpty()) {
  1569.             LOGGER.info("Available dates - "+dates.toJSONString());
  1570.             //System.out.println("Available dates - "+dates.toJSONString());
  1571.             if(dates.size() >= nPerson.getInt("days")) {
  1572.                 if(DatesSequence(dates, nPerson.getInt("days"))) {
  1573.                     status = dbUser.SetUserPerson(ID, nPerson.getInt("id"));
  1574.                     if(status) {
  1575.                         LOGGER.info("User, ID - " + ID + " has new person - " + nPerson.getInt("id"));
  1576.                         //System.out.println();
  1577.                     }
  1578.                 } else {
  1579.                     LOGGER.info("Empty");
  1580.                     //System.out.println();
  1581.                 }
  1582.             } else {
  1583.                 LOGGER.info("Empty");
  1584.                 //System.out.println("Empty");
  1585.             }
  1586.         } else {
  1587.             LOGGER.info("Empty");
  1588.             //System.out.println();
  1589.         }
  1590.         LOGGER.info("End Check Person");
  1591.         //System.out.println();
  1592.         return status;
  1593.     }
  1594.  
  1595.     private boolean DatesSequence(JSONArray dates, int count) throws Exception {
  1596.  
  1597.         int complete = 1;
  1598.  
  1599.         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
  1600.  
  1601.         Calendar calendar = Calendar.getInstance();
  1602.         calendar.setTime(simpleDateFormat.parse(dates.get(0).toString()));
  1603.  
  1604.         for (int i=1; i<dates.size(); i++) {
  1605.             calendar.add(Calendar.DATE, -1);
  1606.             String currentDate = simpleDateFormat.format(calendar.getTime());
  1607.             LOGGER.info(currentDate+" -> "+dates.get(i));
  1608.             if (currentDate.equals(dates.get(i))) {
  1609.                 complete++;
  1610.                 LOGGER.info("++ " + complete);
  1611.             } else {
  1612.                 LOGGER.info("BREAK");
  1613.                 break;
  1614.             }
  1615.         }
  1616.         LOGGER.info("COMPLETE COUNT - "+complete+" COUNT - "+count);
  1617.         return complete >=count;
  1618.     }
  1619.  
  1620.     private void GetProductsImages(JSONArray products) throws SQLException {
  1621.         int pid = dbUser.GetUserPersonID(ID);
  1622.         int gender = dbUser.GetUserGender(ID);
  1623.         for(Object c: products) {
  1624.             JSONObject product = (JSONObject) c;
  1625.             int id = product.getInt("id");
  1626.             String path = PERSON_DIR+SEPARATOR+pid+SEPARATOR+gender+SEPARATOR;
  1627.             File image = FindFile(new File(UTILS.getRoot()+path), String.valueOf(id));
  1628.             if(image!=null&&image.exists()) {
  1629.                 product.put("image", path+image.getName());
  1630.             } else {
  1631.                 product.put("image", "");
  1632.             }
  1633.  
  1634.         }
  1635.     }
  1636.  
  1637.     private File FindFile(File dir, String name) {
  1638.         File[] list = dir.listFiles();
  1639.         if (list != null) {
  1640.             for (File f : list) {
  1641.                 if (f.isFile() && GetFileName(f).equals(name)) {
  1642.                     return f;
  1643.                 }
  1644.             }
  1645.         }
  1646.         return null;
  1647.     }
  1648.  
  1649.     private String GetFileName(File file) {
  1650.         return file.getName().substring(0, file.getName().lastIndexOf("."));
  1651.     }
  1652.  
  1653.     private String GetFileExt(File file) {
  1654.         return file.getName().substring(file.getName().indexOf("."), file.getName().length());
  1655.     }
  1656.  
  1657.     private JSONObject ConvertTableDataToObject(JSONArray input) {
  1658.         JSONObject data = new JSONObject();
  1659.         for(Object o: input) {
  1660.             JSONObject obj = (JSONObject) o;
  1661.             Object date = obj.get("date");
  1662.             if(!data.containsKey(date)) {
  1663.                 data.put(date, new JSONArray());
  1664.             }
  1665.             JSONArray arr = (JSONArray) data.get(date);
  1666.             arr.add(obj);
  1667.         }
  1668.         return data;
  1669.     }
  1670.  
  1671. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement