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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 | package com.codesys.forge; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Intent; import androidx.annotation.NonNull; import android.content.Context; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationManagerCompat; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.app.ProgressDialog; import android.net.Uri; import android.os.Build; import android.util.Log; import android.view.MenuItem; import android.view.KeyEvent; import android.os.Bundle; import android.view.View; import android.view.ViewTreeObserver; import android.view.Window; import android.webkit.MimeTypeMap; import android.webkit.WebChromeClient; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebView; import android.webkit.WebSettings; import android.webkit.WebViewClient; import android.webkit.CookieManager; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.math.BigInteger; import java.net.MalformedURLException; import java.net.URL; import java.net.HttpURLConnection; import java.io.BufferedReader; import java.io.InputStreamReader; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; import android.os.AsyncTask; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; import org.json.*; import com.google.android.material.bottomnavigation.BottomNavigationView; class NotificationReceiver { } public class MainActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener { private Context myContext; private WebView myWebView; private static final String TAG = "Main"; private BottomNavigationView bottomnav; private SwipeRefreshLayout refreshLayout; private ViewTreeObserver.OnScrollChangedListener onScrollChangedListener; // // When rotating the device, onCreate is rerun, and the instance is recreated. // We make everything that should survive this layout change static. // private static String currentURL = "https://forge.codesys.com/forge/community-feed"; private static Boolean xOffline; private static Boolean xNews; private static Boolean xProjects; private static Boolean xTalk; // cache directory private File getLocalCacheDir() { File cacheDir = new File(MainActivity.this.getCacheDir(), "cache"); cacheDir.mkdirs(); return cacheDir; } private void writeStringToCache(String Filename, String Content) throws IOException { File cacheFile = new File(Filename); BufferedWriter writer = new BufferedWriter(new FileWriter(cacheFile)); writer.write(Content); writer.close(); } private void downloadCacheFile(String Filename, String Url) { new AsyncTask<String, Integer, String>() { @Override protected String doInBackground(String... arg0) { String Filename = arg0[0]; String Url = arg0[1]; String cookies = CookieManager.getInstance().getCookie(Url); try { File cacheFile = new File(Filename); Date nextUpdate = new Date(cacheFile.lastModified() + (24 * 60 * 60 * 1000)); if (nextUpdate.before(new Date())) { URL url = new URL(Url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); if (cookies != null) conn.setRequestProperty("Cookie", cookies); conn.connect(); InputStream reader = conn.getInputStream(); FileOutputStream writer = new FileOutputStream(cacheFile); byte[] buffer = new byte[1024]; int len; while ((len = reader.read(buffer)) > 0) { writer.write(buffer, 0, len); } writer.close(); reader.close(); } } catch(MalformedURLException e) { } catch(IOException e) { } return "error"; } }.execute(Filename, Url); } protected void loadUrl(String Url, String Title) { refreshLayout.setRefreshing(true); currentURL = Url; myWebView.loadUrl(Url); RemoveNotification(); } private boolean getNetworkState() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null; } private void setOffline() { myWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY); xOffline = true; } private void setOnline() { myWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); xOffline = false; } private boolean getOffline() { return xOffline; } protected boolean isLoggedIn() { String cookies = CookieManager.getInstance().getCookie("https://forge.codesys.com/"); if (cookies.contains("allura-loggedin=true")) return true; else return false; } @Override public void onRefresh() { refreshLayout.setRefreshing(true); setOnline(); ReLoadWebView(currentURL); } private void ReLoadWebView(String currentURL) { if(getNetworkState()) { setOnline(); } else { setOffline(); } myWebView.loadUrl(currentURL); RemoveNotification(); } private void CreateNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.channel_name); String description = getString(R.string.channel_description); int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(getString(R.string.channel_id), name, importance); channel.setDescription(description); NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } } private void RemoveNotification() { int id = 0; if (currentURL.contains("forge/community-feed")) { id = 1; } else if (currentURL.contains("forge/news")) { id = 2; } else if (currentURL.contains("forge/talk")) { id = 3; } NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.cancel(id); } private void CreateNotification(int id) { String title; String description; switch(id) { case 1: title = getString(R.string.notification1_title); description = getString(R.string.notification1_description); break; case 2: title = getString(R.string.notification2_title); description = getString(R.string.notification2_description); break; case 3: title = getString(R.string.notification3_title); description = getString(R.string.notification3_description); break; default: title = "title undefined"; description = "description undefined"; break; } CreateNotificationChannel(); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getString(R.string.channel_id)) .setSmallIcon(R.drawable.ic_codesys_logo) .setContentTitle(title) .setContentText(description) .setPriority(NotificationCompat.PRIORITY_DEFAULT); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(id, builder.build()); } @Override protected void onCreate(Bundle savedInstanceState) { String myUseragent; super.onCreate(savedInstanceState); // start long polling service startService(new Intent(this, MyService.class)); myContext = getApplicationContext(); // // Instantiate WebView // // hide title bar requestWindowFeature(Window.FEATURE_NO_TITLE); //will hide the title getSupportActionBar().hide(); // hide the title bar setContentView(R.layout.activity_main); myWebView = (WebView) findViewById(R.id.webview); // Enable JavaScript WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); myWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); // enable cache myWebView.getSettings().setAppCacheEnabled(true); myWebView.getSettings().setAppCachePath(getCacheDir().getAbsolutePath()); myWebView.getSettings().setDomStorageEnabled(true); myWebView.getSettings().setAllowFileAccess(true); if(getNetworkState()) { setOnline(); } else { setOffline(); } // add keyword 'cforge' to useragent, so that the website can identify it myUseragent = myWebView.getSettings().getUserAgentString(); myUseragent += " cforge"; myWebView.getSettings().setUserAgentString(myUseragent); // reload page refreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe); refreshLayout.setOnRefreshListener(this); // Override URL Loading myWebView.setWebViewClient(new WebViewClient() { public String getFilenameFromURL(String url) { try { MessageDigest md = MessageDigest.getInstance("MD5"); byte[] messageDigest = md.digest(url.getBytes()); BigInteger number = new BigInteger(1, messageDigest); String md5 = number.toString(16); File cacheDir = getLocalCacheDir(); File fileName = new File(cacheDir, md5); return fileName.toString(); } catch (NoSuchAlgorithmException e) { Log.e("MD5", e.getLocalizedMessage()); return null; } } public boolean shouldOverrideUrlLoading(WebView view, String url) { currentURL = url; return false; } public void onPageFinished(WebView view, String url) { boolean xCache = getOffline(); refreshLayout.setRefreshing(false); } //get encoding by mime type public String getEncoding(String mime) { if (mime != null) { if (mime.startsWith("image/")) { return ""; } } return "UTF-8"; } //get mime type by url public String getMimeType(String url) { String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(url); if (extension != null) { if (extension == "" && url.endsWith("icon")) { return "image/jpeg"; } else if (extension == "") { return "text/html"; } else if (extension.equals("js")) { return "text/javascript"; } else if (extension.equals("woff")) { return "application/font-woff"; } else if (extension.equals("woff2")) { return "application/font-woff2"; } else if (extension.equals("ttf")) { return "application/x-font-ttf"; } else if (extension.equals("eot")) { return "application/vnd.ms-fontobject"; } else if (extension.equals("svg")) { return "image/svg+xml"; } type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } return type; } @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { Uri url = request.getUrl(); String filename = getFilenameFromURL(url.toString()); // remote request if (url.toString().startsWith("https://forge.codesys.com")) { if(!getNetworkState()) { xOffline = true; } if (!getOffline()) { // online => cache all files downloadCacheFile(filename, url.toString()); return super.shouldInterceptRequest(view, request); } else { // offline => return cached files InputStream file; String mime; String enc; try { file = new FileInputStream(filename); mime = getMimeType(url.toString()); enc = getEncoding(mime); if (mime != null) return new WebResourceResponse(mime, enc, file); } catch (FileNotFoundException e) { e.printStackTrace(); } } } return null; } public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { // load local file, stating that we're offline /* File cacheDir = getLocalCacheDir(); File fileName = new File(cacheDir, "default.html"); view.loadUrl("file://" + fileName.toString()); */ refreshLayout.setRefreshing(false); setOffline(); } }); // // copy URL on long click // myWebView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { WebView.HitTestResult result = myWebView.getHitTestResult(); String linkToCopy = ""; if (result != null) { if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) { linkToCopy = result.getExtra(); ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText("Link URL", linkToCopy); clipboard.setPrimaryClip(clip); Toast.makeText(myContext,"Copied to clipboard",Toast.LENGTH_SHORT).show(); return false; } } return false; } }); // // Add navigation bar // bottomnav = findViewById(R.id.bottomNavigationView); bottomnav.setOnNavigationItemSelectedListener(navListener); ReLoadWebView(currentURL); } // back button @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (myWebView.canGoBack()) { myWebView.goBack(); } else { finish(); } return true; } } return super.onKeyDown(keyCode, event); } @Override public void onStart() { super.onStart(); // avoid unwanted refreshes when not scrolled to the top of the webview refreshLayout.getViewTreeObserver().addOnScrollChangedListener(onScrollChangedListener = new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { if (myWebView.getScrollY() == 0) refreshLayout.setEnabled(true); else refreshLayout.setEnabled(false); } }); } @Override public void onStop() { refreshLayout.getViewTreeObserver().removeOnScrollChangedListener(onScrollChangedListener); super.onStop(); } // react on navigation bar private BottomNavigationView.OnNavigationItemSelectedListener navListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { switch(menuItem.getItemId()) { case R.id.community: loadUrl("https://forge.codesys.com/forge/community-feed", "Community"); break; case R.id.news: loadUrl("https://forge.codesys.com/forge/news", "News"); break; case R.id.talk: loadUrl("https://forge.codesys.com/forge/talk", "Talk"); break; } menuItem.setChecked(true); return true; } }; } |