File: RepDownload.py

package info (click to toggle)
aptoncd 0.1-1.2
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 1,572 kB
  • ctags: 544
  • sloc: python: 3,125; xml: 1,216; makefile: 125; sh: 6
file content (399 lines) | stat: -rw-r--r-- 17,077 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#!/usr/bin/env python
# -*- coding: utf-8 -*-
######################################################
##
#  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; version 2 only.
#
#  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.
##
######################################################
## 
#  Project: AptOnCd
#  File: RepDownload.py
#  Author: Laudeci Oliveira <laudeci@gmail.com>
#  Creation: 07/12/2006
#  Changed: 
#  Purpose: Class that will control repositoy downloads
##
######################################################
import CreateAptOncd
import utils
import os
import xmlfile
import parsegz
import config
import ProgressWindow
import config
from messageBox import MessageBox
import time
import gtk
import gtk.glade
import pygtk
import DownloadGUI
import download
import msg
import gzip
import MediaSplitter

class RepDownload:
    def __init__(self,gladeFileName):
        self.gladeFile = gladeFileName
        self.totaltime = 0
        self.totalsize = 0
        self.speed = 0
        self.totalread = 0
        self.filecount = 0
        self.downloadedFiles = 0
        self.treeline = -1
        self.DownloadResult = gtk.RESPONSE_NONE
    
    def load_conf(self, file):
        XMLFile = xmlfile.XMLFile()
        self.node_text = XMLFile.parse(file)
        return XMLFile.load_conf(file)
     
    def CalcSpeed(self, bytesRead):
        if time.time() != self.initialtime:
            TimeFraction = ((self.totalsize - self.totalread )* (time.time() - self.initialtime)) / self.totalread
            speed = self.totalread / (time.time() - self.initialtime)
            
            self.speed = speed
            self.totaltime = TimeFraction 
            self.labelestimatedtime.set_text(str(utils.TimeFormat(self.totaltime)) )
            self.labeldownloadrate.set_text(utils.fileSizeFormat(speed))
            
            fraction = (float(self.totalread) / self.totalsize)
            self.progressbar.set_fraction(fraction)  
            
            self.progressbar.set_text("%d%%" %(100 * float(self.totalread) / self.totalsize) )
            
            
    def scrollToPath(self, index):
        try :
            self.treeprogress.scroll_to_cell(index)
        except:
            pass

    def pCancelEvent(self, widgets = None):
        self.DownloadResult = gtk.RESPONSE_CANCEL
        self.Packages.cancelDownload()
    
    def show_progress(self):
        self.progressgui = gtk.glade.XML(self.gladeFile, "frmFetchRepo")
        
        self.frmFetchRepo = self.progressgui.get_widget("frmFetchRepo")
        self.frmFetchRepo.set_position(gtk.WIN_POS_CENTER)
        self.frmFetchRepo.set_modal(True)
        
        self.frmFetchRepo.connect("delete-event", self.close_fetchwindow)
        
        self.labeltotalsize = self.progressgui.get_widget("lblTotalSize")
        self.labeltotalsize.set_text(utils.fileSizeFormat(self.totalsize))
            
        self.labelnumfiles = self.progressgui.get_widget("lblNumberFiles")
        self.labelnumfiles.set_text( str(self.downloadedFiles) + '/' + str(self.filecount) )
        
        self.labelestimatedtime = self.progressgui.get_widget("lblEstimatedTime")
        self.labelestimatedtime.set_text(str("%0.2f" % (self.totaltime))) 
        
        self.labeldownloadrate = self.progressgui.get_widget("lblDownloadRate")
        self.labeldownloadrate.set_text(utils.fileSizeFormat(self.speed))
        
        self.labeldist = self.progressgui.get_widget("lblDistribuition")
        self.labeldist.set_text( self.conf[3])
        
        self.labelversion = self.progressgui.get_widget("lblVersion")
        self.labelversion.set_text(self.conf[4])

        self.labelsection = self.progressgui.get_widget("lblSection")
        self.labelsection.set_text(self.conf[5])

        self.labelarch = self.progressgui.get_widget("lblArchitecture")
        self.labelarch.set_text(self.conf[6])

        self.labelhost = self.progressgui.get_widget("lblMirror")
        self.labelhost.set_text(self.conf[2])
        
        self.button_cancel = self.progressgui.get_widget("btnCancel")
        self.button_cancel.connect("clicked", self.close_fetchwindow)
        
        self.progressbar = self.progressgui.get_widget("pbDownloadTotal")
        
        self.treeprogress = self.progressgui.get_widget("tvDownload")
        bar = gtk.CellRendererProgress()
        
        self.mgrade = gtk.ListStore(str, str, int)
        
        self.treeprogress.set_model(self.mgrade)
        column1 = gtk.TreeViewColumn(msg.MESSAGE_0060, gtk.CellRendererText(), text = 0)
        column2 = gtk.TreeViewColumn(msg.MESSAGE_0061, gtk.CellRendererText(), text = 1)
        column3 = gtk.TreeViewColumn(msg.MESSAGE_0062, bar, value = 2)
        column1.set_resizable(True)
        column2.set_resizable(True)
        column3.set_resizable(True)
        column1.set_sort_column_id(0)
        column2.set_sort_column_id(1)
        column3.set_sort_column_id(2)
        self.treeprogress.append_column(column1)
        self.treeprogress.append_column(column2)
        self.treeprogress.append_column(column3)
        
        self.frmFetchRepo.show()

    def close_fetchwindow(self, widget, data = None):
        self.DownloadResult = gtk.RESPONSE_CANCEL
        self.frmFetchRepo.destroy()       
         
    def SetOptions(self):
        self.DownloadGUI = DownloadGUI.DownloadGUI(self.gladeFile)
        result = self.DownloadGUI.run()
        column3.set_resizable(True)
        column1.set_sort_column_id(0)
        column2.set_sort_column_id(1)
        column3.set_sort_column_id(2)
        self.treeprogress.append_column(column1)
        self.treeprogress.append_column(column2)
        self.treeprogress.append_column(column3)

    def close_fetchwindow(self, widget, data = None):
        self.DownloadResult = gtk.RESPONSE_CANCEL
        self.frmFetchRepo.destroy()       
    
    def on_downloadStatus(self,widget, filedown, size, bytesRead, percent):
        if "Packages.gz" not in filedown:
            if self.DownloadResult == gtk.RESPONSE_CANCEL:
                widget.cancelDownload()
            self.totalread+= bytesRead
            self.mgrade[self.treeline][2] = percent
            self.CalcSpeed(bytesRead)
        else:
            self.totalread+= bytesRead
            fraction = (float(self.totalread) / self.totalsize)
            #fraction =  (float(percent)/100)
            self.wProgress.updateFraction(fraction)
            time.sleep(0.2)
        utils.updateUI()
        return
    
    def Download_TarGZ(self, PackFiles):
        self.initialtime = time.time()
        self.totalread = 0

        self.wProgress.connectEvent(self.pCancelEvent)
        
        downloaded = []
        downresult = False
        for files in PackFiles:
            try:
                self.Packages = download.Download(files[2], files[1])
                self.wProgress.set_task(msg.MESSAGE_0063 % self.conf[5])
                #self.wProgress.TaskLenght(Packages.getDownloadSize())
                self.Packages.connect('download_status',self.on_downloadStatus)
                downresult = self.Packages.download(True)
                if self.DownloadResult == gtk.RESPONSE_CANCEL:
                   self. Packages.cancelDownload()
                   downloaded = []
                   break
            except:
                pass
            if downresult:
                downloaded.append(files)    
                downresult = False
            
        return downloaded
    
    def donwload_files(self):
        self.initialtime = time.time()
        self.totalread = 0
        self.DownloadResult == gtk.RESPONSE_NONE
        for nfiles in self.PackFiles:
            if self.DownloadResult == gtk.RESPONSE_CANCEL:
                self.Packages.cancelDownload()
                break
            #self.labelsection.set_text(nfiles[download.SECTION])
            self.mgrade.append([nfiles[download.PACKAGE] , utils.fileSizeFormat(nfiles[download.SIZE]) , 0])
            self.treeline+= 1
            self.labelnumfiles.set_text('%s/%s' % (self.treeline + 1 ,self.filecount))
            self.scrollToPath(self.treeline)
            
            mainPath = os.path.join(self.conf[xmlfile.PATH],self.conf[xmlfile.DISTRIBUTION],  nfiles[download.REMOTEFILEPATH])
            
            utils.mkdir(mainPath)
            
            filePath = os.path.join(mainPath,nfiles[download.DEBFILENAME] )

            if not utils.fileExist(filePath):
                remotePath = self.conf[xmlfile.METHOD] + '://' + self.conf[xmlfile.HOST] + '/' + self.conf[xmlfile.DISTRIBUTION]  + '/' + nfiles[download.FILENAME]
                self.Packages = download.Download(remotePath, mainPath)
                self.Packages.connect('download_status',self.on_downloadStatus)
                self.Packages.download(True)
                self.downloadedFiles += 1
            else:
		fraction = float((100 * float(nfiles[download.SIZE])) / self.totalsize)
                self.on_downloadStatus(self.frmFetchRepo, nfiles[download.SIZE],float(nfiles[download.SIZE]), float(nfiles[download.SIZE]), float(fraction))
                self.mgrade[self.treeline][2] =100
       
        if self.DownloadResult == gtk.RESPONSE_CANCEL:
            dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, msg.MESSAGE_0067)
            dialog.run()
            dialog.destroy()
            
    def SetOptions(self):
        self.totalsize = 0
        self.DownloadGUI = DownloadGUI.DownloadGUI(self.gladeFile)
        result = self.DownloadGUI.run()
        
        if result  != gtk.RESPONSE_OK:
            dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, msg.MESSAGE_0067)
            dialog.run()
            dialog.destroy()
            return
        
        
        self.conf = self.load_conf(config.XML_FILE)
        ## just removing for teste purpouse

        self.wProgress = ProgressWindow.AptOnCDProgressDialog(self.DownloadGUI.getWindow())
        self.wProgress.Title(msg.MESSAGE_0059 )
        self.wProgress.Task(msg.MESSAGE_0057)
        self.wProgress.Description(msg.MESSAGE_0058) 
        self.wProgress.TaskTitle(msg.MESSAGE_0056 % self.conf[xmlfile.HOST] )
        self.wProgress.set_text('%d%%' % 0)
        
        utils.updateUI()
       
        #create the path fot destination of all Packages.tar.gz
        #folowing the rule down
        #DISTRIBUTION/dists/VERSION/SECTION/binary-ARCH/
        mainPath = os.path.join(self.conf[xmlfile.PATH],self.conf[xmlfile.DISTRIBUTION], 'dists', self.conf[xmlfile.VERSION])
        utils.mkdir(mainPath)
        tarfiles = []
        tarsize =0
        
        for sectionName in self.conf[xmlfile.SECTION].split(';'): 
           Pathx = os.path.join(mainPath, sectionName , 'binary-' + self.conf[xmlfile.ARCHITECTURE] )
           utils.mkdir(Pathx)

           downloadGz = ( \
                          self.conf[xmlfile.METHOD]  + '://' + self.conf[xmlfile.HOST] + '/' + self.conf[xmlfile.DISTRIBUTION]  + \
                          '/dists/' + self.conf[xmlfile.VERSION]  + '/' + sectionName  + '/binary-' + \
                          self.conf[xmlfile.ARCHITECTURE]  + '/Packages.gz')
           size = float(download.getRemoteFileSize(downloadGz))
           self.totalsize+=size
           
           tarfiles.append( ['Packages.gz',Pathx , downloadGz, size])
              
        validTars = self.Download_TarGZ(tarfiles)
        
        if len(validTars) == 0 or self.DownloadResult == gtk.RESPONSE_CANCEL:
            self.wProgress.destroy()
            dialog = gtk.MessageDialog(None, gtk.DIALOG_MODAL, gtk.MESSAGE_WARNING, gtk.BUTTONS_OK, msg.MESSAGE_0067)
            dialog.run()
            dialog.destroy()
            return
        
        self.PackFiles = []
        self.totalsize = 0
        self.totalread = 0
        for tar in validTars:
            s = parsegz.openGZ(tar[1] + '/Packages.gz'  )
            self.PackFiles.extend(parsegz.ParseFile(s).Parse())
         
        self.filecount = str(len(self.PackFiles))
        
        for nfiles in self.PackFiles:
            if nfiles[3] != '':
                self.totalsize+= float(nfiles[3])
        self.wProgress.destroy()

        if self.DownloadResult != gtk.RESPONSE_CANCEL:
            self.show_progress()
            self.donwload_files()
           
        self.frmFetchRepo.hide()

        if self.DownloadResult != gtk.RESPONSE_CANCEL:
            if self.conf[xmlfile.MEDIA] == 'DVD':
                cdSize =config.DVD
            else:
                cdSize = config.CD
            a = MediaSplitter.Splitter(self.conf[xmlfile.PATH], config.WORK_DIR, self.conf[xmlfile.DISTRIBUTION], self.conf[xmlfile.VERSION], self.conf[xmlfile.SECTION].split(';'), self.conf[xmlfile.ARCHITECTURE], cdSize)
            iSorted = a.SplitMedia()
            
            #we must show a progress window while copy is in progress
            #TODO - create strings in msg.py and input error handler
            taskLen = 0
            for s in iSorted:
                taskLen += len(s[1])
                
            self.wProgress.Title(msg.MESSAGE_0064 )
            self.wProgress.Task(msg.MESSAGE_0066)
            self.wProgress.TaskLenght( int(taskLen)) # Task's len
            self.wProgress.Description(msg.MESSAGE_0065) 
            self.wProgress.TaskTitle(msg.MESSAGE_0064 )
            self.wProgress.set_text('%d%%' % 0)

            i =1
            for s in iSorted:
                #print s[0]
                for n in s[1]:
                    #filesize = (float(n.Size)/1024.0**2 + 1)
                    utils.mkdir(n.TarGZ_Path % n.PackageSection)
                    utils.copyFile(n.SourceLocation, n.Destination)
                    self.wProgress.update(i)
                    i +=1
                    
            curdir = os.getcwd()
            cds ={}
            for s in iSorted:
                mediadir = s[0]+'/'
                os.chdir(mediadir)
                medianame = s[0].split('/')[-1].encode('utf8')
                cds[medianame] = []
                for sec in self.conf[xmlfile.SECTION].split(';'): 
                   pkgzdir = "dists/%s/%s/binary-%s/" % ( self.conf[xmlfile.VERSION],sec,self.conf[xmlfile.ARCHITECTURE])   
                   if utils.pathExists(os.path.join(mediadir,pkgzdir)):
                       os.system('apt-ftparchive packages  pool/ > ' + pkgzdir + 'Packages')
                       #make a .gz file
                       PackagesFile = os.path.join(mediadir,pkgzdir +'Packages')
                       fileObj = gzip.GzipFile(PackagesFile + '.gz', 'wb');
                       fileObj.write(file(PackagesFile, 'rb').read())
                       fileObj.close()
       		       utils.compress(PackagesFile, PackagesFile)
                       
		       os.system('apt-ftparchive release  dists/' + self.conf[xmlfile.VERSION] + ' > dists/' + self.conf[xmlfile.VERSION] + '/Release')
		       
                       cds[medianame].append(sec)

                os.system('ln -s . ' + self.conf[xmlfile.DISTRIBUTION])
                os.chdir(curdir)
            
            self.wProgress.Task(msg.MESSAGE_0020) 
            #print cds  
            for x in cds.keys():
                section = ''
                for n in cds[x]:
                    section+=n+'-'
                section = section[:-1]
                isoname = self.conf[xmlfile.DISTRIBUTION] + '-' + self.conf[xmlfile.VERSION] + '-' 
                isoname += section + '-' + self.conf[xmlfile.ARCHITECTURE] +'-' + x
                os.system('mkisofs -quiet -iso-level 4 -pad -l -r -J -joliet-long -v -V "aptoncd-'+ x  +'" -hide-rr-moved -o ' + os.path.join(config.WORK_DIR ,isoname +'.iso') + ' ' + mediadir + ' 2> /dev/null')
        
        self.wProgress.destroy()
        
        if self.DownloadResult != gtk.RESPONSE_CANCEL :
            checked = MessageBox().ShowFinished(self.gladeFile, config.WORK_DIR )  
        else:
            checked = False

        if checked and self.DownloadResult != gtk.RESPONSE_CANCEL :
            utils.removePath(os.path.join(config.WORK_DIR,'repository'))
	    utils.removePath(self.conf[xmlfile.PATH])
        
        #the comment below must be removed when code is ok
        #self.close_fetchwindow(self)