# -*- coding: utf-8 -*-
"""
Created on Thu Aug  2 13:14:50 2012

@author: Chameleon APython Gypson (Swordf1sh)
"""

# -*- coding: utf-8 -*-
"""
Spyder Editor

"""
import urllib
import urllib2
from Tkinter import *
from tkFileDialog import *

class Myvideo:
    def CheckURL(self,video_url):
        self.countchk=video_url.count('http://')
        if self.countchk==0:
            video_url='http://'+video_url
        return video_url
    def GetTitle(self,video_url):
        self.response=urllib2.urlopen(self.CheckURL(self.CheckURL(video_url)))
        self.page_source=self.response.read()
        self.countdesc=self.page_source.find('"description" content="')
        self.page_source=self.page_source[self.countdesc+22:]
        self.countdot=self.page_source.find('"')
        self.page_source=self.page_source[:self.countdot]
        return self.page_source
    def GetVideo(self,video_url):
        if self.CheckURL(video_url).count('http://')>0:
            self.response=urllib2.urlopen(self.CheckURL(self.CheckURL(video_url)))
            self.page_source=self.response.read()
            self.urllist=['http://silk2.vod.myvideo.ge/flv/','http://vod4.co.myvideo.ge/flv/','http://vod2.co.myvideo.ge/flv/']
            for num in range(0,3):
                if self.page_source.find(self.urllist[num])>0:
                    self.page_source=self.page_source[self.page_source.find(self.urllist[num]):]
                    self.countdotvid=self.page_source.find("\'")
                    self.page_source=self.page_source[:self.countdotvid]
                    return self.page_source
                    break
    def FileType(self,video_url):
        if self.GetVideo(video_url)[-2:]=='flv':
            return 'flv'
        else:
            return 'mp4'
            

def Download(title,video_url):
    file_name=video.GetVideo(Video_URL.get())
    file_name=file_name.split('/')[-1]
    Title.configure(text='Downloading...')
    u=urllib2.urlopen(video.GetVideo(Video_URL.get()))
    f=open(file_name,'wb')
    meta=u.info()
    file_size=int(meta.getheaders("Content-Length")[0])
    print "Downloading: %s Bytes: %s" % (file_name, file_size)
    buffer = u.read()
    f.write(buffer)
    f.close()
    Title.configure(text='Download Complete (%s)' % video.GetTitle(Video_URL.get()))
    
video=Myvideo()

Window=Tk()
Window.title('Myvideo.ge Downloader')
Window.resizable(0,0)

Title=Label(Window,text='Python Myvideo.ge Simple Downloader')
UrlLabel=Label(Window,text='Enter Video Full URL -> ')
Video_URL=Entry(Window)
Submit_Button=Button(Window,text='Download',command=lambda: Download(video.GetTitle(Video_URL.get()),video.GetVideo(Video_URL.get())))     

Title.grid(row=0,column=0,columnspan=3,padx=20,pady=10)
UrlLabel.grid(row=1,column=0)
Video_URL.grid(row=1,column=1)
Submit_Button.grid(row=1,column=2)

Window.mainloop()