Friday, February 17, 2012

A cheesy application to check for new podcasts and transfer them to my Walkman

#! /usr/bin/env python

""" Version 0.02.02
        Just a simple file manipulation tool.
        Used in this instance as a Podcast updater.
        Still stuff to do - see TODO file"""

import sys, os, time, stat, shutil
import tkFileDialog, ttk, tkMessageBox
from Tkinter import *



class Application(Frame):

        import ConfigParser
        # Set these until settings are done - then set them with setup function
        sourceList = targetList = deviceList=[]
        targetList = []
        deviceList = []
        dirList = []
        workList = []

        ask = IntVar
        empty = IntVar
        statusVar = StringVar(Tk())
        sVar = StringVar()
        tVar = StringVar()
        dVar = StringVar()
        changeMade = FALSE
        now = time.time()
        then = 0
        home= os.environ['HOME']+'/'
        cfg = ConfigParser.RawConfigParser()

        def __init__(self,master=None):
                Frame.__init__(self, master)
                statusVar = StringVar()
               
                self.pack()
                statusVar = ""
              
                self.createWidgets()
                self.startup()
                self.refresh()           
               

        def startup(self):
                pass
                #Check for config file
                self.cfg.read(self.home+"/.config/podcm.conf")

                tmpstring=(self.cfg.get('cbox','cboxSource'))
                self.sourceList=tmpstring.split(',')
                self.sourceCombobox ['values'] = self.sourceList

                tmpstring=(self.cfg.get('cbox','cboxTarget'))
                self.targetList=tmpstring.split(',')
                self.targetCombobox ['values'] = self.targetList

                tmpstring=(self.cfg.get('cbox','cboxDevice'))
                self.deviceList=tmpstring.split(',')
                self.deviceCombobox ['values'] = self.deviceList

                self.sourceCombobox.set(self.sourceList[0])
                self.targetCombobox.set(self.targetList[0])
                self.deviceCombobox.set(self.deviceList[0])

                tmp=(self.cfg.getboolean('chkbuttons','ask'))
                if tmp:
                        self.askCheck.select()
                else:
                        self.askCheck.deselect()

                tmp=(self.cfg.getboolean('chkbuttons','empty'))
                if tmp:
                        self.emptyCheck.select()
                else:
                        self.emptyCheck.deselect()

                self.then = (self.cfg.get('itime', 'last'))

               

        def refresh(self):
                pass

                self.sourceCombobox.set(self.sourceList[0])
                self.targetCombobox.set(self.targetList[0])
                self.deviceCombobox.set(self.deviceList[0])
                self.update()
                podDir = self.sourceCombobox.get()
                targetDir = self.targetCombobox.get()
               
                self.statusVar.set("Checking for new files...")

                for f in os.listdir(podDir):
                        ## check is DIR?
                        g = os.path.join(podDir,f)
                        mode = os.stat(g).st_mode
                        t=0
                        for h in os.stat(g):
                                if (t == 9) and (self.now -h < 86400) and stat.S_ISDIR(mode) and (g != targetDir):
                                        ##print (now - h,f)
                                        self.dirList.append(f)
                                t=t+1
                self.txt.insert (END,"Folders altered in the last 24 hours in %s :\n" % podDir)

                for f in self.dirList:
                        self.txt.insert(END,f+'\n')

                for f in self.dirList:                   ## for each directory in the dirList
                        g = os.path.join(podDir,f)          # append the name of the dir to the working pod dir
                        ##print ("try this:",os.listdir(g)[9])  -----> didn't work
                        for h in os.listdir(g):                 # for each file in the directory
                                j = os.path.join(g,h)           # change g so it now is the path + file
                                mode = os.stat(j).st_mode       # get the type of file
                                t = 0                           # my counter because position 9 is itime
                                ## print("Try this #2 ",os.stat(j)[9]) ---> worked but...
                                for i in os.stat(j):
                                        ##print f,j,h,i
                                        if (t == 9) and (self.now - i < 86400) and (stat.S_ISREG(mode)):
                                                self.workList.append(j)
                                        t=t+1

                self.txt.insert(END,"\nNew Files:\n")

                for f in self.workList:
                        self.txt.insert(END,f+'\n')

                self.statusVar.set("These are the files that have been changed in the last 24 hours.")
               

        def execute(self):
                pass
                podDir = self.sourceCombobox.get()
                targetDir = self.targetCombobox.get()

               
                if self.empty:
                        pass
                        self.statusVar.set("Clearing Target Directory.")
                        for f in os.listdir(targetDir):
                                g = os.path.join(targetDir,f)
                                os.remove(g)

                self.update()       

                self.statusVar.set("Copying Files Into Target Directory.")
                for f in self.workList:
                        self.update()
                        self.statusVar.set("Copying %s " %f)
                        shutil.copy2(f,targetDir)
                       

                self.statusVar.set("Copy Complete.")
                        

        def save(self):
                pass
                print ("save function")
                ##cfg.set(
                self.cfg.set('chkbuttons','ask',self.ask)
                self.cfg.set('chkbuttons','empty',self.empty)
                with open(self.home+"/.config/podcm.conf",'wb') as configfile:
                        self.cfg.write(configfile)


        def end(self):
                pass
                if (self.changeMade):
                        mb = tkMessageBox.askyesnocancel(
                        message = "Do you wish to save your configuration before quitting?",
                        icon = 'question',
                        title = "Save current configuration?")

                        if mb == None:
                                return
                        elif mb == True:
                                self.save()
                        elif mb == False:
                                self.quit()

                else:
                        self.destroy()
                        self.quit()
               
               
        def copy2device(self):
                pass
                self.execute
                deviceDir = self.deviceCombobox.get()
                if (self.workList):
                        for f in self.workList:
                                self.update()
                                self.statusVar.set("Copying %s " %f)
                                shutil.copy2(f,deviceDir)
                self.statusVar.set("Copy Complete.")

        def sourceCboxChanged(self,t):
                ## No idea why the second argument is required, but it will complain if it's not there
                self.changeMade = True

        def targetCboxChanged(self,t):
                self.changeMade = True

        def deviceCboxChanged(self,t):
                self.changeMade = True

        def askCheckChanged(self):
                self.changeMade = True
                self.ask=not(self.ask)
       
               
        def emptyCheckChanged(self):
                self.changeMade = True
                self.empty=not(self.empty)
               
        def source(self):
                pass
                ## options defaultextension (string), filetypes (list), initialdir (string), initialfile (string)/
                ## parent (widget), title(string)
                # adjust later so that list is only 5 deep
                b = tkFileDialog.askdirectory(initialdir=self.sourceCombobox.get())
                self.sourceList=[b]+self.sourceList
                self.sourceCombobox ['values'] = self.sourceList
                self.refresh()
                self.changeMade = TRUE

        def target(self):
                pass
                b = tkFileDialog.askdirectory(initialdir=self.targetCombobox.get())
                self.targetList=[b]+self.targetList
                self.targetCombobox ['values'] = self.targetList
                self.targetCombobox.current(0)
                self.changeMade = TRUE

        def device(self):
                pass
                b = tkFileDialog.askdirectory(initialdir=self.deviceCombobox.get())
                self.deviceList=[b]+self.deviceList
                self.deviceCombobox ['values'] = self.deviceList
                self.deviceCombobox.current(0)
                self.changeMade = TRUE
               
        def createWidgets(self):
                self.frame0 = Frame(self)
                self.frame0.pack()

                self.executeButton = Button(self.frame0, text ="Execute", command=self.execute)
                self.executeButton.grid(row=6, column=2,sticky=E)
                self.executeButton.focus_set()
               
                self.copy2deviceButton = Button(self.frame0, text="Copy to Device", command=self.copy2device)
                self.copy2deviceButton.grid(row=6, column=1)

                self.quitButton = Button(self.frame0, text ="Quit",command=self.end)
                self.quitButton.grid(row=6, column=3,sticky=E)

                self.saveButton = Button(self.frame0, text ="Save Preferences",command=self.save)
                self.saveButton.grid(row=6, column=0)

                self.sourceButton = Button(self.frame0, text = "Change Source", command=self.source)
                self.sourceButton.grid(row=0, column=3)

                self.targetButton = Button(self.frame0, text ="Change Target", command=self.target)
                self.targetButton.grid(row=1, column=3)

                self.deviceButton = Button(self.frame0, text ="Change Device", command=self.device)
                self.deviceButton.grid(row=2, column=3)

                self.sourceCombobox = ttk.Combobox(self.frame0,width=50, textvar=self.sVar, values=self.sourceList)
                self.sourceCombobox.grid(row=0,column=0,columnspan=3,sticky=W)
                self.sourceCombobox.bind('<<ComboboxSelected>>', self.sourceCboxChanged)

                self.targetCombobox = ttk.Combobox(self.frame0,width=50, textvar=self.tVar, values=self.targetList)
                self.targetCombobox.grid(row=1,column=0,columnspan=3,sticky=W)
                self.targetCombobox.bind('<<ComboboxSelected>>', self.targetCboxChanged)
               
                self.deviceCombobox = ttk.Combobox(self.frame0,width=50, textvar=self.dVar, values=self.deviceList)
                self.deviceCombobox.grid(row=2,column=0,columnspan=3,sticky=W)
                self.deviceCombobox.bind('<<ComboboxSelected>>', self.deviceCboxChanged)
               
                self.askCheck = Checkbutton(self.frame0, text="Don't ask next time",
                                            command = self.askCheckChanged)
                self.askCheck.grid(row=3, column=0, columnspan=2,sticky=W)

                self.emptyCheck = Checkbutton(self.frame0, text="Empty target directory first?", variable=self.empty,
                                              command = self.emptyCheckChanged)
                self.emptyCheck.grid(row=4, column=0, columnspan=2,sticky=W)

                self.txt = Text(self.frame0)
                self.txt.grid(row=5,columnspan=4)

                self.status=Label(self.frame0,textvariable=self.statusVar,height=2,wraplength=560,justify=LEFT)
                self.status.grid(row=7,columnspan=4)

## Start here
app=Application()
app.master.title("Podcast Mover")
app.master.geometry("600x580+20+20")

app.mainloop()

****************************************************
This was my first attempt at using settings (ConfigParser) so a config file is required
for the application to function. If there is no config file, the values should have defaults like ~.

And the ~/.config/podcm.conf file

[cbox]

cboxSource    :    /home/panchod/Audio/

cboxTarget    :    /home/panchod/Audio/0Today

cboxDevice    :    /media/WALKMAN/MUSIC/


[chkbuttons]

ask = TRUE
empty = FALSE

[itime]

last : "00000000000"

No comments:

Post a Comment