1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
| public String likes(String token, String type, String owner_id,
String item_id, String page_url, String isbutselected,
boolean C1, boolean C2, boolean C3) throws InterruptedException {
this.token = token; //токен
this.type = type; //тип объекта
this.owner_id = owner_id; //идентификатор владельца Like-объекта
this.item_id = item_id; //идентификатор Like-объекта
this.page_url = page_url; //url страницы, на которой установлен виджет «Мне нравится»
this.isbutselected = isbutselected; // Формат вывода результата
this.c1 = C1; //Лайкнувших
this.c2 = C2; //Репостнувших
this.c3 = C3; //Прокомментировавших
//Обнуляем счетчики
j = 0;
offset = 0;
int kol = 0;
Platform.runLater(() -> ZagruzkaOkon.lic.getSpinner().setProgress(0));
Platform.runLater(() -> ZagruzkaOkon.lic.getLabel().setText("0%"));
Platform.runLater(() -> ZagruzkaOkon.lic.getSpinner1().setProgress(0));
Platform.runLater(() -> ZagruzkaOkon.lic.getLabel1().setText("0%"));
Platform.runLater(() -> ZagruzkaOkon.lic.getSpinner2().setProgress(0));
Platform.runLater(() -> ZagruzkaOkon.lic.getLabel2().setText("0%"));
//----------------------------------------------------------
//Переменные для подсчета времени выполнения функции
long starttime = 0;
long finichtime = 0;
int kolzaprosov = 0; //количество сделанных запросов
//----------------------------------------------------------
switch (type) {
case "0":
temp_type = "Запись на стене";
par = "\"type\":\"post\","; //запись на стене пользователя или группы
break;
case "1":
temp_type = "Комментарий к записи на стене";
par = "\"type\":\"comment\","; // комментарий к записи на стене
break;
case "2":
temp_type = "Фотография";
par = "\"type\":\"photo\","; // фотография
break;
case "3":
temp_type = "Видеозапись";
par = "\"type\":\"video\","; // видеозапись
break;
case "4":
temp_type = "Заметка";
par = "\"type\":\"note\","; //заметка
break;
case "5":
temp_type = "Товар";
par = "\"type\":\"market\","; //товар
break;
case "6":
temp_type = "Комментарий к фотографии";
par = "\"type\":\"photo_comment\","; //комментарий к фотографии
break;
case "7":
temp_type = "Комментарий к видеозаписи";
par = "\"type\":\"video_comment\","; //комментарий к видеозаписи
break;
case "8":
temp_type = "Комментарий в обсуждении";
par = "\"type\":\"topic_comment\","; //комментарий в обсуждении
break;
case "9":
temp_type = "Комментарий к товару";
par = "\"type\":\"market_comment\","; //комментарий к товару
break;
case "10":
temp_type = "Страница сайта с виджетом";
par = "\"type\":\"sitepage\","; //страница сайта, на котором установлен виджет «Мне нравится»
break;
default:
break;
}
//Узнаем имя пользователя или группы для названия файла
if(!owner_id.startsWith("-")) {
User_ID u_id = new User_ID(Authorization.token, owner_id);
String[] us_id = u_id.getID();
this.user_name = "\\(Список лайкнувших)".concat(us_id[1].replace("\"", "")).concat("_")
.concat(us_id[2].replace("\"", "")).concat("_ID").
concat(owner_id).concat("_" + temp_type + "_").concat(item_id);
}else{
//Узнаем название группы для названия файлов
Group_ID group_id_name = new Group_ID(Authorization.token, owner_id.replace("-",""));
String[] gr = group_id_name.getID();
this.user_name = "\\(Список лайкнувших)".concat(gr[1].replace("\"", "")).concat("_")
.concat(owner_id.replace("-","")).
concat("_" + temp_type + "_").concat(item_id);
}
//Убираем все запрещенные символы из имени файла
char[] eRsimv = {'/',':','*','?','<','>','|','+','.','%','!','@'};
for(int i = 0; i < eRsimv.length; i++){
user_name = user_name.replace(String.valueOf(eRsimv[i]),"");
user_name = user_name.replace(" ","_");
}
//Удаляем старый файл
File dfile = new File(System.getProperty("user.dir") + "\\temp.txt");
dfile.delete();
File dfile1 = new File(System.getProperty("user.dir") + user_name.concat(".txt"));
dfile1.delete();
File dfile2 = new File(System.getProperty("user.dir") + user_name.concat("NULL").concat(".txt"));
dfile2.delete();
StringBuilder sb = new StringBuilder();
//Делаем шапку таблицы
try {
savefile(System.getProperty("user.dir") + user_name.concat(".txt"),
new StringBuilder("№п\\п".concat(" ") +
"Статус_страницы".concat(" ") +
"ID".concat(" ") +
"Имя".concat(" ") +
"Фамилия".concat(" ") +
"Пол".concat(" ") +
"Дата_рождения".concat(" ") +
"Родной_город".concat(" ") +
"ВУЗ".concat(" ") +
"Моб.телефон".concat(" ") +
"Дом.телефон".concat(" ") +
"Статус_онлайн".concat(lineSeparator)));
} catch (Exception e) {
e.printStackTrace();
}
//Формат для вывода даты
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss");
Boolean b = true;
String filter = "\"filter\":\"likes\","; //возвращать информацию обо всех пользователях
String extended = "\"extended\":\"1\","; //возвращать расширенную информацию о пользователях
String skip_own = "\"skip_own\":\"0\","; // возвращать и самого пользователя
//Прогрессбар
Platform.runLater(() -> ZagruzkaOkon.lic.getSpinner().setProgress(0));
Platform.runLater(() -> ZagruzkaOkon.lic.getLabel().setText("0%"));
//Узнаем количество людей лайкнувших объект
int countLikes = getCount(par, token);
//----------------------------------------------------------------------------------------------------------//
while (b) {
if (kolzaprosov == 0)
starttime = System.nanoTime(); // Стартуем время выполнения функции
kolzaprosov++;
String code = null;
try {
code = URLEncoder.encode(
"var Likes;" +
"Likes = API.likes.getList({" +
par +
"\"owner_id\":" + owner_id + "," +
"\"item_id\":" + item_id + "," +
filter +
extended +
"\"offset\":" + String.valueOf(offset) + "," +
"\"count\":1000," +
skip_own +
"\"v\":\"5.95\"" +
"}).items;" +
"var i = " + countLikes + ";" +
"var k = 1;" +
"var offset = " + String.valueOf(offset + 1000) + ";" +
"while((k < 25) && (offset < i)){" + //ЕСЛИ ТУТ ВЫСТАВИТЬ 15 то все работает ХОРОШО
"Likes = Likes + API.likes.getList({" +
par +
"\"owner_id\":" + owner_id + "," +
"\"item_id\":" + item_id + "," +
filter +
extended +
"\"offset\":offset," +
"\"count\":1000," +
skip_own +
"\"v\":\"5.95\"" +
"}).items;" +
"offset = offset + 1000;" +
"k = k + 1;}" +
"return {\"count\":i, \"items\":Likes};"
, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String query = "https://api.vk.com/method/execute?code="
+ code + "&access_token=" + token;
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) new URL(query).openConnection();
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setConnectTimeout(10000);
connection.setReadTimeout(10000);
connection.connect();
if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {
String line;
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
while ((line = in.readLine()) != null) {
sb.append(line).append(lineSeparator);
System.out.println(sb.length());
try {
savefile(System.getProperty("user.dir") + "\\temp.txt", sb);
} catch (Exception err) {
err.printStackTrace();
}
}
in.close();
} else {
System.out.println(connection.getResponseMessage() + " " + connection.getResponseCode());
System.exit(-1);
}
} catch (Throwable cause) {
if(cause instanceof SocketTimeoutException){
System.out.println("Ошибка ожидания ответа сервера!");
SocketTimeoutException e = (SocketTimeoutException) cause;
e.printStackTrace();
System.exit(-1);
}else {
cause.printStackTrace();
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
//Обработка возможных ошибок
if (sb.toString().indexOf("\"error\":") > -1) {
String err_kod, err_msg;
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(sb.toString());
JsonObject rootObject = jsonElement.getAsJsonObject(); // чтение главного объекта
JsonObject childObject = rootObject.getAsJsonObject("error").getAsJsonObject("Likers"); // get place object
err_kod = childObject.get("error_code").getAsString();
err_msg = childObject.get("error_msg").getAsString();
System.out.println(err_kod + " " + err_msg);
try {
savefile(System.getProperty("user.dir") + user_name.concat(".txt"),
new StringBuilder("Ошибка обработки!" + lineSeparator +
"Код ошибки: " + err_kod + " (" + err_msg + ")"));
} catch (Exception e) {
e.printStackTrace();
}
return (System.getProperty("user.dir") + user_name.concat(".txt"));
}
if (kol == 0) {
kol = countLikes;
}
if (kol - offset > 25000) {
offset += 25000;
//Прогрессбар
double pr = kol / 100;
Platform.runLater(() -> ZagruzkaOkon.lic.getSpinner().setProgress(offset / pr / 100));
Platform.runLater(() -> ZagruzkaOkon.lic.getLabel().setText(String.valueOf(Math.round(ZagruzkaOkon.lic.getSpinner().getProgress() * 100)) + "%"));
} else {
offset = kol;
try {
//Прогрессбар
Platform.runLater(() -> ZagruzkaOkon.lic.getSpinner().setProgress(1));
Platform.runLater(() -> ZagruzkaOkon.lic.getLabel().setText("100%"));
} catch (Exception e) {
e.printStackTrace();
}
b = false;
}
sb = new StringBuilder();
finichtime = System.nanoTime();
if (kolzaprosov == 3) {
//Время работы функции за три запроса
double c = (double) (finichtime - starttime) / 1000000000;
DecimalFormat df = new DecimalFormat("#.##");//округляем до сотых
Platform.runLater(() -> ZagruzkaOkon.lic.
setAppendTextLog("[" + format.format(new Date()) +
"] Три запроса к API - " + df.format(c) + " cек" +
lineSeparator));
kolzaprosov = 0;
}
}
//--------------------------------------------------------------------------------
int finalKol = kol;
Platform.runLater(() -> ZagruzkaOkon.lic.
setAppendTextLog("[" + format.format(new Date()) +
"] Загружены данные на " + finalKol + " чел." +
lineSeparator));
try {
result = OtpravkaPars(System.getProperty("user.dir") + "\\temp.txt");
} catch (Exception e) {
e.printStackTrace();
}
return (result);
} |