#!/usr/bin/python
# -*- coding: utf-8 -*-

# YoutubeDl, Download videos from Youtube.
# This is a part of the external applets for Cairo-Dock
# Copyright: (C) 2012 Brian Whitelock
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# http://www.gnu.org/licenses/licenses.html#GPL
#

try:
	import gobject
except:
	from gi.repository import GObject as gobject

from Configuration import Configuration
from CDApplet import CDApplet, _
import os, subprocess
import multiprocessing, Queue, random
from myYoutubeDownloader import YoutubeDownloader

# if pynotify is available use it otherwise use popup messages.
import userAlerts as alerts

# if tkinter is available use it otherwise use popup messages.
import fileDialogs as dialogs
from urlListEdit import urlListEditor

# all constant types are placed in one file and used as needed.
from constantTypes import PopupTypes
from constantTypes import menuEntries

#Get the clipboard text
from getClipboardText import getClipboardText

class Applet(CDApplet):

	def __init__(self):
	    self.__interval = 60000 # 1 minute (in millisecondes)
	    self.__timerId = None
            self.work_queue = multiprocessing.Queue(1)
            self.result_queue = multiprocessing.Queue(2)
            self.result = ['Idle','Idle','Idle','Idle']
            self.activeDownload = False
            self.urlList = list()
            self.currentDialog = PopupTypes.infoDialog
            self.resultSummary = 'No Data'
            self.listAltered = False
            self.__debugMode = False
            self.validVideoDirectory = False
            self.validUrlDirectory = False
            self.startDownloader()
            CDApplet.__init__(self)

        def startDownloader(self):
            # create the background downloader
            self.downloadManager = YoutubeDownloader(self.work_queue, self.result_queue)
            # Uncomment the following line to trace debug actions in the console.
            #self.downloadManager.debug()
            # start the background downloader
            self.downloadManager.start()

        def begin(self):

            """
                First method ran by CairoDock when applet is launched.
            """
            if self.__showProgressOnIcon:
	        self.icon.SetQuickInfo(str(self.result[0]))
            else:
	        self.icon.SetQuickInfo('')
            # Uncomment the following line to trace debug actions in the console.
            #self.debug()
            self.reload()
	    self.__setTimer()

        def end(self):
            # try to end the background downloader
            self.downloadManager.join(1)
            #If the downloader is still active then terminate it
            if self.downloadManager.is_alive():
                self.downloadManager.terminate()
                self.downloadManager.join(1)
	
	def on_click(self, iState):
	    if len(self.urlList) > 0:
	        if self.useListView and (len(self.urlList) > self.urlListExceeds):
	            endingCharacter = ';'
                else:
	            endingCharacter = '\n'

                tempString = '          Current Download' + endingCharacter
                if self.activeDownload:
                    tempString = tempString + '\n      -> '.join(self.urlList[0]) 
                    rangeStart = 1
                else:
                    tempString = tempString + '    -> None' + endingCharacter
                    rangeStart = 0
                tempString = tempString + '\n          Current URL List' + endingCharacter
                if len(self.urlList) > rangeStart:
                    tempList = list()
                    for item in range(rangeStart,len(self.urlList)):
                        tempList.append('\n      -> '.join(self.urlList[item]))
                    self.messageDebug(tempString)
                    tempString = tempString + endingCharacter.join(tempList)
                    self.messageDebug(tempString)
                else:
                    tempString = tempString + '    -> Empty'
                    self.messageDebug(tempString)
	        if self.useListView and (len(self.urlList) > self.urlListExceeds):
                    self.icon.PopupDialog( {"message" : "Youtube Download URL List",
                    "buttons" : "ok",  
                    "icon" : "gtk-stock-edit"},
                    {"visible" : True,
                     "widget-type" : "list",
                     "multi-lines" : True,
                     "editable" : False,
                     "values" : tempString})
                else:
                    self.icon.PopupDialog( {"message" : tempString,
                    "icon" : "gtk-edit"},
                    {"visible" : True,
                     "multi-lines" : True,
                     "editable" : False, })
                self.currentDialog = PopupTypes.infoDialog
            else:
                self.urlManualEntry()


        def urlManualEntry(self):
                defaultText = getClipboardText()
                dialog_attributes = {
                        'message'    : "Please enter URL:",
                        'use-markup' : True,
                        'buttons'    : 'ok;cancel' }
                widget_attributes = {
                        'widget-type'   : 'text-entry',
                        'initial-value' : defaultText,
                        'multi-lines'   : False}
                self.icon.PopupDialog (dialog_attributes, widget_attributes)
                self.currentDialog = PopupTypes.urlManualEntry

        def editURLs(self):
            urlEdit=urlListEditor(self.urlList).run()
            if urlEdit:
                self.urlList[:] = urlEdit
            else:
                if urlEdit is None:
                    self.icon.PopupDialog( {"message" : "python-tk not installed, Editing not possible",
                    "icon" : "gtk-dialog-info"},
                    {"visible" : True,
                     "multi-lines" : True,
                     "editable" : False, })
                    self.currentDialog = PopupTypes.infoDialog
	    return True

	def on_middle_click(self):
            if self.__actionOnMiddleClick == 'Open Video Folder':
                if self.validVideoDirectory:
                    subprocess.call(['xdg-open',self.__videos_directory], shell=False)
                else:
                    tempString = "Error: Video Directory not writable.\n Please make sure directory is valid and writable"
                    self.icon.PopupDialog( {"message" : tempString,
                    "icon" : "gtk-stock-edit"},
                    {"visible" : True,
                     "multi-lines" : True,
                     "editable" : False, })
                    self.currentDialog = PopupTypes.infoDialog
            else:
                alerts.doUserAlert(self,self.resultSummary,4)
            return True
	
	def reload(self):

            if self.isWritable(self.__videos_directory):
                self.validVideoDirectory = True
            else:
                self.validVideoDirectory = False
                self.__startDownloads = False
                self.__videos_directory = ''
                tempString = "Error: Video Directory not writable.\n Please make sure directory is valid and writable"
                self.icon.PopupDialog( {"message" : tempString,
                "icon" : "gtk-stock-edit"},
                {"visible" : True,
                 "multi-lines" : True,
                 "editable" : False, })
                self.currentDialog = PopupTypes.infoDialog

            if self.isWritable(self.__urlList_directory):
                self.validUrlDirectory = True
            else:
                self.validUrlDirectory = False
                tempString = "Warning:  URL Directory not writable. \nPlease make sure directory is valid and writable"
                self.icon.PopupDialog( {"message" : tempString,
                "icon" : "gtk-stock-edit"},
                {"visible" : True,
                 "multi-lines" : True,
                 "editable" : False, })
                self.currentDialog = PopupTypes.infoDialog

            if self.__showProgressOnIcon:
	        self.icon.SetQuickInfo(str(self.result[0]))
	
	def doUpdate(self):
	    """
	    Update the current status for downloads.
	    """
            if self.activeDownload:
                self.messageDebug("doUpdate: active downloads is true")
                try:
                    queueContents = self.result_queue.get_nowait()
                    if queueContents == 'DownloadComplete':
                        self.result = ['Idle','Idle','Idle','Idle']
                        self.activeDownload = False
                        if self.__showAlertDownloadComplete:
                            alerts.doUserAlert(self,"Download " + self.urlList[0][1] + " is Complete",4)
                        del self.urlList[0]
                        self.messageDebug("doUpdate: result_queue reports DownloadComplete")
                    elif queueContents == 'DownloadAborted':
                        self.result = ['Idle','Idle','Idle','Idle']
                        self.activeDownload = False
                        if self.__showAlertDownloadAbort:
                            alerts.doUserAlert(self,"Download " + self.urlList[0][1] + " has been aborted",4)
                        del self.urlList[0]
                        self.messageDebug("the length of url list is: " + str(len(self.urlList)))
                        self.messageDebug("doUpdate: result_queue reports DownloadAborted")
                    else:
                        self.result = queueContents.split(';')
                        self.resultSummary = "%s\n%s of %s @ %s eta: %s" % (self.urlList[0][1],self.result[0],self.result[1],self.result[2],self.result[3])
                        self.messageDebug("doUpdate: result summary:\n"+self.resultSummary)
                except Queue.Empty:
                    self.result = ['Empty','Empty','Empty','Empty']
                    self.messageDebug("doUpdate: Queue is empty")
            else:
                self.messageDebug("doUpdate: Active Downloads is false")
                self.resultSummary = "No Active Downloads"
                if (len(self.urlList) > 0):
                    self.messageDebug("doUpdate: "+str(len(self.urlList))+" tems in url list")
                    if self.__startDownloads:
                        self.messageDebug("doUpdate: start Downloads is true")
                        self.messageDebug("doUpdate: Start Download:\n"+self.urlList[0][0])
                        self.startDownload(self.urlList[0][0])
                    else:
                        self.messageDebug("doUpdate: start Downloads is false")
                else:
                    self.listAltered = False
            if self.__showStatusOnIcon:
                self.icon.SetLabel(self.resultSummary)
            #update the quickinfo on Icon
            if self.__showProgressOnIcon:
	        self.icon.SetQuickInfo(str(self.result[0]))
            #Reset timer after doing update
	    self.__setTimer()

        def on_drop_data(self,cReceivedData): 
            if self.__showAlertAddURL:
                alerts.doUserAlert(self,"Added to queue list: "+cReceivedData,4)
            if (not self.activeDownload) and self.__startDownloads:
                self.messageDebug("onDropData: download immediately:\n"+str(cReceivedData))
                self.startDownload(cReceivedData)
            if cReceivedData.find('watch?v=') == (-1):
                fileName = "no filename maybe it is a playlist"
                self.messageDebug("onDropData: Found watch?v= in url")
            else:
                self.messageDebug("onDropData: didn't find watch?v= in url")
                p = subprocess.Popen(["./youtubedl.py","--get-filename","-itf","18",cReceivedData],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=False)
                fileName, errors = p.communicate()
                fileName=fileName.rstrip()
            self.urlList.append([str(cReceivedData),fileName])
            self.messageDebug("onDropData: New URL List:\n"+str(self.urlList))
            self.listAltered = True

        def startDownload(self, url):
            if self.validVideoDirectory:
                try:
                    self.work_queue.put(url)
                    self.messageDebug("startDownload: put url on work queue:\n"+url)
                    if self.__showAlertStartDownloads:
                        alerts.doUserAlert(self,"Starting Download: "+url,4)
                    self.activeDownload = True
                    self.result = ['Starting','Starting','Starting','Starting']
	            self.icon.SetQuickInfo(str(self.result[0]))
                except Queue.Full:
                    self.messageDebug("startDownload: work queue is full:\n"+url)
                    alerts.doUserAlert(self,"Can't Download: Queue is Full",4)

        def on_build_menu(self):
            self.messageDebug("onBuildMenu: context menu called")
            items = []
            if self.validVideoDirectory:
                if self.__actionOnMiddleClick == 'Open Video Folder':
                    items.append(
                    {"label": _("Open Video Folder") + " (" + _("middle-click") + ")",
                     "icon" : "gtk-open",
                     "id"   : menuEntries.openVideoFolder })
                else:
                    items.append(
                    {"label": _("Show Download Status") + " (" + _("middle-click") + ")",
                     "icon" : "gtk-info",
                     "id"   : menuEntries.showDownloadStatus })
            if self.activeDownload:
                items.append(
                {"label": "Abort current download",
                 "icon" : "gtk-cancel",
                 "id"   : menuEntries.abortDownload,
                 "tooltip" : _("Send abort signal to the downloader. There may be a delay") })
            if len(self.urlList) > 0:
                items.append(
                {"label": "Save current URL list", 
                 "icon" : "gtk-save",
                 "id"   : menuEntries.saveURLs })
                if not (self.activeDownload):
                    items.append(
                    {"label": "Clear current URL list", 
                     "icon" : "gtk-delete",
                     "id"   : menuEntries.clearURLs })
                    items.append(
                    {"label": "Edit current URL list", 
                     "icon" : "gtk-edit",
                     "id"   : menuEntries.editURLs })
            if len(self.urlList) == 0:
                items.append(
                {"label": "Load URL list from file", 
                 "icon" : "gtk-open", 
                 "id"   : menuEntries.loadURLs })
            if getClipboardText():
                items.append(
                {"label": "Add URL from clipboard", 
                 "icon" : "gtk-edit", 
                 "id"   : menuEntries.clipboardURL })
            if self.__startDownloads:
                items.append(
                {"label": "Pause Downloading", 
                 "icon" : "gtk-media-pause", 
                 "id"   : menuEntries.pauseDownload })
            else:
                if self.validVideoDirectory:
                    items.append(
                    {"label": "Enable Downloading", 
                     "icon" : "gtk-media-play", 
                     "id"   : menuEntries.enableDownload })
            self.icon.AddMenuItems(items)

        def on_menu_select(self,iNumEntry):
            self.messageDebug("onSelectMenu: "+str(iNumEntry)+" selected")
            if iNumEntry == menuEntries.abortDownload:
                self.icon.PopupDialog( {"message" : "Are you sure you want to cancel the current download?",  
             "buttons" : "ok;cancel",  
             "icon" : "gtk-cancel"},  
             {"visible" : True } )
                self.currentDialog = PopupTypes.confirmAbort
            elif iNumEntry == menuEntries.clearURLs:
                self.icon.PopupDialog( {"message" : "Are you sure you want to clear the current URL list?",  
             "buttons" : "ok;cancel",  
             "icon" : "gtk-delete"},  
             {"visible" : True } )
                self.currentDialog = PopupTypes.delList
            elif iNumEntry == menuEntries.editURLs:
                self.editURLs()
            elif iNumEntry == menuEntries.saveURLs:
                self.saveURLs()
            elif iNumEntry == menuEntries.loadURLs:
                self.loadURLs()
            elif iNumEntry == menuEntries.clipboardURL:
                self.urlManualEntry()
            elif iNumEntry == menuEntries.openVideoFolder:
                subprocess.call(['xdg-open',self.__videos_directory], shell=False)
            elif iNumEntry == menuEntries.showDownloadStatus:
                alerts.doUserAlert(self,self.resultSummary,4)
            elif iNumEntry == menuEntries.pauseDownload:
                self.__startDownloads = False
                message = "Downloading Paused"
                if self.activeDownload:
                    message = message+": Current download will complete. To stop it use the Download Abort"
                alerts.doUserAlert(self,message,5)
            elif iNumEntry == menuEntries.enableDownload:
                self.__startDownloads = True
                alerts.doUserAlert(self,"Downloading Enabled",5)
                if not (self.activeDownload):
                    if len(self.urlList) > 0:
                        self.startDownload(self.urlList[0][0])
                    else:
                        self.result = ['Enabling','Enabling','Enabling','Enabling']
	                self.icon.SetQuickInfo(str(self.result[0]))
            else:
                self.messageDebug("An unknown menu entry was received")

        def on_answer_dialog(self,button, userResponse): 
            if button == CDApplet.DIALOG_KEY_ENTER:
                button = 0
            if self.currentDialog == PopupTypes.confirmAbort:
                self.messageDebug("onAnswerDialog: confirm abort: "+str(button)+" "+str(userResponse))
                if button == 0:
                    self.work_queue.put('Abort')
                    self.result = ['Aborting','Aborting','Aborting','Aborting']
	            self.icon.SetQuickInfo(str(self.result[0]))
            elif self.currentDialog == PopupTypes.delList:
                self.messageDebug("onAnswerDialog: confirm delete: "+str(button)+" "+str(userResponse))
                if button == 0:
                    del self.urlList[:]
            elif self.currentDialog == PopupTypes.saveListFilename:
                self.messageDebug("onAnswerDialog: save list filename: "+str(button)+" "+str(userResponse))
                if button == 0:
                    fileName = os.path.abspath(self.__urlList_directory + "/" + userResponse)
                    self.saveTheList(fileName)
            elif self.currentDialog == PopupTypes.getListFilename:
                self.messageDebug("onAnswerDialog: get list filename: "+str(button)+" "+str(userResponse))
                if button == 0:
                    fileName = os.path.abspath(self.__urlList_directory + "/" + userResponse)
                    self.readTheList(fileName)
            elif self.currentDialog == PopupTypes.urlManualEntry:
                self.messageDebug("onAnswerDialog: URL Manual Entry: "+str(button)+" "+str(userResponse))
                if button == 0:
                    self.on_drop_data(userResponse)
            elif self.currentDialog == PopupTypes.infoDialog:
                self.messageDebug("onAnswerDialog: info dialog : "+str(button)+" "+str(userResponse))
            elif self.currentDialog == PopupTypes.showUrlList:
                self.messageDebug("onAnswerDialog: showUrlList : "+str(button)+" "+str(userResponse))
            else:
                self.messageDebug("onAnswerDialog: Unknown dialog : "+str(button)+" "+str(userResponse))

            self.currentDialog = PopupTypes.infoDialog

        def saveURLs(self):
            fileName=dialogs.saveUrlFilename(self.__urlList_directory)
            if fileName == None:
                self.messageDebug("returned filename is None")
                dialog_attributes = {
                        'message'    : "Please enter URL list filename to save",
                        'use-markup' : True,
                        'buttons'    : 'ok;cancel' }
                widget_attributes = {
                        'widget-type'   : 'text-entry',
                        'initial-value' : "",
                        'multi-lines'   : False}
                self.icon.PopupDialog (dialog_attributes, widget_attributes)
                self.currentDialog = PopupTypes.saveListFilename
            elif len(fileName) > 0:
                self.messageDebug("returned filename is: "+fileName)
                self.saveTheList(fileName)
            else:
                self.messageDebug("returned filename is 0 ")

        def loadURLs(self):
            fileName=dialogs.openUrlFilename(self.__urlList_directory)
            if fileName == None:
                self.messageDebug("returned filename is None")
                dialog_attributes = {
                        'message'    : "Please enter URL list file to open",
                        'use-markup' : True,
                        'buttons'    : 'ok;cancel' }
                widget_attributes = {
                        'widget-type'   : 'text-entry',
                        'initial-value' : "",
                        'multi-lines'   : False}
                self.icon.PopupDialog (dialog_attributes, widget_attributes)
                self.currentDialog = PopupTypes.getListFilename
            elif len(fileName) > 0:
                self.readTheList(fileName)
            else:
                self.messageDebug("returned filename is 0 ")

        def saveTheList(self,fileName):
                try:
                    saveFile = open(fileName, 'w')
                    self.icon.ShowDialog("Saving list",4)
                    for item in range(len(self.urlList)):
                        saveFile.write("{0}::{1}\n".format(self.urlList[item][0],self.urlList[item][1]))
                    saveFile.close()
                    self.listAltered = False
                except IOError:
                    tempString = "Error: Not able to save URL list file:\n" + fileName + "\nPlease make sure directory and filename are valid and writable"
                    self.icon.PopupDialog( {"message" : tempString,
                    "icon" : "gtk-stock-edit"},
                    {"visible" : True,
                     "multi-lines" : True,
                     "editable" : False, })
                    self.currentDialog = PopupTypes.infoDialog

        def readTheList(self,fileName):
                try:
                    del self.urlList[:]
                    self.urlList = [line.strip().split('::') for line in open(fileName)]
                    self.listAltered = False
                    self.messageDebug("new list is: ")
                    self.messageDebug(self.urlList)
                except IOError:
                    tempString = "Error: Not able to read URL list file:\n" + fileName + "\nPlease make sure directory and filename are valid and readable"
                    self.icon.PopupDialog( {"message" : tempString,
                    "icon" : "gtk-stock-edit"},
                    {"visible" : True,
                     "multi-lines" : True,
                     "editable" : False, })
                    self.currentDialog = PopupTypes.infoDialog

        def messageDebug(self, message):
            """
            Write debug message to console.
            """
            if self.__debugMode:
                print '<%s : %s>' % (self.cAppletName, message)

        def debug(self):
            """
            Call me one time in the beginning of your script. 
            If you are running Cairo-Dock from a console window, 
            you'll be able to see what I'm doing.
            """
            self.__debugMode = True


	def get_config(self, keyfile):
	    """
	    Reload the configuration.
	    """
	    interval = keyfile.getint('Configuration', 'interval')
	    self.__interval = interval * 1000 # convert in millisecondes.
	    self.__startDownloads = keyfile.getboolean('Configuration', 'startDownloads')
	    self.__showAlertStartDownloads = keyfile.getboolean('Configuration', 'showAlertStartDownloads')
	    self.__showAlertDownloadComplete = keyfile.getboolean('Configuration', 'showAlertDownloadComplete')
	    self.__showAlertDownloadAbort = keyfile.getboolean('Configuration', 'showAlertDownloadAbort')
	    self.__showAlertAddURL = keyfile.getboolean('Configuration', 'showAlertAddURL')
	    self.usePynotify = keyfile.getboolean('Configuration', 'usePynotify')
	    self.useListView = keyfile.getboolean('Configuration', 'useListView')
	    self.urlListExceeds = keyfile.getint('Configuration', 'urlListExceeds')
	    self.__actionOnMiddleClick = keyfile.get('Configuration', 'actionOnMiddleClick')
	    self.__showProgressOnIcon = keyfile.getboolean('Configuration', 'showProgressOnIcon')
	    self.__showStatusOnIcon = keyfile.getboolean('Configuration', 'showStatusOnIcon')
	    self.__videos_directory = keyfile.get('Configuration', 'videos_directory')
	    self.__urlList_directory = keyfile.get('Configuration', 'urlList_directory')
	    self.__setTimer()

            if not self.__videos_directory:
                p = subprocess.Popen(["xdg-user-dir","VIDEOS"],stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=False)
                directoryName, errors = p.communicate()
                directoryName=directoryName.rstrip()
                self.__videos_directory = os.path.abspath(directoryName)
                
            if not self.__urlList_directory:
                self.__urlList_directory = os.path.expanduser("~")
	
	def __setTimer(self):
	    """
	    Set the time between two checks.
	    """
	    self.__removeTimer()
	    #self.__timerId = timeout_add(self.__interval, self.doUpdate)
	    self.__timerId = gobject.timeout_add(self.__interval, self.doUpdate)
		
	def __removeTimer(self):
	    """
	    Properly remove the timer.
	    """
	    if self.__timerId != None:
	    	gobject.source_remove(self.__timerId)
	    	gobject.source_remove(self.__timerId)

        def isWritable(self, directory):
            try:
                tmp_prefix = "write_tester";
                count = 0
                filename = os.path.join(directory, tmp_prefix)
                while(os.path.exists(filename)):
                    filename = "{}.{}".format(os.path.join(directory, tmp_prefix),count)
                    count = count + 1
                f = open(filename,"w")
                f.close()
                os.remove(filename)
                return True
            except Exception as e:
                return False

############
### main ###
############
if __name__ == '__main__':
        Applet().run()

