88import io .javalin .http .NotFoundResponse ;
99import kong .unirest .Unirest ;
1010import org .jsoup .Jsoup ;
11- import org .jsoup .nodes .Document ;
1211
1312import java .sql .SQLException ;
14- import java . time . LocalDateTime ;
13+
1514
1615public class UrlChecksController {
1716 public static void check (Context ctx ) throws SQLException {
@@ -23,33 +22,43 @@ public static void check(Context ctx) throws SQLException {
2322
2423
2524 try {
26- var response = Unirest .get (name ).asString ();
25+ var response = Unirest .get (name )
26+ .header ("User-Agent" , "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" )
27+ .asString ();
28+
2729 int statusCode = response .getStatus ();
30+ String h1 = "" ;
31+ String title = "" ;
32+ String description = "" ;
2833
2934 if (statusCode == 200 ) {
30- Document responseBody = Jsoup .parse (response .getBody ());
31-
32- String h1 = responseBody .selectFirst ("h1" ) != null
33- ? responseBody .selectFirst ("h1" ).text () : "" ;
35+ var doc = Jsoup .parse (response .getBody ());
36+ var h1El = doc .selectFirst ("h1" );
37+ var descEl = doc .selectFirst ("meta[name~=(?i)description]" );
3438
35- String title = responseBody . title () ;
36-
37- String description = ! responseBody . select ( "meta[name=description]" ). isEmpty ()
38- ? responseBody . select ( "meta[name=description]" ). get ( 0 ). attr ( "content" ) : "" ;
39+ h1 = h1El != null ? h1El . text () : "" ;
40+ title = doc . title ();
41+ description = descEl != null ? descEl . attr ( "content" ) : "" ;
42+ }
3943
40- var createdAt = LocalDateTime .now ();
44+ var check = new UrlCheck (statusCode , h1 , title , description );
45+ check .setUrlId (urlId );
46+ UrlCheckRepository .save (check );
4147
42- var urlCheck = new UrlCheck (statusCode , h1 , title , description );
43- urlCheck .setUrlId (urlId );
44- UrlCheckRepository .save (urlCheck );
45- System .out .println ("[DEBUG] Сохранили новую проверку для urlId=" + urlId );
48+ boolean incomplete = statusCode != 200 || title .isEmpty () || h1 .isEmpty () || description .isEmpty ();
49+ if (incomplete ) {
50+ ctx .sessionAttribute ("message" , "Проверка выполнена, но не удалось получить все данные "
51+ + "(код " + statusCode + ")" );
52+ } else {
53+ ctx .sessionAttribute ("message" , "Проверка выполнена успешно (код " + statusCode + ")" );
4654 }
47- ctx . redirect ( NamedRoutes . urlPath ( urlId ));
55+
4856 } catch (Exception e ) {
49- ctx . sessionAttribute ( "message" , " Проверка не пройдена" );
50- ctx .redirect ( NamedRoutes . urlPath ( urlId ));
57+ System . out . println ( "[ERROR] Проверка не выполнена: " + e . getMessage () );
58+ ctx .sessionAttribute ( "message" , "Проверка не пройдена: " + e . getMessage ( ));
5159 }
5260
61+ ctx .redirect (NamedRoutes .urlPath (urlId ));
5362 }
5463}
5564
0 commit comments