Package play_downloader

Source Code of play_downloader.PlayDownloaderView$MenuItemActionListener

/*
* PlayDownloaderView.java
*/

package play_downloader;

import java.awt.Desktop;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.WindowEvent;
import java.net.*;
import java.util.EventObject;
import java.util.logging.Level;
import javax.swing.JTable;
import javax.swing.text.BadLocationException;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.io.*;
import java.util.prefs.Preferences;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.application.Application.ExitListener;

/**
* The application's main frame.
* @author UT_lol
*/
public class PlayDownloaderView extends FrameView {

    public PlayDownloaderView(SingleFrameApplication app) {
        super(app);
        checkOS();

        initComponents();
        jTextField1.addMouseListener(new PopupClickListener());
        jTable1.addMouseListener(new PopupClickListener());
        jTable1.setShowGrid(false);
        jTable1.setAutoCreateRowSorter(true);
        jTable1.setFillsViewportHeight(true); //white background
        clearTableData();

        applySettings(); //check if the proxy is activated,
        prefs = Preferences.userNodeForPackage(PlayDownloaderApp.class);

        File dir = new File (prefs.get(S.PREF_SAVE_FOLDER, "."));
        try {
            saveFolder = dir.getCanonicalPath();
            //prefs.put(S.PREF_SAVE_FOLDER, saveFolder);
        } catch (IOException ex) {
            PlayDownloaderApp.logger.log(Level.SEVERE, null, ex);
        }
        jTextField2.setText(saveFolder);
        dObjects = new DownloadableObjects[4];

        //adding exitListener
        PlayDownloaderApp.getApplication().addExitListener(new ExitListener() {

            public boolean canExit(EventObject eo) {
                if(progressBar.isVisible()){
                    int out = JOptionPane.showConfirmDialog(mainPanel, "You have still unfinished downloads.\n\nAre you sure you want to quit?");
                    if(out == 1) return false;
                    if(out == 0) return true;
                    return false;
                }else{
                    //nothing is downloading, its okej to exit
                    return true;
                }
            }

            public void willExit(EventObject eo) {
                //OK
            }
        });

        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = PlayDownloaderApp.getApplication().getMainFrame();
            aboutBox = new PlayDownloaderAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        PlayDownloaderApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jFindButton = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        proxySettingsMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        viewMenu = new javax.swing.JMenu();
        showLogView_MenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        mainPanel.setName("mainPanel"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        jPanel1.setName("jPanel1"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(play_downloader.PlayDownloaderApp.class).getContext().getResourceMap(PlayDownloaderView.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jTextField1.setText(resourceMap.getString("AddressBar.text")); // NOI18N
        jTextField1.setName("AddressBar"); // NOI18N
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextField1KeyPressed(evt);
            }
        });

        jFindButton.setText(resourceMap.getString("findButton.text")); // NOI18N
        jFindButton.setName("findButton"); // NOI18N
        jFindButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFind(evt);
            }
        });

        jButton2.setText(resourceMap.getString("downloadButton.text")); // NOI18N
        jButton2.setName("downloadButton"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDownload(evt);
            }
        });

        jButton3.setText(resourceMap.getString("clearButton.text")); // NOI18N
        jButton3.setMaximumSize(new java.awt.Dimension(81, 23));
        jButton3.setMinimumSize(new java.awt.Dimension(81, 23));
        jButton3.setName("clearButton"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonClear(evt);
            }
        });

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "Title", "Address", "Bitrate", "Status", "Progress"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane2.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTable1.columnModel.title0")); // NOI18N
        jTable1.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTable1.columnModel.title1")); // NOI18N
        jTable1.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jTable1.columnModel.title2")); // NOI18N
        jTable1.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("jTable1.columnModel.title4")); // NOI18N
        jTable1.getColumnModel().getColumn(4).setHeaderValue(resourceMap.getString("jTable1.columnModel.title3")); // NOI18N
        jTable1.getColumnModel().getColumn(4).setCellRenderer(new play_downloader.ProgressRenderer());

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
        jLabel2.setName("jLabel2"); // NOI18N

        jTextField2.setEditable(false);
        jTextField2.setText(resourceMap.getString("jTextField2.text")); // NOI18N
        jTextField2.setName("jTextField2"); // NOI18N

        jButton4.setText(resourceMap.getString("jButton4.text")); // NOI18N
        jButton4.setName("jButton4"); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBrowse(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 914, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 792, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jFindButton, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 615, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jFindButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 230, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4))
                .addContainerGap())
        );

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setMnemonic('f');
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        proxySettingsMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        proxySettingsMenuItem.setMnemonic('E');
        proxySettingsMenuItem.setText(resourceMap.getString("proxySettingsMenuItem.text")); // NOI18N
        proxySettingsMenuItem.setName("proxySettingsMenuItem"); // NOI18N
        proxySettingsMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                proxySettingsMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(proxySettingsMenuItem);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(play_downloader.PlayDownloaderApp.class).getContext().getActionMap(PlayDownloaderView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        viewMenu.setMnemonic('v');
        viewMenu.setText(resourceMap.getString("viewMenu.text")); // NOI18N
        viewMenu.setName("viewMenu"); // NOI18N

        showLogView_MenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_L, java.awt.event.InputEvent.CTRL_MASK));
        showLogView_MenuItem.setText(resourceMap.getString("showLogView_MenuItem.text")); // NOI18N
        showLogView_MenuItem.setName("showLogView_MenuItem"); // NOI18N
        showLogView_MenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showLogView_MenuItemActionPerformed(evt);
            }
        });
        viewMenu.add(showLogView_MenuItem);

        menuBar.add(viewMenu);

        helpMenu.setMnemonic('h');
        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 966, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 792, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        jMenuBar1.setName("jMenuBar1"); // NOI18N

        jMenu1.setText(resourceMap.getString("jMenu1.text")); // NOI18N
        jMenu1.setName("jMenu1"); // NOI18N
        jMenuBar1.add(jMenu1);

        jMenu2.setText(resourceMap.getString("jMenu2.text")); // NOI18N
        jMenu2.setName("jMenu2"); // NOI18N
        jMenuBar1.add(jMenu2);

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    /**
     * Downloads the htm file and sends everyLine from line 140+ to "findLink"-method
     * @param evt
     */
    private void jButtonFind(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFind
        startBusyIcon();

        new Thread(new Runnable() {
           
            public void run() {
                jFindButton.setEnabled(false);
                siteUrl = jTextField1.getText();
                int found = 0;
                if(!siteUrl.equals("")){
                    clearTableData();
                    URL curSite = null;
                    try {
                        if(PLAYRAPPORT_PATTERN.matcher(siteUrl).find())
                            siteUrl = playrapportToSvtplay(siteUrl);

                        if(isDirectLink(siteUrl, RTMP_PATTERN)){ //only for svtplay.se
                            DefaultTableModel defModel = (DefaultTableModel)jTable1.getModel();
                           
                            dObjects[0] = new DownloadableObjects(siteUrl, "unknown");
                            defModel.addRow(new Object[]{dObjects[0].getTitle(), dObjects[0].getAddress(), dObjects[0].getBits(), dObjects[0].getStatus()});

                            jTable1.setEnabled(true);
                            stopBusyIcon();
                            jFindButton.setEnabled(true);
                            return;
                        }

                        curSite = new URL(siteUrl);
                        BufferedReader in = new BufferedReader(new InputStreamReader(curSite.openStream()));
                        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(S.INDEX_FILE));
                        int inputLine;

                        while ((inputLine = in.read()) != -1){
                            out.write(inputLine);
                            //System.out.println(inputLine);
                        }
                        out.flush();
                        out.close();
                        in.close();

                    } catch (UnknownHostException ex) {
                        showLine(new String[]{"error"}, "Site not found!");
                        jTable1.setEnabled(false);
                        stopBusyIcon();
                        jFindButton.setEnabled(true);
                        return;
                    } catch (IOException ex){
                        showLine(new String[]{"error"}, ex.getMessage());
                        jTable1.setEnabled(false);
                        stopBusyIcon();
                        jFindButton.setEnabled(true);
                        return;
                    }catch (IllegalArgumentException ex){
                        showLine(new String[]{"error"}, ex.getMessage());
                        jTable1.setEnabled(false);
                        stopBusyIcon();
                        jFindButton.setEnabled(true);
                        return;
                    }catch (Exception ex){ // other exceptions
                        showLine(new String[]{"error"}, "No video link found(1)!");
                        PlayDownloaderApp.logger.log(Level.SEVERE, null, ex);
                        jTable1.setEnabled(false);
                        stopBusyIcon();
                        jFindButton.setEnabled(true);
                        return;
                    }

                    LinkFinder lf;
                    if(SVT_PATTERN.matcher(siteUrl).find()){
                        lf = new LinkFinder();
                        found = lf.find(LinkFinder.SVT, jTable1);
                        //found = readIndexFileSVT();
                    }
                    else if(UR_PATTERN.matcher(siteUrl).find()){
                        lf = new LinkFinder();
                        found = lf.find(LinkFinder.UR, jTable1);
                        //found = readIndexFileUR();
                    }
                    else if(TV4PLAY_PATTERN.matcher(siteUrl).find()){
                        lf = new LinkFinder();
                        found = lf.find(LinkFinder.TV4, jTable1);
                        //found = readIndexFileTV4();//TODO: fix this method
                    }
                    else
                        PlayDownloaderApp.logger.log(Level.INFO, "No download support for the given site/link!");
                }


                if(found == 0){
                    showLine(new String[]{"error"}, "Paste the video link into the address bar!");
                    jTable1.setEnabled(false);
                }
                if(found == -1){
                    showLine(new String[]{"error"}, "No video link found(2)!");
                    jTable1.setEnabled(false);
                }
                jFindButton.setEnabled(true);
                stopBusyIcon();
            }
        }).start();
    }//GEN-LAST:event_jButtonFind

    /**
     * Converts a link from playrapport.se to a link from svtplay.se
     * @param link The link to be converted
     * @return returns the converted link
     */
    private String playrapportToSvtplay(String link){
        String tmp = "";
        Pattern numberPattern = Pattern.compile("\\d+");
        Matcher numberMatcher = numberPattern.matcher(link);
        numberMatcher.find();
        tmp = numberMatcher.group();

        return "http://svtplay.se/v/" + tmp;
    }

    private boolean isDirectLink(String link, Pattern PATTERN){
        Matcher linkMatcher = PATTERN.matcher(link);
        return linkMatcher.matches() ? true : false;
    }

    private void clearTableData(){
        ((DefaultTableModel)jTable1.getModel()).setNumRows(0);
        jTable1.setEnabled(false);
    }

    private void showLine(String[] title, String line){
        JOptionPane.showMessageDialog(mainPanel, line);
    }

    /**
     * Clear button, clears table-data, address bar and deletes the index.htm file.
     * @param evt
     */
    private void jButtonClear(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonClear
        //showLine(tableTitles, "");
        clearTableData();
        jTextField1.setText("");
        String curDir = System.getProperty("user.dir");
        File indexFile = new File(curDir + "\\" + S.INDEX_FILE);
        indexFile.delete();
        jFindButton.setEnabled(true);
    }//GEN-LAST:event_jButtonClear

    private void jButtonDownload(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDownload
        startNewDownload();
    }//GEN-LAST:event_jButtonDownload

    public void startNewDownload(){
        new DownloadThread(dObjects, jTable1, progressBar, mainPanel).start();
    }
    /**
     * Set the folder to download into
     * @param evt
     */
    private void jButtonBrowse(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBrowse
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if(fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
            jTextField2.setText(saveFolder = fc.getSelectedFile().getPath());
        prefs.put(S.PREF_SAVE_FOLDER, saveFolder);
    }//GEN-LAST:event_jButtonBrowse

    private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyPressed
        if(evt.getKeyCode() == KeyEvent.VK_ENTER && jFindButton.isEnabled()){
            jButtonFind(null);
        }
    }//GEN-LAST:event_jTextField1KeyPressed

    private void proxySettingsMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_proxySettingsMenuItemActionPerformed
        proxySettings = new SettingsFrame();
        proxySettings.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                applySettings();
            }
        });
        proxySettings.setVisible(true);
    }//GEN-LAST:event_proxySettingsMenuItemActionPerformed

    private void showLogView_MenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showLogView_MenuItemActionPerformed
        new LogFrame().setVisible(true);
    }//GEN-LAST:event_showLogView_MenuItemActionPerformed

    /**
     *
     */
    public void openSelectedItems(){
        for(int curIndex: jTable1.getSelectedRows()){
            try {
                Desktop.getDesktop().open(new File(saveFolder + "/" + dObjects[curIndex].getTitle()));
            } catch (IOException ex) {
                PlayDownloaderApp.logger.log(Level.SEVERE, null, ex);
            } catch (IllegalArgumentException ex){
                String directorySlash = "/";
                if(S.OS_NAME == S.OS_WINDOWS){
                    directorySlash = "\\";
                }
                showLine(null, "Could not find file: \"" + saveFolder + directorySlash + dObjects[curIndex].getTitle() + "\"");
            }
        }
    }

    /**
     *
     */
    public void deleteSelectedFiles(){
        for(int curIndex: jTable1.getSelectedRows()){
            if(new File(saveFolder + "/" + dObjects[curIndex].getTitle()).delete()){
                dObjects[curIndex].setStatus(DownloadableObjects.STATUS_NA);
                jTable1.setValueAt(null, curIndex, 4);
                jTable1.setValueAt(dObjects[curIndex].getStatus(), curIndex, 3);
            }else{
                String directorySlash = "/";
                if(S.OS_NAME == S.OS_WINDOWS){
                    directorySlash = "\\";
                }
                showLine(null, "Could not find file: \"" + saveFolder + directorySlash + dObjects[curIndex].getTitle() + "\"");
            }
        }
    }

    class PopupClickListener extends MouseAdapter{
        @Override
        public void mousePressed(MouseEvent e){
            if(e.isPopupTrigger())
                doPop(e);
        }

        @Override
        public void mouseReleased(MouseEvent e){
            if(e.isPopupTrigger())
                doPop(e);
        }

        @Override
        public void mouseClicked(MouseEvent e){
            if(e.getClickCount() == 2 && e.getComponent() instanceof JTable){
                int rowIndex = jTable1.getSelectedRow();
                if(jTable1.getValueAt(rowIndex, 3).equals(DownloadableObjects.STATUS_DOWNLOADED)){
                    openSelectedItems();
                }else if (!jTable1.getValueAt(rowIndex, 3).equals(DownloadableObjects.STATUS_DOWNLOADING)){
                    new DownloadThread(dObjects, jTable1, progressBar, mainPanel).start();
                }
            }
        }

        private void doPop(MouseEvent e){
            JPopupMenu menu = null;
            if(e.getComponent() instanceof JTextField){
                menu = new PopupMenu();
            }else if(e.getComponent() instanceof JTable){
                menu = new TablePopupMenu(jTable1, dObjects, PlayDownloaderView.this);
            }
            menu.show(e.getComponent(), e.getX(), e.getY());
        }
    }

    class PopupMenu extends JPopupMenu{
        //JMenuItem undo;
        JMenuItem copy;
        JMenuItem delete;
        JMenuItem selectAll;
        JMenuItem paste;
        JMenuItem cut;
        MenuItemActionListener aListener = new MenuItemActionListener();

        public PopupMenu(){
            //undo = new JMenuItem("Undo");
            cut = new JMenuItem("Cut");
            copy = new JMenuItem("Copy");
            paste = new JMenuItem("Paste");
            delete = new JMenuItem("Delete");
            selectAll = new JMenuItem("Select All");

            cut.addActionListener(aListener);
            copy.addActionListener(aListener);
            paste.addActionListener(aListener);
            delete.addActionListener(aListener);
            selectAll.addActionListener(aListener);

            if(getClipboardContents().equals(""))
                paste.setEnabled(false);

            String selectedText = jTextField1.getSelectedText();
            if(selectedText == null){
                copy.setEnabled(false);
                delete.setEnabled(false);
                cut.setEnabled(false);
            }
           
            //add(undo);
            //addSeparator();
            add(cut);
            add(copy);
            add(paste);
            add(delete);
            addSeparator();
            add(selectAll);
        }
    }

    class MenuItemActionListener implements ActionListener{
        private static final int PASTE = 1, CUT = 2, DELETE = 3;
        public void actionPerformed(ActionEvent e) {
            if(e.getActionCommand().equals("Paste")){
                pasteCutDelete(PASTE);
            }else if(e.getActionCommand().equals("Cut")){
                pasteCutDelete(CUT);
            }else if(e.getActionCommand().equals("Copy")){
                setClipboardContents(jTextField1.getSelectedText());
            }else if(e.getActionCommand().equals("Delete")){
                pasteCutDelete(DELETE);
            }else if(e.getActionCommand().equals("Select All")){
                jTextField1.selectAll();
            }
        }

        private void pasteCutDelete(int pasteCutDelete){
            int selectStart = jTextField1.getSelectionStart();
            int selectEnd   = jTextField1.getSelectionEnd();
            String firstPart = "";
            String lastPart = "";

            try {
                firstPart = jTextField1.getText(0, selectStart);
                lastPart = jTextField1.getText(selectEnd, jTextField1.getText().length()-selectEnd);
            } catch (BadLocationException ex) {
                PlayDownloaderApp.logger.log(Level.SEVERE, null, ex);
            }
            if(pasteCutDelete == PASTE){//Paste
                jTextField1.setText(firstPart + getClipboardContents() + lastPart);
            }else if(pasteCutDelete == CUT){//Cut
                setClipboardContents(jTextField1.getSelectedText());
                jTextField1.setText(firstPart + lastPart);
            }else if(pasteCutDelete == DELETE){//Delete
                jTextField1.setText(firstPart + lastPart);
            }
        }
    }

    /**
    * Get the String residing on the clipboard.
    *
    * @return any text found on the Clipboard; if none found, return an
    * empty String.
    */
    public String getClipboardContents() {
        String result = "";
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        //odd: the Object param of getContents is not currently used
        Transferable contents = clipboard.getContents(null);
        boolean hasTransferableText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor);

        if(hasTransferableText){
          try {
            result = (String)contents.getTransferData(DataFlavor.stringFlavor);
          }
          catch(UnsupportedFlavorException ex){
            //highly unlikely since we are using a standard DataFlavor
            PlayDownloaderApp.logger.log(Level.SEVERE, null, ex);
          }
          catch(IOException ex){
            PlayDownloaderApp.logger.log(Level.SEVERE, null, ex);
          }
        }
        return result;
    }

    /**
    * Place a String on the clipboard, and make this class the
    * owner of the Clipboard's contents.
    */
    public void setClipboardContents(String aString){
        StringSelection stringSelection = new StringSelection(aString);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(stringSelection, new ClipboardOwner() {
            public void lostOwnership(Clipboard clipboard, Transferable contents) {
                //do nothing
            }
        });
    }

    public void stopSelectedDownloadProcess(){
        for(int curIndex: jTable1.getSelectedRows()){
            Process curProc = dObjects[curIndex].getProcess();
            if(curProc != null){
                curProc.destroy();
                dObjects[curIndex].setStatus(DownloadableObjects.STATUS_CANCELED);
                jTable1.setValueAt(dObjects[curIndex].getStatus(), curIndex, 3);
                progressBar.setVisible(false);
            }
        }
    }

    private void startBusyIcon(){
        if (!busyIconTimer.isRunning()){
            statusAnimationLabel.setIcon(busyIcons[0]);
            busyIconIndex = 0;
            busyIconTimer.start();
        }

        /*Status_Task task = new Status_Task();
        task.addPropertyChangeListener(taskListener);
        task.execute();*/
    }

    private void stopBusyIcon(){
        busyIconTimer.stop();
        statusAnimationLabel.setIcon(idleIcon);
    }

    private void checkOS(){
        String osName = System.getProperty("os.name");
        //String osArch = System.getProperty("os.arch");
        //String osVers = System.getProperty("os.version");

        String javaVersion = System.getProperty("java.runtime.version");
        String javaVendor = System.getProperty("java.vm.vendor");

        PlayDownloaderApp.logger.log(Level.CONFIG, "Found os.name: {0}", osName);
        PlayDownloaderApp.logger.log(Level.CONFIG, "Found java version: {0}", javaVersion);
        PlayDownloaderApp.logger.log(Level.CONFIG, "Found java vendor: {0}", javaVendor);
        try{
            float jVersion = Float.parseFloat(javaVersion.substring(0, 3));
            if(jVersion < 1.6){
                PlayDownloaderApp.logger.log(Level.WARNING, "Java version must be atleast 1.6.");
            }
        }catch(NumberFormatException e){
            PlayDownloaderApp.logger.log(Level.WARNING, "Error parsing java version! {0}", javaVersion);
        }

        if(IS_WINDOWS_PATTERN.matcher(osName).find()){
            S.OS_NAME = S.OS_WINDOWS;
        }else if(IS_LINUX.matcher(osName).find()){
            S.OS_NAME = S.OS_LINUX;
        }else if(IS_MAC_PATTERN.matcher(osName).find()){
            S.OS_NAME = S.OS_MAC;
        }else{
            int out = JOptionPane.showConfirmDialog(mainPanel, "Your OS is not supported!\n\nRun anyway?\n\n", "Unsupported OS!", JOptionPane.YES_NO_OPTION);
            PlayDownloaderApp.logger.log(Level.WARNING, "OS not supported, run anyway?");
            if(out == 1){
                PlayDownloaderApp.logger.log(Level.INFO, "Exiting!");
                System.exit(0);
            }else{
                PlayDownloaderApp.logger.log(Level.WARNING, "Runing with default OS");
                S.OS_NAME = S.OS_WINDOWS;
            }// set the OS to windows if the os name was not supported or correctly detected
        }

        /*
        showLine(new String[]{"error"},
                "OS Name: " + osName +
                "\nOS Architecture: " + osArch +
                "\nOS Version: " + osVers);*/
    }

    private void applySettings(){
        prefs = null;
        prefs = Preferences.userNodeForPackage(PlayDownloaderApp.class);

        if(prefs.getBoolean(S.PREF_USE_PROXY, false)){
            String proxyHost = prefs.get(S.PREF_PROXY_HOST_HTTP, "null");
            if(!proxyHost.equals("null")){
                int proxyPort = prefs.getInt(S.PREF_PROXY_PORT_HTTP, 8080);

                System.setProperty("http.proxyHost", proxyHost);
                System.setProperty("http.proxyPort", ""+proxyPort);
                System.setProperty("http.proxySet", "true");

                PlayDownloaderApp.logger.log(Level.CONFIG, "Is using proxy on: {0}:{1}", new Object[]{System.getProperty("http.proxyHost"), System.getProperty("http.proxyPort")});
            }
        }else{
            PlayDownloaderApp.logger.log(Level.CONFIG, "Doesn't use proxy...");
        }
    }

    /*class Status_Task extends SwingWorker<Void, Void>{

        @Override
        protected Void doInBackground() throws Exception {


            //do something
            return null;
        }

        @Override
        public void done(){
            Toolkit.getDefaultToolkit().beep();
            //Enable the pressed button!?
            getRootPane().setCursor(null);
            //turn off the wait cursor
            //taskOutput.append("Done!\n"); //whats this for?
        }

    }*/

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jFindButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JMenuItem proxySettingsMenuItem;
    private javax.swing.JMenuItem showLogView_MenuItem;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JMenu viewMenu;
    // End of variables declaration//GEN-END:variables

    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;

    private JDialog aboutBox;
    private JFrame proxySettings;

    private Preferences prefs;
    private String siteUrl = "";
    private String saveFolder = "";
    public static DownloadableObjects[] dObjects;
    private Pattern RTMP_PATTERN = Pattern.compile("(rtmp://|rtmpe://|rtm://)(\\w|\\x2f|\\x2e|\\x5f|\\x2d)+");
    //private Pattern HTTP_PATTERN = Pattern.compile("http://(\\w|\\x2f|\\x2e|\\x5f|\\x2d)+(\\x2eflv)");


    private Pattern SVT_PATTERN = Pattern.compile("http://(www.)?(svtplay|playrapport).se(\\w|\\x2f|\\x2e|\\x5f|\\x2d)+");
    private Pattern PLAYRAPPORT_PATTERN = Pattern.compile("http://(www.)?playrapport.se(\\w|\\x2f|\\x2e|\\x5f|\\x2d)+");
    private Pattern UR_PATTERN = Pattern.compile("http://(www.)?urplay.se(\\w|\\x2f|\\x2e|\\x5f|\\x2d)+");
    private Pattern TV4PLAY_PATTERN = Pattern.compile("http://(www.)?tv4play.se(\\w|\\x2f|\\x2e|\\x5f|\\x2d)+");

    private Pattern IS_WINDOWS_PATTERN = Pattern.compile("(w|W)indows");
    private Pattern IS_MAC_PATTERN = Pattern.compile("(m|M)ac");
    private Pattern IS_LINUX = Pattern.compile("(l|L)inux");
}
TOP

Related Classes of play_downloader.PlayDownloaderView$MenuItemActionListener

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.