Advertisement
Guest User

VkServiceImpl

a guest
Nov 11th, 2018
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 32.81 KB | None | 0 0
  1. package com.ewp.crm.service.impl;
  2.  
  3. import com.ewp.crm.configs.inteface.VKConfig;
  4. import com.ewp.crm.exceptions.parse.ParseClientException;
  5. import com.ewp.crm.exceptions.util.VKAccessTokenException;
  6. import com.ewp.crm.models.*;
  7. import com.ewp.crm.models.Client.Sex;
  8. import com.ewp.crm.service.interfaces.*;
  9. import com.ewp.crm.service.interfaces.VKService;
  10. import com.github.scribejava.apis.VkontakteApi;
  11. import com.github.scribejava.core.builder.ServiceBuilder;
  12. import com.github.scribejava.core.model.OAuth2AccessToken;
  13. import com.github.scribejava.core.model.OAuthRequest;
  14. import com.github.scribejava.core.model.Response;
  15. import com.github.scribejava.core.model.Verb;
  16. import com.github.scribejava.core.oauth.OAuth20Service;
  17. import org.apache.http.HttpResponse;
  18. import org.apache.http.client.HttpClient;
  19. import org.apache.http.client.config.CookieSpecs;
  20. import org.apache.http.client.config.RequestConfig;
  21. import org.apache.http.client.methods.HttpGet;
  22. import org.apache.http.impl.client.DefaultHttpClient;
  23. import org.apache.http.impl.client.HttpClients;
  24. import org.apache.http.util.EntityUtils;
  25. import org.json.JSONArray;
  26. import org.json.JSONException;
  27. import org.json.JSONObject;
  28. import org.slf4j.Logger;
  29. import org.slf4j.LoggerFactory;
  30. import org.springframework.beans.factory.annotation.Autowired;
  31. import org.springframework.stereotype.Component;
  32.  
  33. import javax.annotation.PostConstruct;
  34. import java.io.IOException;
  35. import java.util.*;
  36.  
  37. @Component
  38. public class VKServiceImpl implements VKService {
  39.     private static Logger logger = LoggerFactory.getLogger(VKService.class);
  40.     private final YoutubeClientService youtubeClientService;
  41.     private final SocialProfileService socialProfileService;
  42.     private final ClientHistoryService clientHistoryService;
  43.     private final ClientService clientService;
  44.     private final MessageService messageService;
  45.     private final SocialProfileTypeService socialProfileTypeService;
  46.     private final UserService userService;
  47.     private final MessageTemplateService messageTemplateService;
  48.     private final ProjectPropertiesService projectPropertiesService;
  49.     private final VkRequestFormService vkRequestFormService;
  50.  
  51.     private String vkAPI;
  52.     //Токен аккаунта, отправляющего сообщения
  53.     private String robotAccessToken;
  54.     //Айди группы
  55.     private String clubId;
  56.     //Версия API ВК
  57.     private String version;
  58.     //Токен доступа от имени сообщества
  59.     private String communityToken;
  60.     //Айди приложения (Может изменяться на релизе)
  61.     private String applicationId;
  62.     private String display;
  63.     //URL, на который приходит
  64.     private String redirectUri;
  65.     private String scope;
  66.     private String technicalAccountToken;
  67.     private OAuth20Service service;
  68.     private String robotClientSecret;
  69.     private String robotClientId;
  70.     private String robotUsername;
  71.     private String robotPassword;
  72.     private String firstContactMessage;
  73.  
  74.     @Autowired
  75.     public VKServiceImpl(VKConfig vkConfig, YoutubeClientService youtubeClientService, SocialProfileService socialProfileService, ClientHistoryService clientHistoryService, ClientService clientService, MessageService messageService, SocialProfileTypeService socialProfileTypeService, UserService userService, MessageTemplateService messageTemplateService, ProjectPropertiesService projectPropertiesService, VkRequestFormService vkRequestFormService) {
  76.         clubId = vkConfig.getClubIdWithMinus();
  77.         version = vkConfig.getVersion();
  78.         communityToken = vkConfig.getCommunityToken();
  79.         applicationId = vkConfig.getApplicationId();
  80.         display = vkConfig.getDisplay();
  81.         redirectUri = vkConfig.getRedirectUri();
  82.         scope = vkConfig.getScope();
  83.         vkAPI = vkConfig.getVkAPIUrl();
  84.         this.youtubeClientService = youtubeClientService;
  85.         this.socialProfileService = socialProfileService;
  86.         this.clientHistoryService = clientHistoryService;
  87.         this.clientService = clientService;
  88.         this.messageService = messageService;
  89.         this.socialProfileTypeService = socialProfileTypeService;
  90.         this.userService = userService;
  91.         this.messageTemplateService = messageTemplateService;
  92.         this.projectPropertiesService = projectPropertiesService;
  93.         this.vkRequestFormService = vkRequestFormService;
  94.         this.service = new ServiceBuilder(clubId).build(VkontakteApi.instance());
  95.         this.robotClientSecret = vkConfig.getRobotClientSecret();
  96.         this.robotClientId = vkConfig.getRobotClientId();
  97.         this.robotUsername = vkConfig.getRobotUsername();
  98.         this.robotPassword = vkConfig.getRobotPassword();
  99.         this.firstContactMessage = vkConfig.getFirstContactMessage();
  100.     }
  101.  
  102.     @Override
  103.     public String receivingTokenUri() {
  104.  
  105.         return "https://oauth.vk.com/authorize" +
  106.                 "?client_id=" + applicationId +
  107.                 "&display=" + display +
  108.                 "&redirect_uri=" + redirectUri +
  109.                 "&scope=" + scope +
  110.                 "&response_type=token" +
  111.                 "&v" + version;
  112.     }
  113.  
  114.     @Override
  115.     public Optional<List<String>> getNewMassages() throws VKAccessTokenException {
  116.         logger.info("VKService: getting new messages...");
  117.         if (technicalAccountToken == null && (technicalAccountToken = projectPropertiesService.get() != null ? projectPropertiesService.get().getTechnicalAccountToken() : null) == null) {
  118.             throw new VKAccessTokenException("VK access token has not got");
  119.         }
  120.         String uriGetMassages = vkAPI + "messages.getHistory" +
  121.                 "?user_id=" + clubId +
  122.                 "&rev=0" +
  123.                 "&version=" + version +
  124.                 "&access_token=" + technicalAccountToken;
  125.         try {
  126.             HttpGet httpGetMessages = new HttpGet(uriGetMassages);
  127.             HttpClient httpClient = HttpClients.custom()
  128.                     .setDefaultRequestConfig(RequestConfig.custom()
  129.                             .setCookieSpec(CookieSpecs.STANDARD).build())
  130.                     .build();
  131.             HttpResponse response = httpClient.execute(httpGetMessages);
  132.             String result = EntityUtils.toString(response.getEntity());
  133.             JSONObject json = new JSONObject(result);
  134.             JSONArray jsonMessages = json.getJSONArray("response");
  135.             List<String> resultList = new ArrayList<>();
  136.             for (int i = 1; i < jsonMessages.length(); i++) {
  137.                 JSONObject jsonMessage = jsonMessages.getJSONObject(i);
  138.                 if ((clubId.equals(jsonMessage.getString("uid"))) && (jsonMessage.getInt("read_state") == 0)) {
  139.                     resultList.add(jsonMessage.getString("body"));
  140.                 }
  141.             }
  142.             markAsRead(Long.parseLong(clubId), httpClient, technicalAccountToken);
  143.             return Optional.of(resultList);
  144.         } catch (JSONException e) {
  145.             logger.error("Can not read message from JSON ", e);
  146.         } catch (IOException e) {
  147.             logger.error("Failed to connect to VK server ", e);
  148.         }
  149.         return Optional.empty();
  150.     }
  151.  
  152.     @Override
  153.     public void sendMessageToClient(Long clientId, String templateText, String body, User principal) {
  154.         Client client = clientService.getClientByID(clientId);
  155.         String fullName = client.getName() + " " + client.getLastName();
  156.         Map<String, String> params = new HashMap<>();
  157.         params.put("%fullName%", fullName);
  158.         params.put("%bodyText%", body);
  159.         params.put("%dateOfSkypeCall%", body);
  160.         List<SocialProfile> socialProfiles = client.getSocialProfiles();
  161.         for (SocialProfile socialProfile : socialProfiles) {
  162.             if (socialProfile.getSocialProfileType().getName().equals("vk")) {
  163.                 String link = socialProfile.getLink();
  164.                 Optional<Long> optId = getVKIdByUrl(link);
  165.                 if (optId.isPresent()) {
  166.                     Long id = optId.get();
  167.                     String vkText = replaceName(templateText, params);
  168.                     String token = communityToken;
  169.                     if (principal != null) {
  170.                         User user = userService.get(principal.getId());
  171.                         if (user.getVkToken() != null) {
  172.                             token = user.getVkToken();
  173.                         }
  174.                         Message message = messageService.addMessage(Message.Type.VK, vkText);
  175.                         client.addHistory(clientHistoryService.createHistory(principal, client, message));
  176.                         clientService.updateClient(client);
  177.                     }
  178.                     sendMessageById(id, vkText, token);
  179.                 } else {
  180.                     logger.info("{} has wrong VK url {}", client.getEmail(), link);
  181.                 }
  182.             }
  183.         }
  184.     }
  185.  
  186.     /**
  187.      * Get user VK id by profile url.
  188.      *
  189.      * @param url user profile url.
  190.      * @return optional of user VK id.
  191.      */
  192.     private Optional<Long> getVKIdByUrl(String url) {
  193.         Optional<Long> result = Optional.empty();
  194.         if (url.matches("(.*)://vk.com/id(\\d*)")) {
  195.             result = Optional.of(Long.parseLong(url.replaceAll(".+id", "")));
  196.         } else if (url.matches("(.*)://vk.com/(.*)")) {
  197.             String screenName = url.substring(url.lastIndexOf("/") + 1);
  198.             String urlGetMessages = vkAPI + "users.get" +
  199.                     "?user_ids=" + screenName +
  200.                     "&version=" + version +
  201.                     "&access_token=" + communityToken;
  202.             try {
  203.                 HttpGet httpGetMessages = new HttpGet(urlGetMessages);
  204.                 HttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom()
  205.                         .setCookieSpec(CookieSpecs.STANDARD).build())
  206.                         .build();
  207.                 HttpResponse httpResponse = httpClient.execute(httpGetMessages);
  208.                 String entity = EntityUtils.toString(httpResponse.getEntity());
  209.                 JSONArray users = new JSONObject(entity).getJSONArray("response");
  210.                 result = Optional.of(users.getJSONObject(0).getLong("uid"));
  211.             } catch (IOException e) {
  212.                 logger.error("Failed to connect to VK server", e);
  213.             } catch (JSONException e) {
  214.                 logger.error("Can not read message from JSON", e);
  215.             }
  216.         }
  217.         return result;
  218.     }
  219.  
  220.     /**
  221.      * Send VK notification to client without logging and additional body parameters.
  222.      *
  223.      * @param clientId     recipient client.
  224.      * @param templateText email template text.
  225.      */
  226.     @Override
  227.     public void simpleVKNotification(Long clientId, String templateText) {
  228.         sendMessageToClient(clientId, templateText, "", null);
  229.     }
  230.  
  231.     @Override
  232.     public Optional<ArrayList<VkMember>> getAllVKMembers(Long groupId, Long offset) {
  233.         logger.info("VKService: getting all VK members...");
  234.         if (groupId == null) {
  235.             groupId = Long.parseLong(clubId) * (-1);
  236.         }
  237.         String urlGetMessages = vkAPI + "groups.getMembers" +
  238.                 "?group_id=" + groupId +
  239.                 "&offset=" + offset +
  240.                 "&version=" + version +
  241.                 "&access_token=" + communityToken;
  242.         try {
  243.             HttpGet httpGetMessages = new HttpGet(urlGetMessages);
  244.             HttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom()
  245.                     .setCookieSpec(CookieSpecs.STANDARD).build())
  246.                     .build();
  247.             HttpResponse httpResponse = httpClient.execute(httpGetMessages);
  248.             String result = EntityUtils.toString(httpResponse.getEntity());
  249.             JSONObject json = new JSONObject(result);
  250.             JSONObject responeJson = json.getJSONObject("response");
  251.             JSONArray jsonArray = responeJson.getJSONArray("users");
  252.             ArrayList<VkMember> vkMembers = new ArrayList<>();
  253.             for (int i = 0; i < jsonArray.length(); i++) {
  254.                 vkMembers.add(new VkMember(Long.parseLong(jsonArray.get(i).toString()), groupId));
  255.             }
  256.             return Optional.of(vkMembers);
  257.         } catch (IOException e) {
  258.             logger.error("Failed to connect to VK server");
  259.         } catch (JSONException e) {
  260.             logger.error("Can not read message from JSON");
  261.         }
  262.         return Optional.empty();
  263.     }
  264.  
  265.     @Override
  266.     public String sendMessageById(Long id, String msg) {
  267.         return sendMessageById(id, msg, robotAccessToken);
  268.     }
  269.  
  270.     @Override
  271.     public String sendMessageById(Long id, String msg, String token) {
  272.         logger.info("VKService: sending message to client with id {}...", id);
  273.         String replaceCarriage = msg.replaceAll("(\r\n|\n)", "%0A")
  274.                 .replaceAll("\"|\'", "%22");
  275.         String uriMsg = replaceCarriage.replaceAll("\\s", "%20");
  276.  
  277.         String sendMsgRequest = vkAPI + "messages.send" +
  278.                 "?user_id=" + id +
  279.                 "&v=" + version +
  280.                 "&message=" + uriMsg +
  281.                 "&access_token=" + token;
  282.  
  283.         HttpGet request = new HttpGet(sendMsgRequest);
  284.         HttpClient httpClient = HttpClients.custom()
  285.                 .setDefaultRequestConfig(RequestConfig.custom()
  286.                         .setCookieSpec(CookieSpecs.STANDARD).build())
  287.                 .build();
  288.         try {
  289.             HttpResponse response = httpClient.execute(request);
  290.             JSONObject jsonEntity = new JSONObject(EntityUtils.toString(response.getEntity()));
  291.             return determineResponse(jsonEntity);
  292.         } catch (JSONException e) {
  293.             logger.error("JSON couldn't parse response ", e);
  294.         } catch (IOException e) {
  295.             logger.error("Failed connect to vk api ", e);
  296.         }
  297.         return "Failed to send message";
  298.     }
  299.  
  300.     // Determine text, which varies depending of the success of the sending message
  301.     private String determineResponse(JSONObject jsonObject) throws JSONException {
  302.         try {
  303.             jsonObject.getInt("response");
  304.             return "Message sent";
  305.         } catch (JSONException e) {
  306.             JSONObject jsonError = jsonObject.getJSONObject("error");
  307.             String errorMessage = jsonError.getString("error_msg");
  308.             logger.error(errorMessage);
  309.             return errorMessage;
  310.         }
  311.     }
  312.  
  313.     @Override
  314.     public Optional<List<Long>> getUsersIdFromCommunityMessages() {
  315.         logger.info("VKService: getting user ids from community messages...");
  316.         String uriGetDialog = vkAPI + "messages.getDialogs" +
  317.                 "?v=" + version +
  318.                 "&unread=1" +
  319.                 "&access_token=" +
  320.                 communityToken;
  321.  
  322.         HttpGet httpGetDialog = new HttpGet(uriGetDialog);
  323.         HttpClient httpClient = HttpClients.custom()
  324.                 .setDefaultRequestConfig(RequestConfig.custom()
  325.                         .setCookieSpec(CookieSpecs.STANDARD).build())
  326.                 .build();
  327.         try {
  328.             HttpResponse response = httpClient.execute(httpGetDialog);
  329.             String result = EntityUtils.toString(response.getEntity());
  330.             JSONObject json = new JSONObject(result);
  331.             JSONObject responseObject = json.getJSONObject("response");
  332.             JSONArray jsonUsers = responseObject.getJSONArray("items");
  333.             List<Long> resultList = new ArrayList<>();
  334.             for (int i = 0; i < jsonUsers.length(); i++) {
  335.                 JSONObject jsonMessage = jsonUsers.getJSONObject(i).getJSONObject("message");
  336.                 resultList.add(jsonMessage.getLong("user_id"));
  337.                 markAsRead(jsonMessage.getLong("user_id"), httpClient, technicalAccountToken);
  338.             }
  339.             return Optional.of(resultList);
  340.         } catch (JSONException e) {
  341.             logger.error("Can not read message from JSON ", e);
  342.         } catch (IOException e) {
  343.             logger.error("Failed to connect to VK server ", e);
  344.         }
  345.         return Optional.empty();
  346.     }
  347.  
  348.     private void markAsRead(long userId, HttpClient httpClient, String token) {
  349.         String uriMarkAsRead = vkAPI + "messages.markAsRead" +
  350.                 "?peer_id=" + userId +
  351.                 "&version=" + version +
  352.                 "&access_token=" + token;
  353.  
  354.         HttpGet httpMarkMessages = new HttpGet(uriMarkAsRead);
  355.         try {
  356.             httpClient.execute(httpMarkMessages);
  357.         } catch (IOException e) {
  358.             logger.error("Failed to mark as read message from community", e);
  359.         }
  360.     }
  361.  
  362.     @Override
  363.     public Optional<Client> getClientFromVkId(Long id) {
  364.         logger.info("VKService: getting client by VK id...");
  365.         String uriGetClient = vkAPI + "users.get?" +
  366.                 "version=" + version +
  367.                 "&user_id=" + id +
  368.                 "&access_token=" + technicalAccountToken;
  369.  
  370.         HttpGet httpGetClient = new HttpGet(uriGetClient);
  371.         HttpClient httpClient = HttpClients.custom()
  372.                 .setDefaultRequestConfig(RequestConfig.custom()
  373.                         .setCookieSpec(CookieSpecs.STANDARD).build())
  374.                 .build();
  375.         try {
  376.             HttpResponse response = httpClient.execute(httpGetClient);
  377.             String result = EntityUtils.toString(response.getEntity());
  378.             JSONObject json = new JSONObject(result);
  379.             JSONArray jsonUsers = json.getJSONArray("response");
  380.             JSONObject jsonUser = jsonUsers.getJSONObject(0);
  381.             String name = jsonUser.getString("first_name");
  382.             String lastName = jsonUser.getString("last_name");
  383.             String vkLink = "https://vk.com/id" + id;
  384.             Client client = new Client(name, lastName);
  385.             SocialProfile socialProfile = new SocialProfile(vkLink);
  386.             List<SocialProfile> socialProfiles = new ArrayList<>();
  387.             socialProfiles.add(socialProfile);
  388.             client.setSocialProfiles(socialProfiles);
  389.             return Optional.of(client);
  390.         } catch (JSONException e) {
  391.             logger.error("Can not read message from JSON ", e);
  392.         } catch (IOException e) {
  393.             logger.error("Failed to connect to VK server ", e);
  394.         }
  395.  
  396.         return Optional.empty();
  397.     }
  398.  
  399.     @Override
  400.     public Client parseClientFromMessage(String message) throws ParseClientException {
  401.         logger.info("VKService: parsing client from VK message...");
  402.         if (!message.startsWith("Новая заявка")) {
  403.             throw new ParseClientException("Invalid message format");
  404.         }
  405.         String[] fields = message.replaceAll("<br>", "").split("Q:");
  406.         Client newClient = new Client();
  407.         try {
  408.             StringBuilder description = new StringBuilder();
  409.             long number = 0; // позиция поля в заявке
  410.             boolean flag = true; // флаг для проверки заполненности не обязательного поля
  411.             for (VkRequestForm vkRequestForm : vkRequestFormService.getAllVkRequestForm()) {
  412.                 if (flag) {
  413.                     number = vkRequestForm.getNumberVkField();
  414.                 }
  415.                 if ("Обязательное".equals(vkRequestForm.getTypeVkField())) {
  416.                     switch (vkRequestForm.getNameVkField()) {
  417.                         case "Имя":
  418.                             newClient.setName(getValue(fields[(int) number]));
  419.                             flag = true;
  420.                             break;
  421.                         case "Фамилия":
  422.                             newClient.setLastName(getValue(fields[(int) number]));
  423.                             flag = true;
  424.                             break;
  425.                         case "Email":
  426.                             newClient.setEmail(getValue(fields[(int) number]));
  427.                             flag = true;
  428.                             break;
  429.                         case "Номер телефона":
  430.                             newClient.setPhoneNumber(getValue(fields[(int) number]));
  431.                             flag = true;
  432.                             break;
  433.                         case "Skype":
  434.                             newClient.setSkype(getValue(fields[(int) number]));
  435.                             flag = true;
  436.                             break;
  437.                         case "Возраст":
  438.                             newClient.setAge(Byte.parseByte(getValue(fields[(int) number])));
  439.                             flag = true;
  440.                             break;
  441.                         case "Город":
  442.                             newClient.setCity(getValue(fields[(int) number]));
  443.                             flag = true;
  444.                             break;
  445.                         case "Страна":
  446.                             newClient.setCountry(getValue(fields[(int) number]));
  447.                             flag = true;
  448.                             break;
  449.                         case "Пол":
  450.                             newClient.setSex(Sex.valueOf(getValue(fields[(int) number])));
  451.                             flag = true;
  452.                             break;
  453.                     }
  454.                 } else {
  455.                     if (message.contains(vkRequestForm.getNameVkField())) {
  456.                         description.append(vkRequestForm.getNameVkField()).append(": ").append(getValue(fields[(int) number])).append(" \n");
  457.                         flag = true;
  458.                     } else {
  459.                         flag = false;
  460.                     }
  461.                 }
  462.             }
  463.  
  464.             newClient.setClientDescriptionComment(description.toString());
  465.             SocialProfileType socialProfileType = socialProfileTypeService.getByTypeName("vk");
  466.             String social = fields[0];
  467.             SocialProfile socialProfile = new SocialProfile("https://" + social.substring(social.indexOf("vk.com/id"), social.indexOf("Диалог")), socialProfileType);
  468.             newClient.setSocialProfiles(Collections.singletonList(socialProfile));
  469.         } catch (Exception e) {
  470.             logger.error("Parse error, can't parse income string", e);
  471.         }
  472.         return newClient;
  473.     }
  474.  
  475.     private static String getValue(String field) {
  476.         return field.substring(field.indexOf("A: ") + 3);
  477.     }
  478.  
  479.     @Override
  480.     public String refactorAndValidateVkLink(String link) {
  481.         logger.info("VKService: refactoring and validation of VK link...");
  482.         String userName = link.replaceAll("^.+\\.(com/)", "");
  483.         String request = vkAPI + "users.get?"
  484.                 + "user_ids=" + userName
  485.                 + "&fields=first_name"
  486.                 + "&access_token=" + communityToken
  487.                 + "&v=" + version;
  488.         HttpGet httpGetClient = new HttpGet(request);
  489.         HttpClient httpClient = HttpClients.custom()
  490.                 .setDefaultRequestConfig(RequestConfig.custom()
  491.                         .setCookieSpec(CookieSpecs.STANDARD).build()).build();
  492.         try {
  493.             HttpResponse response = httpClient.execute(httpGetClient);
  494.             String result = EntityUtils.toString(response.getEntity());
  495.             JSONObject json = new JSONObject(result);
  496.             JSONArray responseArray = json.getJSONArray("response");
  497.             JSONObject vkUserJson = responseArray.getJSONObject(0);
  498.             String vkId = vkUserJson.getString("id");
  499.             if (vkUserJson.has("deactivated")) {
  500.                 logger.error("VkUser with id {} don't validate", vkId);
  501.                 return "undefined";
  502.             }
  503.             return "https://vk.com/id" + vkId;
  504.         } catch (JSONException e) {
  505.             logger.error("Can't take id by screen name {}", userName);
  506.             return "undefined";
  507.         } catch (IOException e) {
  508.             logger.error("Failed to connect to VK server ", e);
  509.             return link;
  510.         }
  511.     }
  512.  
  513.     private String replaceName(String msg, Map<String, String> params) {
  514.         String vkText = msg;
  515.         for (Map.Entry<String, String> entry : params.entrySet()) {
  516.             vkText = String.valueOf(new StringBuilder(vkText.replaceAll(entry.getKey(), entry.getValue())));
  517.         }
  518.         return vkText;
  519.     }
  520.  
  521.     @Override
  522.     public void setTechnicalAccountToken(String technicalAccountToken) {
  523.         this.technicalAccountToken = technicalAccountToken;
  524.     }
  525.  
  526.     @Override
  527.     public String replaceApplicationTokenFromUri(String uri) {
  528.         return uri.replaceAll(".+(access_token=)", "")
  529.                 .replaceAll("&.+", "");
  530.     }
  531.  
  532.     @Override
  533.     public String createNewAudience(String groupName, String idVkCabinet) throws Exception {
  534.         logger.info("VKService: creation of new audience...");
  535.         String createGroup = "https://api.vk.com/method/ads.createTargetGroup";
  536.         OAuth2AccessToken accessToken = new OAuth2AccessToken(technicalAccountToken);
  537.         OAuthRequest request = new OAuthRequest(Verb.GET, createGroup);
  538.         request.addParameter("account_id", idVkCabinet);
  539.         request.addParameter("name", groupName);
  540.         request.addParameter("v", version);
  541.         service.signRequest(accessToken, request);
  542.         Response response = service.execute(request);
  543.         String resp = new JSONObject(response.getBody()).get("response").toString();
  544.         String groupId = new JSONObject(resp).get("id").toString();
  545.         return groupId;
  546.     }
  547.  
  548.     @Override
  549.     public void addUsersToAudience(String groupId, String contacts, String idVkCabinet) throws Exception {
  550.         logger.info("VKService: adding users to audience...");
  551.         String addContactsToGroup = "https://api.vk.com/method/ads.importTargetContacts";
  552.         OAuth2AccessToken accessToken = new OAuth2AccessToken(technicalAccountToken);
  553.         OAuthRequest request = new OAuthRequest(Verb.POST, addContactsToGroup);
  554.         request.addParameter("account_id", idVkCabinet);
  555.         request.addParameter("target_group_id", groupId);
  556.         request.addParameter("contacts", contacts);
  557.         request.addParameter("v", version);
  558.         service.signRequest(accessToken, request);
  559.         Response response = service.execute(request);
  560.     }
  561.  
  562.     @Override
  563.     public void removeUsersFromAudience(String groupId, String contacts, String idVkCabinet) throws Exception {
  564.         logger.info("VKService: removing users to audience...");
  565.         String addContactsToGroup = "https://api.vk.com/method/ads.removeTargetContacts";
  566.         OAuth2AccessToken accessToken = new OAuth2AccessToken(technicalAccountToken);
  567.         OAuthRequest request = new OAuthRequest(Verb.POST, addContactsToGroup);
  568.         request.addParameter("account_id", idVkCabinet);
  569.         request.addParameter("target_group_id", groupId);
  570.         request.addParameter("contacts", contacts);
  571.         request.addParameter("v", version);
  572.         service.signRequest(accessToken, request);
  573.         Response response = service.execute(request);
  574.     }
  575.  
  576.     @PostConstruct
  577.     private void initAccessToken() {
  578.         logger.info("VKService: initialization of access token...");
  579.         String uri = "https://oauth.vk.com/token" +
  580.                 "?grant_type=password" +
  581.                 "&client_id=" + robotClientId +
  582.                 "&client_secret=" + robotClientSecret +
  583.                 "&username=" + robotUsername +
  584.                 "&password=" + robotPassword;
  585.  
  586.         HttpGet httpGet = new HttpGet(uri);
  587.         try {
  588.             HttpClient httpClient = new DefaultHttpClient();
  589.             HttpResponse response = httpClient.execute(httpGet);
  590.             String result = EntityUtils.toString(response.getEntity());
  591.             try {
  592.                 JSONObject json = new JSONObject(result);
  593.                 this.robotAccessToken = json.getString("access_token");
  594.             } catch (JSONException e) {
  595.                 logger.error("Perhaps the VK username/password configs are incorrect. Can not get AccessToken");
  596.             }
  597.         } catch (IOException e) {
  598.             logger.error("Failed to connect to VK server", e);
  599.         }
  600.  
  601.     }
  602.  
  603.     @Override
  604.     public String getFirstContactMessage() {
  605.         return firstContactMessage;
  606.     }
  607.  
  608.     @Override
  609.     public boolean hasTechnicalAccountToken() {
  610.         if (technicalAccountToken == null) {
  611.             if (projectPropertiesService.get() == null) {
  612.                 logger.error("VK access token has not got");
  613.                 return false;
  614.             }
  615.             technicalAccountToken = projectPropertiesService.get().getTechnicalAccountToken();
  616.         }
  617.         return true;
  618.     }
  619.  
  620.     @Override
  621.     public String getLongIDFromShortName(String vkGroupShortName) {
  622.         if (hasTechnicalAccountToken()) {
  623.             String uriGetGroup = vkAPI + "groups.getById?" +
  624.                     "group_id=" + vkGroupShortName +
  625.                     "&v=" + version +
  626.                     "&access_token=" + technicalAccountToken;
  627.             HttpGet httpGetGroup = new HttpGet(uriGetGroup);
  628.             HttpClient httpClient = HttpClients.custom()
  629.                     .setDefaultRequestConfig(RequestConfig.custom()
  630.                             .setCookieSpec(CookieSpecs.STANDARD).build())
  631.                     .build();
  632.             try {
  633.                 HttpResponse response = httpClient.execute(httpGetGroup);
  634.                 String result = EntityUtils.toString(response.getEntity());
  635.                 JSONObject json = new JSONObject(result);
  636.                 JSONArray responseObjects = json.getJSONArray("response");
  637.                 JSONObject responseObject = responseObjects.getJSONObject(0);
  638.                 String id = responseObject.getString("id");
  639.                 return id;
  640.             } catch (JSONException e) {
  641.                 logger.error("Can not read message from JSON", e);
  642.             } catch (IOException e) {
  643.                 logger.error("Failed to connect to VK server ", e);
  644.             }
  645.         }
  646.         return null;
  647.     }
  648.  
  649.     @Override
  650.     public Optional<PotentialClient> getPotentialClientFromYoutubeLiveStreamByYoutubeClient(YoutubeClient youtubeClient) {
  651.         if (hasTechnicalAccountToken()) {
  652.             youtubeClient.setChecked(true);
  653.             youtubeClientService.update(youtubeClient);
  654.             String fullName = youtubeClient.getFullName().replaceAll("(?U)[\\pP\\s]", "%20");
  655.             logger.info("VKService: getting client from YouTube Live Stream by name: " + fullName);
  656.             String uriGetClient = vkAPI + "users.search?" +
  657.                     "q=" + fullName +
  658.                     "&count=1" +
  659.                     "&group_id=" + youtubeClient.getYouTubeTrackingCard().getVkGroupID() +
  660.                     "&v=" + version +
  661.                     "&access_token=" + technicalAccountToken;
  662.  
  663.             HttpGet httpGetClient = new HttpGet(uriGetClient);
  664.             HttpClient httpClient = HttpClients.custom()
  665.                     .setDefaultRequestConfig(RequestConfig.custom()
  666.                             .setCookieSpec(CookieSpecs.STANDARD).build())
  667.                     .build();
  668.             try {
  669.                 HttpResponse response = httpClient.execute(httpGetClient);
  670.                 String result = EntityUtils.toString(response.getEntity());
  671.                 JSONObject json = new JSONObject(result);
  672.                 JSONObject responseObject = json.getJSONObject("response");
  673.  
  674.                 if (responseObject.getString("count").equals("0")) {
  675.                     logger.warn("VKService: response is empty");
  676.                     return Optional.empty();
  677.                 } else {
  678.                     logger.info("VKService: processing of response...");
  679.                     JSONArray jsonUsers = responseObject.getJSONArray("items");
  680.                     JSONObject jsonUser = jsonUsers.getJSONObject(0);
  681.                     long id = jsonUser.getLong("id");
  682.                     String firstName = jsonUser.getString("first_name");
  683.                     String lastName = jsonUser.getString("last_name");
  684.                     String vkLink = "https://vk.com/id" + id;
  685.                     PotentialClient potentialClient = new PotentialClient(firstName, lastName);
  686.                     SocialProfile socialProfile = new SocialProfile(vkLink);
  687.                     socialProfile.setSocialProfileType(socialProfileTypeService.getByTypeName("vk"));
  688.                     List<SocialProfile> socialProfiles = new ArrayList<>();
  689.                     socialProfiles.add(socialProfile);
  690.                     potentialClient.setSocialProfiles(socialProfiles);
  691.                     return Optional.of(potentialClient);
  692.                 }
  693.             } catch (JSONException e) {
  694.                 logger.error("Can not read message from JSON or YoutubeClient don't exist in VK group", e);
  695.             } catch (IOException e) {
  696.                 logger.error("Failed to connect to VK server ", e);
  697.             }
  698.         }
  699.         return Optional.empty();
  700.     }
  701.  
  702. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement