-
Notifications
You must be signed in to change notification settings - Fork 8
/
makerProject.py
executable file
·1803 lines (1544 loc) · 68.6 KB
/
makerProject.py
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: cp1252 -*-
import os
import sys
import webbrowser
from xml.sax import parse
from xml.sax.handler import ContentHandler
from ftplib import FTP
import ftplib
import time
import shutil
import re
import urllib
import urlparse
import cPickle
import string
import makerFileTemplates
import makerFileTypes
import makerServerlink
from makerUtilities import readFile, writeFile
from makerUtilities import copyFileTree
import makerUtilities
import makerImageImporter
import makerDeleteImage
import makerFtpBrowser
import makerAddNewLanguageCodedFile
import makerCheckInternetConnection
import makerProjectController
from makerConstants import Constants
def afterThisUpdateStatusInfo(func):
def wrapped(*args, **kwds):
self = args[0]
func(*args, **kwds)
# for now we have to do this check
try:
if self.projectController:
self.projectController.updateStatusInformation()
except Exception, e:
print "makerProject"
print "unable to process: afterThisUpdateInfo", str(e)
return wrapped
def enforcePassword(func):
def wrapped(*args, **kwds):
self = args[0]
if not self.checkIfProjectIsSetUp(verbose=True):
return
else:
if self.loadPassword():
func(*args, **kwds)
return wrapped
class MakerProjectModel:
""" The model for projects
on instantiation you pass it a path to a project
"""
def __init__(self, project, view, projectManager=None):
self.projectController = makerProjectController.MakerProjectController(self, view)
self.projectManager = projectManager
self.setProjectPath(project)
self.coreMessage("Working directory is: %s" % os.getcwd())
self.systemSetup()
self.pathParts = os.path.join(self.getProjectPath(), "parts/")
self.setupProjectAndInitServerlink()
self.setImageSyncNeeded(needed = False)
self.clearPassAttempts()
self.setCurrentFile(None)
self.setRemotePassword() # defaults to None
self.setContentEditMode(".content")
self.markers = ["!projectName!",
"!pageName!",
"!creationDate!",
"!todaysDate!"
]
self.initFtpQueue()
self.supportedFiles = [".content",
".css",
".cgi",
".js",
".txt",
".xml",
".html",
".php",
".py",
".dynamic",
".mov",
".pdf",
".nav",
".body",
".foot",
".head",
".zip"]
self.supportedImages = [".png",
".jpg",
".jpeg",
".tif",
".tiff",
".gif",
".pnm",
".pcx",
".ico",
".cur",
".ani",
".xpm",
".PNG",
".JPG",
".JPEG",
".TIF",
".TIFF",
".GIF",
".PNM",
".PCX",
".ICO",
".CUR",
".ANI",
".XPM"]
self.loadFiles()
@afterThisUpdateStatusInfo
def loadFiles(self):
self.projectController.projectRootItem = self.projectManager.controller.findTreeItemByText(self.getProject())
self.setItemGroups(self.mergeSupportedAndUnsupportedFileGroups())
self.itemsInGroups = {}
self.loadGroupItems() # this call populates the itemsInGroups List
self.projectController.treeViewExpandItem(self.projectController.projectRootItem)
self.projectController.selectTreeItem(self.projectController.projectRootItem)
self.projectController.markAllQueuedFiles()
def mergeSupportedAndUnsupportedFileGroups(self):
allFileGroups = []
for group in self.supportedFiles:
allFileGroups.append(group)
for group in self.getAllFileExtensionsFromParts():
if allFileGroups.count(group) == 0:
allFileGroups.append(group)
toIgnore = ['.head',
'.htm',
'.rss',
'.DS_Store']
for imageType in self.supportedImages:
toIgnore.append(imageType)
toIgnore.append(imageType.upper())
for item in toIgnore:
try:
allFileGroups.remove(item)
except:
sys.stdout.write("*")
# remove _local and _content files
for item in allFileGroups:
if item.endswith("_local"):
allFileGroups.remove(item)
return allFileGroups
def getAllFilesFromParts(self):
"""Returns a list of all the files in the parts folder."""
return os.listdir(self.getPathParts())
def getAllFileExtensionsFromParts(self):
""" returns a list of all file extensions in parts"""
theExtensions = []
for file in self.getAllFilesFromParts():
theExt = os.path.splitext(file)[-1]
if theExtensions.count(theExt) == 0:
theExtensions.append(theExt)
return theExtensions
def replaceStringInAllItems(self, old, new):
"""
Replaces old with new in all text based files that are in the parts
folder.
Note: there is no distinction between binary and text files
only a try: block that fails (then it is likely to be a binary)
if the anything goes wrong
"""
files = []
itemGroups = self.getItemGroups()
more = ['.nav','.body','.foot','.head']
for items in more:
itemGroups.append(items)
for x in itemGroups:
for y in self.getFilesByExtension(x):
files.append(y + x)
for z in files:
f_ = readFile(self.getPathParts() + z)
try:
if old in f_:
self.addToFtpQueue(z)
f__ = f_.replace(old , new)
writeFile(self.getPathParts() + z , f__)
except:
m = "Cannot replace in file %s\n" % z
m += 'Possible (likely) binary file...'
print m
def setProjectPath(self, aPath):
self.pathProject = aPath
def getProjectPath(self):
return self.pathProject
def getItemsByGroup(self, groupName):
"""Returns items of a special group. The index is the position
of the group in itemGroups.
"""
return self.itemsInGroups[groupName]
def loadGroupItems(self):
self.coreMessage("loading group items...")
self.itemsInGroups = {}
for groupName in self.getItemGroups():
result = self.getFilesByExtension(groupName)
self.itemsInGroups[groupName] = result
parentItem = self.projectController.findTreeItemByText(groupName)
if parentItem:
for file in result:
self.projectController.treeViewAppendItem(parentItem, file, type="File")
def getFilesByExtension(self, ext):
"""ext is in the .ext format eg. .jpg or .content."""
theResult = []
for thing in os.listdir(self.getPathParts()):
(pfad, datei) = os.path.split(thing)
(eins, zwei) = os.path.splitext(datei)
if zwei == ext:
theResult.append(eins)
return theResult
def setItemGroups(self, groups):
for item in groups:
self.projectController.treeViewAppendItem(self.projectController.projectRootItem, item)
self.itemGroups = groups
def getItemGroups(self):
return self.itemGroups
@afterThisUpdateStatusInfo
def setProject(self, proj):
self.project = proj
def getProject(self):
return self.project
def getPathParts(self):
return self.pathParts
def coreMessage(self, message):
print 'makerCore: %s' % str(message)
def closeProject(self):
self.cleanUp()
if self.getFtpQueue():
self.saveFtpQueue()
def cleanUp(self):
"""
some cleanup things
"""
print "cleaning up"
if os.path.isfile(os.path.join(self.getProjectPath(), "makerPrintOut.html")):
print "deleting printOut file"
os.remove(os.path.join(self.getProjectPath(), "makerPrintOut.html"))
def importImage(self):
makerImageImporter.MakerImageImporter(self, self.projectController.view)
self.setImageSyncNeeded(needed = True)
def deleteImage(self):
delImg = makerDeleteImage.DeleteImg(self, self.projectController)
delImg.deleteImage()
def syncImages(self, verbose = True):
"""
Sync local and remote image files
"""
if not self.checkIfProjectIsSetUp(verbose = True):
return
self.serverLogin()
if not self.server.status == "connected":
return
imagesToUpload = []
imagesToDownload = []
remoteImages = self.getRemoteImageFiles()
localImages = self.getImageFiles()
for image in remoteImages:
if localImages.count(image) == 0:
imagesToDownload.append(image)
for image in localImages:
if remoteImages.count(image) == 0:
imagesToUpload.append(image)
if imagesToUpload == [] and imagesToDownload == []:
self.serverLogout()
if verbose == True:
self.projectController.infoMessage("Nothing To Sync!")
return
if imagesToDownload != []:
self.projectController.showProgress(len(imagesToDownload),"downloading:", title="synchronizing images...")
count = 0
for image in imagesToDownload:
self.projectController.updateProgressMessage(count,"downloading:" + image)
self.downloadFile(os.path.join(self.getRemoteGfxFolder(),image),
os.path.join(self.getPathParts(),image),
"binary")
count += 1
if imagesToUpload != []:
self.projectController.showProgress(len(imagesToUpload),"uploading:", title="synchronizing images...")
count = 0
for image in imagesToUpload:
self.projectController.updateProgressMessage(count,"uploading:" + image)
self.uploadFile(os.path.join(self.getPathParts(),image),
self.getRemoteGfxFolder(),image,
"binary")
count += 1
self.projectController.killProgressBar()
self.serverLogout()
self.projectController.killProgressBar()
self.setImageSyncNeeded(needed = False)
def setupProjectAndInitServerlink(self):
self.projectSetup()
self.coreMessage('Initializing link to ftp server')
self.server = makerServerlink.Server(self)
def saveProjectAsTemplate(self, event = None):
def resetProjectSetup(pathToExported = None):
string = """<?xml version="1.0" encoding="ISO-8859-1" ?>
<project_setup>
<version>1</version>
<sprache>en</sprache>
<encoding>utf-8</encoding>
<add_language>de</add_language>
<gfx_folder>gfx/</gfx_folder>
<ftp_host>not set</ftp_host>
<ftp_user>not set</ftp_user>
<ftp_password>None</ftp_password>
<ftp_root>.</ftp_root>
<url>http://www.yourserver.com/</url>
</project_setup>"""
xPath = os.path.join(pathToExported, "setup", "project_setup.xml")
writeFile(xPath, string)
def deleteHiddenFiles(root = None):
path = root
maxDepth = 3
folderDepth = -1
for root,subFolders,files in os.walk(path):
folderDepth += 1
if folderDepth < maxDepth: #limit folder depth for deletion to 3 (safety)
for root,subFolders, files in os.walk(path, topdown=False):#traverse filesystem from "path" in reverse
#delete files begining with "."
for file in files:
if file.startswith("."):
dPath = os.path.join(root,file)
#print dPath
self.projectController.updateProgressPulse("cleaning up: " + dPath)
os.remove(dPath)
#delete folders begining with "."
for dir in subFolders:
if dir.startswith("."):
dPath=os.path.join(root,dir)
self.projectController.updateProgressPulse("cleaning up: " + dPath)
shutil.rmtree(dPath, ignore_errors=True)
m = "If you are exporting a template, make sure that you have "
m += "a current screenshot included.\n"
m += "Save this screenshot as 'preview.jpg' into your parts folder. "
m += "Dimensions should be 320x240 pixels."
self.projectController.infoMessage(m)
tgt = self.projectController.dirDialog("Save Template To:")
if not tgt: return
fullTarget = os.path.join(tgt, self.getProject())
if os.path.isdir(fullTarget):
if self.projectController.askYesOrNo("'" + str(fullTarget) +
"' already exists! Would you like to overwrite it?") != "Yes":
return
else:
shutil.rmtree(fullTarget, ignore_errors=True)
os.mkdir(fullTarget)
src = self.getProjectPath()
self.projectController.showProgress(limit=1, Message="Saving template...", title="Saving template...")
copyFileTree(src, fullTarget, [], self.projectController.updateProgressPulse, ("storing: " + self.getProject()))
deleteHiddenFiles(root = fullTarget)
resetProjectSetup(fullTarget)
self.projectController.killProgressBar()
def systemSetup(self):
"""Sets up the CMS. Data is read from system.xml"""
self.homeDir = os.path.dirname(sys.argv[0])
if os.name == 'nt':
self.coreMessage('nt found converting path')
new = self.homeDir.replace('\\','/')
self.homeDir = new
self.pathSystem = os.path.join(self.homeDir, 'system')
self.coreMessage('Setting up system')
class XmlReader(ContentHandler):
def __init__(XmlReader, scrwid=79, *args):
ContentHandler.__init__(XmlReader, *args)
def startElement(XmlReader, name, attrs):
XmlReader.start_name = name
if XmlReader.start_name=="System_Setup":
sys.stdout.write("setting up system...\n")
def endElement(XmlReader, name):
XmlReader.end_name = name
if XmlReader.end_name=="System_Setup":
sys.stdout.write("\n done\n")
def characters(XmlReader, chars):
if XmlReader.start_name == "feedbackadress":
self.feedbackadress = chars
XmlReader.start_name = ""
parse(self.getSystemSetupFilename(), XmlReader())
# ------------------------------------------------------------
@enforcePassword
def serverLogin(self):
"""Login to FTP server."""
self.projectController.showProgress(2, "logging in...", "logging in...")
self.projectController.updateProgressMessage(1, "logging in...")
try:
self.server.login()
self.coreMessage("Logged in to server: OK...")
self.projectController.killProgressBar()
return True
except:
self.projectController.killProgressBar()
self.projectController.errorMessage("Log in to server: FAILED...")
return False
def serverLogout(self):
"""Logout from the FTP server."""
self.projectController.showProgress(2, "logging out...", "logging out...")
self.projectController.updateProgressMessage(1, "logging out...")
try:
self.server.logout()
self.coreMessage("Logged out of server: OK...")
self.projectController.killProgressBar()
return True
except:
self.projectController.killProgressBar()
self.projectController.errorMessage("Logging out of server: FAILED...")
return False
def checkIfRemoteDirIsDir(self, aDir):
return self.server.isdir(aDir)
def makeRemoteDir(self, aDir):
return self.server.mkd(aDir)
def makeAll(self, event=None):
"""Rebuilds all web sites for the current language, and is queuing them.
This method is not invoking any upload functions like in version < 0.91
"""
def initForMakeAll(name, group):
theClass = self.getFileClassForSupportedGroup(group)
file = theClass(self, name, view=False)
self.setCurrentFile(file)
if self.getCurrentFile():
nowFile = self.getCurrentFile()
else:
nowFile = None
pagelist = self.getFilesByExtension(".content")
self.projectController.showProgress(len(pagelist),"rebuilding websites")
step = xrange(len(pagelist))[0]
for i in pagelist:
try:
initForMakeAll(i,".content")
x = self.getCurrentFile()
x.makeWebSite()
self.projectController.updateProgressMessage(step,"making page: "+ x.getName())
step += 1
except:
print "Make all failed for :" , i
self.projectController.killProgressBar()
self.setCurrentFile(nowFile)
def testFTPFromSetupFile(self):
psfn = self.getProjectSetupFilename()
theInformation = self.getProjectInformation(psfn)
host = theInformation['ftp_host']
user = theInformation['ftp_user']
root = theInformation['ftp_root']
print "testing connection from file...", host, user, root
if host == "not set" or user == "not set":
return False
passw = self.projectController.password("Please enter FTP password...")
if self.testFtp(host, user, root, passw) != True:
return False
else:
self.saveValidFTPHost(host, user, root)
return True
def testFtp(self, host, user, root, passw):
"""
Returns True if FTP settings are good, else an error string
about what is wrong. If the password is good it is stored
and used for upcoming connections.
"""
self.projectController.showProgress(4,"testing Hostname: " + host)
testFtp = FTP()
testFtp.set_debuglevel(2)
try:
print "action testFTP: testing hostname..."
print "-----------------------------------"
testFtp.connect(host)
print testFtp.getwelcome()
except Exception, e:
self.projectController.killProgressBar()
testFtp.close()
return "bad hostname!"
try:
self.projectController.updateProgressMessage(3,"testing Username: " + user)
print "action testFTP: testing username..."
print "-----------------------------------"
print testFtp.sendcmd("USER " +user )
except ftplib.all_errors, e:
testFtp.close()
self.projectController.killProgressBar()
return str("Error No:\n" + e[0] + "\nbad username")
try:
self.projectController.updateProgressMessage(2,"testing Password" )
print "action testFTP: testing password..."
print "-----------------------------------"
testFtp.sendcmd("PASS " +passw )
except ftplib.all_errors,e:
self.projectController.killProgressBar()
testFtp.close()
self.setRemotePassword(None)
# the fact that the server is accepting the username does not
# mean that it is valid
return str("Error No:\n" + e[0] + "\nbad username or password")
try:
self.projectController.updateProgressMessage(1,"testing root" )
testFtp.cwd(root)
except ftplib.all_errors,e:
self.projectController.killProgressBar()
testFtp.close()
self.setRemotePassword(None)
return str("Error No:\n" + e[0] + "\n bad path to project")
self.projectController.killProgressBar()
testFtp.close()
return True
def addAllFilesToQueue(self):
self.makeAll()
distributionData = self.readDistributionTable()
listOfFiles = []
for aDict in distributionData:
listOfFiles.append(aDict["ftp_source"])
for file in listOfFiles:
# .htm files or in other words .content are already queued thru make all
if not file.endswith(".htm"):
try:
self.addToFtpQueue(file)
except Exception, e:
self.projectController.errorMessage("Unable to add " +
file +
" to queue: \n" +
str(e) + "\n Skipping " +
file + "...")
def uploadEverything(self, event=None):
if not self.checkIfProjectIsSetUp(verbose=True):
return
self.addAllFilesToQueue()
if not makerCheckInternetConnection.check():
self.projectController.infoMessage("No internet connection!\nSorry, cannot send files to server...")
else:
self.publishQueuedFiles()
self.syncImages(verbose = False)
def uploadFile(self, theFile, remoteFolder, theTarget, theFtpMode):
"""
Uploads a single file and returns a boolean indicating outcome.
You have to be logged in to do this.
"""
try:
self.server.upload(theFile, remoteFolder, theTarget, theFtpMode)
return True
except:
return False
def downloadFile(self, remoteFile, localFile, theFtpMode):
"""
downloads a single file and returns file ?
You have to be logged in to do this.
"""
if self.server.download(remoteFile, localFile, theFtpMode):
return True
else:
return False
def renameRemoteFile(self, oldName, newName):
try:
self.server.rename(oldName, newName)
return True
except:
return False
# ------------------------------------------------------------
def deleteRemoteFile(self, remoteFolder, theFile):
"""
delete remote File
you have to be logged in to do that
returns True or False
if one of the parameters is "undefined" which is the value in the
distribution table for pages that exist only locally -
this method returns True but does nothing
"""
if remoteFolder=="undefined": return True
res = self.server.delete(remoteFolder, theFile)
if res != True:
return False
else:
return True
def getRemoteGfxFolder(self):
return self.gfxFolder
def getSystemPath(self):
return self.pathSystem
def getSystemSetupFilename(self):
return os.path.join(self.getSystemPath(), 'system_setup.xml')
def getProjectSetupFilename(self):
return os.path.join(self.getProjectPath(), "setup/project_setup.xml")
def initFtpQueue(self):
"""
* check if there is an old queue
* set the queue with old values or to []
"""
self.ftpQueue = []
currQueue = os.path.join(self.getPathParts(), "current.queue")
if os.path.isfile(currQueue):
bFile = open(currQueue,"rb")
last = cPickle.load(bFile)
lastQueue = cPickle.loads(last)
bFile.close()
self.setFtpQueue(lastQueue)
os.remove(currQueue)
else:
self.setFtpQueue([])
self.coreMessage("FTP Queue: %s" % str(self.ftpQueue))
def setFtpQueue(self, files):
"""items is a list of maker files."""
self.ftpQueue = files
def isFileInQueue(self, theFile):
"""Returns a boolean."""
if theFile in self.ftpQueue:
return True
else:
return False
@afterThisUpdateStatusInfo
def addToFtpQueue(self, theFile):
# check if item is already in queue
# TO DO: change to use "thing in list" syntax
if self.ftpQueue.count(theFile) == 0:
if os.path.isfile(os.path.join(self.getPathParts(), theFile)):
self.ftpQueue.append(theFile)
self.projectController.markQueuedFile(theFile)
@afterThisUpdateStatusInfo
def deleteFromFtpQueue(self, theFile):
self.ftpQueue.remove(theFile)
def getFtpQueue(self):
""" returns the current FTP queue"""
return self.ftpQueue
def renameItemInFtpQueue(self, oldName, newName):
print self.ftpQueue
if oldName in self.getFtpQueue():
new = []
for item in self.getFtpQueue():
print "+"
if item == oldName:
new.append(newName)
else:
new.append(item)
self.ftpQueue = new
print self.ftpQueue
def clearFtpQueue(self):
"""Clears the queue with no warning."""
self.ftpQueue = []
def saveFtpQueue(self):
"""Serializes the queue for the next session."""
self.coreMessage("Saving FTP Queue for later...")
currentQueue = self.getFtpQueue()
bytes = cPickle.dumps(currentQueue, 2)
bFile = open(os.path.join(self.getPathParts(),"current.queue"), "wb")
cPickle.dump(bytes, bFile, 2)
bFile.close()
@enforcePassword
def publishQueuedFiles(self, event=None):
""" also checks for image sync """
if not self.checkIfProjectIsSetUp():
self.projectController.errorMessage("You need to setup your project to do that...")
return
nowFile = self.getCurrentFile()
publishedFiles = []
self.projectController.showProgress(len(self.getFtpQueue()),
"uploading:",
title="uploading...")
self.serverLogin()
if not self.server.status == "connected":
self.projectController.killProgressBar()
return
count = 0
for aFile in self.getFtpQueue():
split = os.path.splitext(aFile)
self.justInitFile(split[0], split[1])
fName = self.currentFile.getName()
fExt = split[1]
fileName = fName + fExt
# here you publish
self.projectController.updateProgressMessage(count, fileName)
self.currentFile.publish()
count += 1
publishedFiles.append(fileName)
self.projectController.markQueuedFile(fileName, mark=False)
self.serverLogout()
self.setCurrentFile(nowFile)
for file in publishedFiles:
self.deleteFromFtpQueue(file)
if self.imageSyncNeeded:
self.syncImages(verbose = False)
self.projectController.killProgressBar()
# ------------------------------------------------------------
# -- password stuff
#-------------------------------------------------------------
def getPassAttempts(self):
"""Returns the number of password attempts."""
print "password attempt # ", self.passAttempts
return self.passAttempts
def incPassAttempts(self):
"""Increases by 1 the password attempts."""
self.passAttempts += 1
def clearPassAttempts(self):
"""Sets the number of pass attempts to zero."""
self.passAttempts = 0
def maxPassAttemptsReached(self):
return self.getPassAttempts() == Constants.MAX_PASS_ATTEMPTS
def dealWithMaxPassReached(self):
m = 'Sorry, no more password attempts allowed. Exiting...'
self.projectController.errorMessage(m)
sys.exit()
def loadPassword(self):
def passwordOK(passw):
""" password has been entered"""
passw = passw.strip()
if not passw: return False
result = self.testFtp(self.ftpHost,
self.ftpUser,
self.ftpRoot,
passw)
return result
if self.remotePasswordIsSet(): return True
passw = self.projectController.password("Please enter FTP password...")
if not passw:
return False
while passw is not None and passwordOK(passw) != True:
self.handleBadPassword()
if self.maxPassAttemptsReached():
self.dealWithMaxPassReached()
passw = self.projectController.password("Please enter FTP password...")
self.setRemotePassword(passw)
self.clearPassAttempts()
return passw != None
def handleBadPassword(self):
self.incPassAttempts()
left = Constants.MAX_PASS_ATTEMPTS - self.getPassAttempts()
m = 'Wrong password!'
m += ' You have %d attempts left...' % left
self.projectController.errorMessage(m)
def isFileBinary(self, file):
"""Returns a boolean.
PDF files are treated as binary by default."""
if os.path.splitext(file)[-1].lower() == '.pdf':
print 'PDF file found. Is considered binary.'
return True
textCharacters = "".join(map(chr, range(32, 127)) + list("\n\r\t\b"))
nullTrans = string.maketrans("", "")
s = readFile(file)
if "\0" in s:
return True
if not s: # Empty files are considered text
return False
# Get the non-text characters (maps a character to itself then
# use the 'remove' option to get rid of the text characters.)
t = s.translate(nullTrans, textCharacters)
# If more than 30% non-text characters, then
# this is considered a binary file
if len(t)/len(s) > 0.30: return True
return False
def setFtpHost(self, host):
self.ftpHost = host
def getFtpHost(self):
return self.ftpHost
def setFtpUser(self, user):
self.ftpUser = user
def getFtpUser(self):
return self.ftpUser
def setFtpRoot(self,root):
self.ftpRoot = root
def getFtpRoot(self):
return self.ftpRoot
def checkIfProjectIsSetUp(self, verbose=False):
"""
Determines weather FTP settings are useful
returns True or False
"""
# The project is NOT set up when:
#
# - there is no internet connection since we cannot test the settings
# - there is no pickled file called validFTP
#
#
#
connection = makerCheckInternetConnection.check()
if not connection:
if verbose:
self.projectController.infoMessage("No Internet Connection !")
return False
if self.readValidFTPFile():
valid = self.readValidFTPFile()
psfn = self.getProjectSetupFilename()
projectData = self.getProjectInformation(psfn)
if projectData['ftp_host'] == valid[0] and projectData['ftp_user'] == valid[1]:
return True
else:
m = "All right. It seems like you have manually changed your setup file.\n"
m += "The current FTP settings have not been tested. Please use Project / Project Setup "
m += "to run a test."
self.projectController.errorMessage(m)
return False
else:
if connection:
if not self.testFTPFromSetupFile():
if verbose:
self.projectController.errorMessage("Please set up your FTP connection!")
return False
else:
return True
else:
# no internet connection
return False
def saveValidFTPHost(self, host, user, root):
data = [host, user, root]
bytes = cPickle.dumps(data, 2)
bFile = open(os.path.join(self.getProjectPath(),"setup/valid.ftp"), "wb")
cPickle.dump(bytes, bFile, 2)
bFile.close()
def readValidFTPFile(self):
validFTPFile = os.path.join(self.getProjectPath(), "setup/valid.ftp")
if os.path.isfile(validFTPFile):
bFile = open(validFTPFile,"rb")
last = cPickle.load(bFile)
validConnection = cPickle.loads(last)
bFile.close()
return validConnection
else:
return False
def projectSetup(self):
"""
This is the project setup function. It is reading all the settings
from the projects setup.xml
"""
class XmlReader(ContentHandler):
def __init__(XmlReader, scrwid=79, *args):
ContentHandler.__init__(XmlReader, *args)
def startElement(XmlReader, name, attrs):
XmlReader.start_name = name
if XmlReader.start_name=="project_setup":
sys.stdout.write("*")
def endElement(XmlReader, name):
XmlReader.end_name = name
if XmlReader.end_name=="project_setup":
sys.stdout.write("\n done\n")
def characters(XmlReader, chars):
sys.stdout.write("*")
if XmlReader.start_name == "encoding":
self.encoding = chars
elif XmlReader.start_name == "gfx_folder":
if not chars.endswith("/"):
self.gfxFolder = chars + "/"
else:
self.gfxFolder = chars
elif XmlReader.start_name == "stylesheet":
self.stylesheet = chars
elif XmlReader.start_name == "rss_feed":
self.rss_feed = chars
elif XmlReader.start_name == "rss_page":
self.rss_page = chars
elif XmlReader.start_name == "rss_language":
self.rss_language = chars
elif XmlReader.start_name == "remote_rss_dir":
self.remote_rss_dir = chars
elif XmlReader.start_name == "url":
self.url = chars
elif XmlReader.start_name == "ftp_host":
self.setFtpHost(chars)
elif XmlReader.start_name == "ftp_user":
self.setFtpUser(chars)
elif XmlReader.start_name == "ftp_root":
self.setFtpRoot(chars)
elif XmlReader.start_name == "startup_page":
self.page = chars
XmlReader.start_name = ""
# this is default for older projects < version 0.8 that did
# not have the encoding node in the setup file
self.encoding = 'latin-1'
parse(self.getProjectSetupFilename(), XmlReader())