5

Like we detect anchor text using hitTestResult.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE, How can I detect a video playing on Facebook?

I want to know the hitTestResult.GetExtra() for a video file and then search for its valid extension (.mp4) and then download the file.

TheOnlyAnil
  • 877
  • 1
  • 15
  • 27

1 Answers1

10

So as I understand based on what you described you load your FB page in a WebView and want to download .mp4 videos if there is one. This code will do it for you

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    webView = (WebView)findViewById(R.id.webView);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setPluginState(WebSettings.PluginState.ON);
    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setDisplayZoomControls(true);
    webView.getSettings().setUseWideViewPort(true);
    webView.getSettings().setLoadWithOverviewMode(true);
    webView.addJavascriptInterface(this, "FBDownloader");
    webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url)
            {
                if (swipeLayout.isRefreshing())
                {
                    swipeLayout.setRefreshing(false);
                }

                webView.loadUrl("javascript:(function() { "
                                + "var el = document.querySelectorAll('div[data-sigil]');"
                                + "for(var i=0;i<el.length; i++)"
                                + "{"
                                + "var sigil = el[i].dataset.sigil;"
                                + "if(sigil.indexOf('inlineVideo') > -1){"
                                + "delete el[i].dataset.sigil;"
                                + "var jsonData = JSON.parse(el[i].dataset.store);"
                                + "el[i].setAttribute('onClick', 'FBDownloader.processVideo(\"'+jsonData['src']+'\");');"
                                + "}" + "}" + "})()");
            }

            @Override
            public void onLoadResource(WebView view, String url)
            {
                webView.loadUrl("javascript:(function prepareVideo() { "
                                + "var el = document.querySelectorAll('div[data-sigil]');"
                                + "for(var i=0;i<el.length; i++)"
                                + "{"
                                + "var sigil = el[i].dataset.sigil;"
                                + "if(sigil.indexOf('inlineVideo') > -1){"
                                + "delete el[i].dataset.sigil;"
                                + "console.log(i);"
                                + "var jsonData = JSON.parse(el[i].dataset.store);"
                                + "el[i].setAttribute('onClick', 'FBDownloader.processVideo(\"'+jsonData['src']+'\",\"'+jsonData['videoID']+'\");');"
                                + "}" + "}" + "})()");
                webView.loadUrl("javascript:( window.onload=prepareVideo;"
                                + ")()");
            }
        });

    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    CookieSyncManager.getInstance().startSync();

    webView.loadUrl(target_url);
}

@JavascriptInterface
public void processVideo(final String vidData, final String vidID)
{
    try
    {
        String mBaseFolderPath = android.os.Environment
            .getExternalStorageDirectory()
            + File.separator
            + "FacebookVideos" + File.separator;
        if (!new File(mBaseFolderPath).exists())
        {
            new File(mBaseFolderPath).mkdir();
        }
        String mFilePath = "file://" + mBaseFolderPath + "/" + vidID + ".mp4";

        Uri downloadUri = Uri.parse(vidData);
        DownloadManager.Request req = new DownloadManager.Request(downloadUri);
        req.setDestinationUri(Uri.parse(mFilePath));
        req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        DownloadManager dm = (DownloadManager) getSystemService(getApplicationContext().DOWNLOAD_SERVICE);
        dm.enqueue(req);
        Toast.makeText(this, "Download Started", Toast.LENGTH_LONG).show();
    }
    catch (Exception e)
    {
        Toast.makeText(this, "Download Failed: " + e.toString(), Toast.LENGTH_LONG).show();
    }
}
Rainmaker
  • 10,294
  • 9
  • 54
  • 89
  • How to detect Image ? Upvote for detect Video script. – Tushar Lathiya Jul 22 '19 at 07:05
  • @Rainmaker how to do this for any website which play videos? – Mayank Pandya Aug 01 '19 at 07:41
  • @MayankPandya check this link, the accepted answer has a similar script to detect a video https://stackoverflow.com/questions/51264506/check-if-a-webview-is-playing-a-video – Rainmaker Aug 01 '19 at 13:36
  • @Rainmaker Thank you for your response. but that link is only detecting video playing in webview and I have no idea how to download that playing video. can you suggest me something? – Mayank Pandya Aug 01 '19 at 19:09
  • @MayankPandya you can reuse the script from my answer as u will need basically the same javascript interface for that , or if u need a ready to run solution it is better to ask a stand alone question for that. – Rainmaker Aug 02 '19 at 15:44
  • it is valid way to do? i mean play team accept this kind of stuff? – Daxesh V Jun 02 '20 at 10:36
  • They allow injecting javascript into WebView but in the docs it says that it is a vulnerability point for your app and the better way is to disable JS whatsoever but it doesn't mean it is not allowed. @DaxeshVekariya – Rainmaker Jun 02 '20 at 13:53
  • It is not working. I think it needs an update. – Maseed Jun 02 '21 at 06:31
  • It give me MPD file sometimes, so how to handle it to fetch the url of video ? – Smeet Jun 04 '21 at 09:58