From 256017ab88e4e46d1973df49b9c2e0cf5557ff36 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 9 May 2015 16:06:24 +0300 Subject: [PATCH 001/108] First working version --- Unixconfig/autodeploy | 1 + client/Client/.svn/all-wcprops | 53 +++ client/Client/.svn/entries | 303 ++++++++++++++++++ .../Client/.svn/text-base/Client.py.svn-base | 74 +++++ .../.svn/text-base/ClientJob.py.svn-base | 137 ++++++++ .../Client/.svn/text-base/Common.py.svn-base | 2 + .../Client/.svn/text-base/Config.py.svn-base | 12 + .../Client/.svn/text-base/Connect.py.svn-base | 45 +++ client/Client/.svn/text-base/README.svn-base | 6 + .../.svn/text-base/__init__.py.svn-base | 3 + .../Client/.svn/text-base/config.cfg.svn-base | 6 + client/Client/Client.py | 54 ++++ client/Client/ClientJob.py | 93 ++++++ client/Client/Clients/.svn/all-wcprops | 11 + client/Client/Clients/.svn/entries | 68 ++++ .../.svn/text-base/__init__.py.svn-base | 0 .../Client/Clients/Facebook/.svn/all-wcprops | 29 ++ client/Client/Clients/Facebook/.svn/entries | 164 ++++++++++ .../text-base/Facebook_Comment.py.svn-base | 12 + .../.svn/text-base/Facebook_Post.py.svn-base | 21 ++ .../.svn/text-base/Facebook_User.py.svn-base | 5 + .../.svn/text-base/__init__.py.svn-base | 0 .../Clients/Facebook/Facebook_Comment.py | 12 + .../Client/Clients/Facebook/Facebook_Post.py | 21 ++ .../Client/Clients/Facebook/Facebook_User.py | 5 + client/Client/Clients/Facebook/__init__.py | 0 .../Client/Clients/Twitter/.svn/all-wcprops | 23 ++ client/Client/Clients/Twitter/.svn/entries | 130 ++++++++ .../Twitter/.svn/text-base/Tweet.py.svn-base | 34 ++ .../.svn/text-base/Twitter_user.py.svn-base | 14 + .../.svn/text-base/__init__.py.svn-base | 1 + client/Client/Clients/Twitter/Tweet.py | 34 ++ client/Client/Clients/Twitter/Twitter_user.py | 14 + client/Client/Clients/Twitter/__init__.py | 1 + client/Client/Clients/__init__.py | 0 client/Client/Common.py | 2 + client/Client/Config.py | 12 + client/Client/Connect.py | 48 +++ client/Client/README | 6 + client/Client/__init__.py | 3 + client/Client/my | 6 + client/__init__.py | 0 client/config/.svn/all-wcprops | 11 + client/config/.svn/entries | 62 ++++ .../config/.svn/text-base/config.cfg.svn-base | 6 + client/config/config.cfg | 6 + client/test.py | 69 ++++ deployer/Common.py | 25 -- exampleConfig/registry.yaml | 16 + server/Common.py | 3 +- server/Config.cfg | 2 +- server/Request.py | 190 ++++++----- server/__init__.py | 1 + server/autodeploy-server.py | 57 +++- server/client.pub | 15 + server/deployer/Common.py | 28 ++ server/deployer/__init__.py | 1 + {deployer => server/deployer}/autodeployer.py | 32 +- server/scm/BaseSCM.py | 12 + server/scm/Git.py | 26 ++ server/scm/__init__.py | 1 + webapp/__init__.py | 1 + webapp/autoDeploy/autoDeploy/settings.py | 4 +- webapp/autoDeploy/autoDeploy/urls.py | 5 + webapp/autoDeploy/autodeploy/client | 1 + webapp/autoDeploy/autodeploy/forms.py | 13 +- .../migrations/0005_auto_20150509_0744.py | 27 ++ webapp/autoDeploy/autodeploy/models.py | 28 +- webapp/autoDeploy/autodeploy/tables.py | 13 + webapp/autoDeploy/autodeploy/views.py | 71 +++- webapp/autoDeploy/static/css/screen.css | 141 ++++++++ webapp/autoDeploy/templates/add_project.html | 11 +- webapp/autoDeploy/templates/add_sshkey.html | 22 ++ webapp/autoDeploy/templates/base.html | 30 +- webapp/autoDeploy/templates/clone.html | 28 ++ webapp/autoDeploy/templates/deploy.html | 19 ++ webapp/autoDeploy/templates/deploy2.html | 27 ++ .../autoDeploy/templates/django-table2.html | 77 +++++ webapp/autoDeploy/templates/projects.html | 5 +- webapp/autoDeploy/templates/table.html | 19 ++ 80 files changed, 2398 insertions(+), 172 deletions(-) create mode 100644 Unixconfig/autodeploy create mode 100644 client/Client/.svn/all-wcprops create mode 100644 client/Client/.svn/entries create mode 100644 client/Client/.svn/text-base/Client.py.svn-base create mode 100644 client/Client/.svn/text-base/ClientJob.py.svn-base create mode 100644 client/Client/.svn/text-base/Common.py.svn-base create mode 100644 client/Client/.svn/text-base/Config.py.svn-base create mode 100644 client/Client/.svn/text-base/Connect.py.svn-base create mode 100644 client/Client/.svn/text-base/README.svn-base create mode 100644 client/Client/.svn/text-base/__init__.py.svn-base create mode 100644 client/Client/.svn/text-base/config.cfg.svn-base create mode 100644 client/Client/Client.py create mode 100644 client/Client/ClientJob.py create mode 100644 client/Client/Clients/.svn/all-wcprops create mode 100644 client/Client/Clients/.svn/entries create mode 100644 client/Client/Clients/.svn/text-base/__init__.py.svn-base create mode 100644 client/Client/Clients/Facebook/.svn/all-wcprops create mode 100644 client/Client/Clients/Facebook/.svn/entries create mode 100644 client/Client/Clients/Facebook/.svn/text-base/Facebook_Comment.py.svn-base create mode 100644 client/Client/Clients/Facebook/.svn/text-base/Facebook_Post.py.svn-base create mode 100644 client/Client/Clients/Facebook/.svn/text-base/Facebook_User.py.svn-base create mode 100644 client/Client/Clients/Facebook/.svn/text-base/__init__.py.svn-base create mode 100644 client/Client/Clients/Facebook/Facebook_Comment.py create mode 100644 client/Client/Clients/Facebook/Facebook_Post.py create mode 100644 client/Client/Clients/Facebook/Facebook_User.py create mode 100644 client/Client/Clients/Facebook/__init__.py create mode 100644 client/Client/Clients/Twitter/.svn/all-wcprops create mode 100644 client/Client/Clients/Twitter/.svn/entries create mode 100644 client/Client/Clients/Twitter/.svn/text-base/Tweet.py.svn-base create mode 100644 client/Client/Clients/Twitter/.svn/text-base/Twitter_user.py.svn-base create mode 100644 client/Client/Clients/Twitter/.svn/text-base/__init__.py.svn-base create mode 100644 client/Client/Clients/Twitter/Tweet.py create mode 100644 client/Client/Clients/Twitter/Twitter_user.py create mode 100644 client/Client/Clients/Twitter/__init__.py create mode 100644 client/Client/Clients/__init__.py create mode 100644 client/Client/Common.py create mode 100644 client/Client/Config.py create mode 100644 client/Client/Connect.py create mode 100644 client/Client/README create mode 100644 client/Client/__init__.py create mode 100644 client/Client/my create mode 100644 client/__init__.py create mode 100644 client/config/.svn/all-wcprops create mode 100644 client/config/.svn/entries create mode 100644 client/config/.svn/text-base/config.cfg.svn-base create mode 100644 client/config/config.cfg create mode 100644 client/test.py delete mode 100755 deployer/Common.py create mode 100644 exampleConfig/registry.yaml create mode 100644 server/__init__.py create mode 100755 server/client.pub create mode 100755 server/deployer/Common.py create mode 100644 server/deployer/__init__.py rename {deployer => server/deployer}/autodeployer.py (76%) create mode 100644 server/scm/BaseSCM.py create mode 100644 server/scm/Git.py create mode 100644 server/scm/__init__.py create mode 100644 webapp/__init__.py create mode 120000 webapp/autoDeploy/autodeploy/client create mode 100644 webapp/autoDeploy/autodeploy/migrations/0005_auto_20150509_0744.py create mode 100644 webapp/autoDeploy/autodeploy/tables.py create mode 100644 webapp/autoDeploy/static/css/screen.css create mode 100644 webapp/autoDeploy/templates/add_sshkey.html create mode 100644 webapp/autoDeploy/templates/clone.html create mode 100644 webapp/autoDeploy/templates/deploy.html create mode 100644 webapp/autoDeploy/templates/deploy2.html create mode 100644 webapp/autoDeploy/templates/django-table2.html create mode 100644 webapp/autoDeploy/templates/table.html diff --git a/Unixconfig/autodeploy b/Unixconfig/autodeploy new file mode 100644 index 0000000..9ca9605 --- /dev/null +++ b/Unixconfig/autodeploy @@ -0,0 +1 @@ +autodeploy ALL=NOPASSWD: ALL diff --git a/client/Client/.svn/all-wcprops b/client/Client/.svn/all-wcprops new file mode 100644 index 0000000..9ff058f --- /dev/null +++ b/client/Client/.svn/all-wcprops @@ -0,0 +1,53 @@ +K 25 +svn:wc:ra_dav:version-url +V 39 +/!svn/ver/433/crawl/client/trunk/Client +END +Client.py +K 25 +svn:wc:ra_dav:version-url +V 49 +/!svn/ver/433/crawl/client/trunk/Client/Client.py +END +__init__.py +K 25 +svn:wc:ra_dav:version-url +V 51 +/!svn/ver/433/crawl/client/trunk/Client/__init__.py +END +Config.py +K 25 +svn:wc:ra_dav:version-url +V 49 +/!svn/ver/433/crawl/client/trunk/Client/Config.py +END +README +K 25 +svn:wc:ra_dav:version-url +V 46 +/!svn/ver/433/crawl/client/trunk/Client/README +END +Common.py +K 25 +svn:wc:ra_dav:version-url +V 49 +/!svn/ver/433/crawl/client/trunk/Client/Common.py +END +ClientJob.py +K 25 +svn:wc:ra_dav:version-url +V 52 +/!svn/ver/433/crawl/client/trunk/Client/ClientJob.py +END +Connect.py +K 25 +svn:wc:ra_dav:version-url +V 50 +/!svn/ver/433/crawl/client/trunk/Client/Connect.py +END +config.cfg +K 25 +svn:wc:ra_dav:version-url +V 50 +/!svn/ver/433/crawl/client/trunk/Client/config.cfg +END diff --git a/client/Client/.svn/entries b/client/Client/.svn/entries new file mode 100644 index 0000000..4aaff0f --- /dev/null +++ b/client/Client/.svn/entries @@ -0,0 +1,303 @@ +10 + +dir +436 +http://svn.trendak.com/crawl/client/trunk/Client +http://svn.trendak.com + + + +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + +82768435-6001-4b23-9c5b-483360495a41 + +Common.py +file + + + + +2012-10-06T13:20:12.000000Z +1063a85c3cb271685676a0aabdf9a34d +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +15 + +ClientJob.py +file + + + + +2012-10-06T13:20:12.000000Z +cbbd7b48fa4df5e0777383d18643ef5c +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +4474 + +Connect.py +file + + + + +2012-10-06T13:20:12.000000Z +94cb48b97ce60b794080973b5e492a8a +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +984 + +Clients +dir + +config.cfg +file + + + + +2012-10-06T13:20:12.000000Z +58ca31e8944b8f20d8424a9d69015c56 +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +79 + +Client.py +file + + + + +2012-10-06T13:20:12.000000Z +961943973b31487620c13cde4937e591 +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +2572 + +__init__.py +file + + + + +2012-10-06T13:20:12.000000Z +2411341a5e57cc0cb16eb41057faf032 +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +45 + +Config.py +file + + + + +2012-10-06T13:20:12.000000Z +7675dbfa26e83419a1a74a1122cc2ef1 +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +319 + +README +file + + + + +2012-10-06T13:20:12.000000Z +b429093d12d06232d3f4f745067f97d2 +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +126 + diff --git a/client/Client/.svn/text-base/Client.py.svn-base b/client/Client/.svn/text-base/Client.py.svn-base new file mode 100644 index 0000000..47109c1 --- /dev/null +++ b/client/Client/.svn/text-base/Client.py.svn-base @@ -0,0 +1,74 @@ +import Config,ClientJob as Job,Connect +import simplejson,xml.dom.minidom +class Client: + network="" + options={} + msg="" + def __init__(self,network): + self.network=network + def Search(self,query,sinceId=None,maxId=None,count=None,startDateTime=None,endDateTime=None,format="json",save="Y",owner=''): + global msg + if owner=='': + owner=Config.Owner + msg=Job.createSearchMessage(owner,query,sinceId,maxId,count,startDateTime,endDateTime,save,network=self.network,options=self.options) + result= Connect.Send(msg) + res=self.parseResult(result) + if format=="object": + return self.jsonToObjects(res) + return res + def Track(self,name,searchWord,fetchAll,owner=''): + if owner=='': + owner=Config.Owner + global msg + msg=Job.createTrackMessage(owner,name,searchWord,fetchAll,network=self.network) + return self.parseResult(Connect.Send(msg)) + def Reterive(self,query,sinceId=None,maxId=None,count=None,startDateTime=None,endDateTime=None,format="json",oldTweets="N",owner='',page=-1,rpp=100,table='recent'): + global msg + if owner=='': + owner=Config.Owner + msg=Job.createReteriveMessage(owner,query,sinceId,maxId,count,startDateTime,endDateTime,oldTweets,network=self.network,options=self.options,page=page,rpp=rpp,table=table) + result= Connect.Send(msg) + res=self.parseResult(result) + if format=="object": + return self.jsonToObjects(res) + return res + def GetById(self,id,idType,owner='',format="json"): + global msg + if owner=='': + owner=Config.Owner + msg=Job.createGetbyId(owner,id,idType,network=self.network,options=self.options) + result= Connect.Send(msg) + res=self.parseResult(result) + if format=="object": + return self.jsonToObjects(res) + return res + def GetByName(self,name,nameType,owner='',format="json"): + global msg + if owner=='': + owner=Config.Owner + msg=Job.createGetbyName(owner,name,nameType,network=self.network,options=self.options) + result= Connect.Send(msg) + res=self.parseResult(result) + if format=="object": + return self.jsonToObjects(res) + return res + def parseResult(self,res): + global msg + doc = xml.dom.minidom.parseString(res) + res=doc.getElementsByTagName('result')[0] + resType=res.getAttribute('type') + result=res.firstChild.nodeValue + if not result: + return result + if resType=="ERROR": + if result == "Connection Closed by Server": + import time + print "Server closed Connection, trying again in 15 seconds." + time.sleep(15) + result= Connect.Send(msg) + res=self.parseResult(result) + else: + raise Exception(result) + elif resType=="JSON": + return simplejson.loads(result) + diff --git a/client/Client/.svn/text-base/ClientJob.py.svn-base b/client/Client/.svn/text-base/ClientJob.py.svn-base new file mode 100644 index 0000000..fbc0685 --- /dev/null +++ b/client/Client/.svn/text-base/ClientJob.py.svn-base @@ -0,0 +1,137 @@ +import socket,base64,time,sys,subprocess +import os +import hashlib + +def signMessage(owner): + m = hashlib.md5() + m.update("tre"+owner+"ndak") + return m.hexdigest() + +#Provide id, owner and command as string +# inputsFiles as List of file path +def createSearchMessage(owner,query,sinceId=0,maxId=0,count=None,startDateTime=None,endDateTime=None,save="Y",network='',options=None): + sec=signMessage(owner) + f='\n' + f+= '%s'%query + f+= '%s'%sinceId + f+= '%s'%maxId + f+= '%s'%startDateTime + f+= '%s'%endDateTime + #f+= '%s'%format + f+= '%s'%count + f+= '%s'%save + if options!=None: + f+= '' + for option in options.keys(): + f+=""%(option,options[option]) + + f+="" + f+= '' + + #print f + #exit() + + return f + +def createTrackMessage(owner,name,searchWord,fetchAll,network=''): + try: + searchWord = searchWord.encode("utf-8") + except: + searchWord=searchWord.decode('utf-8') + sec=signMessage(owner) + f='\n' + f+="%s"%searchWord + f+="%s"%name + f+="%s"%fetchAll + f+="" + return f + + +def createReteriveMessage(owner,query,sinceId=0,maxId=0,count=None,startDateTime=None,endDateTime=None,oldTweets="N",network="",options=None,page=-1,rpp=100,table="recent"): + sec=signMessage(owner) + f='\n' + f+= '%s'%query + f+= '%s'%sinceId + f+= '%s'%maxId + f+= '%s'%startDateTime + f+= '%s'%endDateTime + #f+= '%s'%format + f+= '%s'%count + f+= '%s'%oldTweets + f+='%s
'%table + if page!=-1: + f+="%s"%page + f+="%s"%rpp + if options!=None: + f+= '' + for option in options.keys(): + f+=""%(option,options[option]) + + f+="" + f+= '
' + return f +def createCountMessage(owner,query,sinceId=0,maxId=0,count=None,startDateTime=None,endDateTime=None,oldTweets="N",network="",options=None): + sec=signMessage(owner) + f='\n' + f+= '%s'%query + f+= '%s'%sinceId + f+= '%s'%maxId + f+= '%s'%startDateTime + f+= '%s'%endDateTime + #f+= '%s'%format + f+= '%s'%count + f+= '%s'%oldTweets + if options!=None: + f+= '' + for option in options.keys(): + f+=""%(option,options[option]) + f+="" + f+= '' + return f +def createGetbyId(owner,id,idType,network="",options=None): + sec=signMessage(owner) + f='\n' + f+="%s"%id + f+="%s"%idType + if options!=None: + f+= '' + for option in options.keys(): + f+=""%(option,options[option]) + f+="" + f+= '' + return f +def createGetbyName(owner,name,nameType,network="",options=None): + sec=signMessage(owner) + f='\n' + f+="%s"%name + f+="%s"%nameType + if options!=None: + f+= '' + for option in options.keys(): + f+=""%(option,options[option]) + f+="" + f+= '' + return f + +def checkJobStatus(Connect,id,owner,waitTillCompleted=True): + sec=base64.encodestring(importKey().encrypt(id+owner,"")[0]) + st = '' + while 1: + res = Connect.Send(st) + #print res + status=res[res.find('status="')+8:][0] + if waitTillCompleted: + print 'status of ' + id + ' = ' + status + else: + return status + if (status!='R' and status!='Q'): break + time.sleep(15) + return status + +def run(excuter): + + PIPE=subprocess.PIPE + p=subprocess.Popen(excuter,stdout=PIPE,stderr=PIPE,shell=True) + p.wait() + st=p.stderr.read() + return p.stdout.read() diff --git a/client/Client/.svn/text-base/Common.py.svn-base b/client/Client/.svn/text-base/Common.py.svn-base new file mode 100644 index 0000000..c34c24a --- /dev/null +++ b/client/Client/.svn/text-base/Common.py.svn-base @@ -0,0 +1,2 @@ +EOM="\n\n###" + diff --git a/client/Client/.svn/text-base/Config.py.svn-base b/client/Client/.svn/text-base/Config.py.svn-base new file mode 100644 index 0000000..c6c4d02 --- /dev/null +++ b/client/Client/.svn/text-base/Config.py.svn-base @@ -0,0 +1,12 @@ +import ConfigParser +import os + + +mainPath=os.path.dirname(os.path.abspath( __file__ ))[:-6]+'' + +config = ConfigParser.RawConfigParser() +config.read(os.path.join(mainPath ,'config' ,'config.cfg')) + +ServerHost=config.get('Server', 'ServerHost') +ServerPort=config.get('Server','ServerPort') +Owner=config.get('Client','ID') diff --git a/client/Client/.svn/text-base/Connect.py.svn-base b/client/Client/.svn/text-base/Connect.py.svn-base new file mode 100644 index 0000000..6540168 --- /dev/null +++ b/client/Client/.svn/text-base/Connect.py.svn-base @@ -0,0 +1,45 @@ +import socket,base64,time,sys,subprocess +import Config +EOM="\n\n###" + +def Send (message): + try: + message = message.encode('utf-8') + except: + message = message.decode('utf-8') + global domain,port + if (isAlive(Config.ServerHost,int(Config.ServerPort))): + client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) + client.connect((Config.ServerHost,int(Config.ServerPort))) + client.send(message+EOM) + chunks=[] + i=0 + while (1): + #i+=1 + buf=client.recv(10000) + chunks.append(str(buf)) + if (EOM in chunks[-1]): + res="".join(chunks)[:-5] + break + return res + + +def isAlive(domain,port): + client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) + secondTime=False + while (1): + try: + client.connect((domain,port)) + client.send("TEST: HELLO\n\n###") + client.close() + if secondTime: + print "Connected To:", domain + break + except IOError: + import time + time.sleep(5) + secondTime=True + print "Trying again...." + return True + +#isAlive('127.0.0.1',5000) diff --git a/client/Client/.svn/text-base/README.svn-base b/client/Client/.svn/text-base/README.svn-base new file mode 100644 index 0000000..36ad4fc --- /dev/null +++ b/client/Client/.svn/text-base/README.svn-base @@ -0,0 +1,6 @@ +[Server] +ServerHost: HOSTNAME/IP OF CRAWL SERVER +ServerPort: CRAWL SERVER PORT + +[Client] +Owner: NAME TO SEND FOR CRAWL SERVER diff --git a/client/Client/.svn/text-base/__init__.py.svn-base b/client/Client/.svn/text-base/__init__.py.svn-base new file mode 100644 index 0000000..3806f70 --- /dev/null +++ b/client/Client/.svn/text-base/__init__.py.svn-base @@ -0,0 +1,3 @@ +#! /usr/bin/env python + +from Client import * diff --git a/client/Client/.svn/text-base/config.cfg.svn-base b/client/Client/.svn/text-base/config.cfg.svn-base new file mode 100644 index 0000000..f23af0e --- /dev/null +++ b/client/Client/.svn/text-base/config.cfg.svn-base @@ -0,0 +1,6 @@ +[Server] +ServerHost: cloud.trendak.com +ServerPort: 5555 + +[Client] +Owner: user1 diff --git a/client/Client/Client.py b/client/Client/Client.py new file mode 100644 index 0000000..53c1f03 --- /dev/null +++ b/client/Client/Client.py @@ -0,0 +1,54 @@ +import Config +import ClientJob as Job +import Connect +import simplejson +import xml.dom.minidom + + +class Client: + scm = "" + options = None + msg = "" + + def __init__(self, scm): + self.scm = scm + + def Clone(self, repo,workdir,key,owner=''): + global msg + if owner == '': + owner = Config.Owner + msg = Job.createCloneMessage(owner, repo, workdir, key, self.scm, options=self.options) + result = Connect.Send(msg) + return result + + def Pull(self, repo,workdir,key,owner=''): + global msg + if owner == '': + owner = Config.Owner + msg = Job.createPullMessage(owner, workdir, self.scm, options=self.options) + result = Connect.Send(msg) + return result + + def ListTags(self,workdir,owner=''): + global msg + if owner == '': + owner = Config.Owner + msg=Job.createListTagsMessage(workdir=workdir,scm=self.scm,owner=owner) + result = Connect.Send(msg) + return result + + def SwitchTag(self,workdir,tag,owner=''): + global msg + if owner == '': + owner = Config.Owner + msg=Job.createSwitchTagMessage(workdir=workdir,tag=tag,scm=self.scm,owner=owner) + result = Connect.Send(msg) + return result + + def Deploy(self,workdir, configFile,owner=''): + global msg + if owner == '': + owner = Config.Owner + msg=Job.createDeployMessage(workdir=workdir,configFile=configFile,scm=self.scm,owner=owner) + result = Connect.Send(msg) + return result diff --git a/client/Client/ClientJob.py b/client/Client/ClientJob.py new file mode 100644 index 0000000..68c82a6 --- /dev/null +++ b/client/Client/ClientJob.py @@ -0,0 +1,93 @@ +import socket, base64, time, sys, subprocess +import os +import hashlib +from Crypto.PublicKey import RSA +from Crypto import Random + +def importKey(): + mainPath=os.path.dirname(os.path.abspath( __file__ )) + file=open(mainPath + "/my",'r') + st = "".join(file.readlines()) + key = RSA.importKey(st) + #print "KEY Opened" , key + return key + + + +# Provide id, owner and command as string +# inputsFiles as List of file path +def createCloneMessage(owner, repo, workdir, key, scm, options=None): + sec=base64.encodestring(importKey().encrypt(owner+scm+"CLONE","")[0]) + f = '\n'%( owner,"CLONE",sec,scm) + f += '%s'%workdir + f += '%s'%repo + f += '%s'%key + if options: + f += '' + for option in options.keys(): + f += "" % (option, options[option]) + + f += "" + f += '' + + + return f + + +def createPullMessage(owner,workdir, scm, options=None): + sec=base64.encodestring(importKey().encrypt(owner+scm+"PULL","")[0]) + f = '\n'%( owner,"PULL",sec,scm) + f += '%s'%workdir + f += '%s'%repo + f += '%s'%key + if options: + f += '' + for option in options.keys(): + f += "" % (option, options[option]) + + f += "" + f += '' + return f + +def createListTagsMessage(owner, workdir, scm, options=None): + sec=base64.encodestring(importKey().encrypt(owner+scm+"LIST-TAGS","")[0]) + f = '\n'%( owner,"LIST-TAGS",sec,scm) + f += '%s'%workdir + if options: + f += '' + for option in options.keys(): + f += "" % (option, options[option]) + + f += "" + f += '' + return f + +def createSwitchTagMessage(owner, workdir, scm, tag, options=None): + sec=base64.encodestring(importKey().encrypt(owner+scm+"SWITCH-TAG","")[0]) + f = '\n'%( owner,"SWITCH-TAG",sec,scm) + f += '%s'%workdir + f += '%s'%tag + + if options: + f += '' + for option in options.keys(): + f += "" % (option, options[option]) + + f += "" + f += '' + return f + +def createDeployMessage(owner, workdir, scm, configFile, options=None): + sec=base64.encodestring(importKey().encrypt(owner+scm+"DEPLOY","")[0]) + f = '\n'%( owner,"DEPLOY",sec,scm) + f += '%s'%workdir + f += '%s'%configFile + + if options: + f += '' + for option in options.keys(): + f += "" % (option, options[option]) + + f += "" + f += '' + return f diff --git a/client/Client/Clients/.svn/all-wcprops b/client/Client/Clients/.svn/all-wcprops new file mode 100644 index 0000000..b69d761 --- /dev/null +++ b/client/Client/Clients/.svn/all-wcprops @@ -0,0 +1,11 @@ +K 25 +svn:wc:ra_dav:version-url +V 47 +/!svn/ver/433/crawl/client/trunk/Client/Clients +END +__init__.py +K 25 +svn:wc:ra_dav:version-url +V 59 +/!svn/ver/433/crawl/client/trunk/Client/Clients/__init__.py +END diff --git a/client/Client/Clients/.svn/entries b/client/Client/Clients/.svn/entries new file mode 100644 index 0000000..4b233d6 --- /dev/null +++ b/client/Client/Clients/.svn/entries @@ -0,0 +1,68 @@ +10 + +dir +436 +http://svn.trendak.com/crawl/client/trunk/Client/Clients +http://svn.trendak.com + + + +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + +82768435-6001-4b23-9c5b-483360495a41 + +Twitter +dir + +__init__.py +file + + + + +2012-10-06T13:20:12.000000Z +d41d8cd98f00b204e9800998ecf8427e +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +0 + +Facebook +dir + diff --git a/client/Client/Clients/.svn/text-base/__init__.py.svn-base b/client/Client/Clients/.svn/text-base/__init__.py.svn-base new file mode 100644 index 0000000..e69de29 diff --git a/client/Client/Clients/Facebook/.svn/all-wcprops b/client/Client/Clients/Facebook/.svn/all-wcprops new file mode 100644 index 0000000..3f5ed86 --- /dev/null +++ b/client/Client/Clients/Facebook/.svn/all-wcprops @@ -0,0 +1,29 @@ +K 25 +svn:wc:ra_dav:version-url +V 56 +/!svn/ver/433/crawl/client/trunk/Client/Clients/Facebook +END +Facebook_User.py +K 25 +svn:wc:ra_dav:version-url +V 73 +/!svn/ver/433/crawl/client/trunk/Client/Clients/Facebook/Facebook_User.py +END +Facebook_Comment.py +K 25 +svn:wc:ra_dav:version-url +V 76 +/!svn/ver/433/crawl/client/trunk/Client/Clients/Facebook/Facebook_Comment.py +END +Facebook_Post.py +K 25 +svn:wc:ra_dav:version-url +V 73 +/!svn/ver/433/crawl/client/trunk/Client/Clients/Facebook/Facebook_Post.py +END +__init__.py +K 25 +svn:wc:ra_dav:version-url +V 68 +/!svn/ver/433/crawl/client/trunk/Client/Clients/Facebook/__init__.py +END diff --git a/client/Client/Clients/Facebook/.svn/entries b/client/Client/Clients/Facebook/.svn/entries new file mode 100644 index 0000000..c76cf05 --- /dev/null +++ b/client/Client/Clients/Facebook/.svn/entries @@ -0,0 +1,164 @@ +10 + +dir +436 +http://svn.trendak.com/crawl/client/trunk/Client/Clients/Facebook +http://svn.trendak.com + + + +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + +82768435-6001-4b23-9c5b-483360495a41 + +Facebook_User.py +file + + + + +2012-10-06T13:20:12.000000Z +f1c96d3c463682e3e1e40e034c52ba65 +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +164 + +Facebook_Comment.py +file + + + + +2012-10-06T13:20:12.000000Z +f1c13ed37e2b569c4660be92461d1f95 +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +522 + +Facebook_Post.py +file + + + + +2012-10-06T13:20:12.000000Z +ecfd66cdfb76df342542d5d0ecf50bd8 +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +903 + +__init__.py +file + + + + +2012-10-06T13:20:12.000000Z +d41d8cd98f00b204e9800998ecf8427e +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +0 + diff --git a/client/Client/Clients/Facebook/.svn/text-base/Facebook_Comment.py.svn-base b/client/Client/Clients/Facebook/.svn/text-base/Facebook_Comment.py.svn-base new file mode 100644 index 0000000..db65fa1 --- /dev/null +++ b/client/Client/Clients/Facebook/.svn/text-base/Facebook_Comment.py.svn-base @@ -0,0 +1,12 @@ +class Comment(object): + def __init__(self,comment_id,user,message,creation_date,creation_time,likes_count,user_likes,can_remove,sentiment=None,ontologies=[],entities=[]): + self.id = comment_id + self.user = user + self.text = message + self.creation_date = creation_date + self.creation_time = creation_time + self.likes_count = likes_count + self.can_remove = can_remove + self.sentiment = sentiment + self.ontologies = ontologies + self.entities = entities \ No newline at end of file diff --git a/client/Client/Clients/Facebook/.svn/text-base/Facebook_Post.py.svn-base b/client/Client/Clients/Facebook/.svn/text-base/Facebook_Post.py.svn-base new file mode 100644 index 0000000..3eec898 --- /dev/null +++ b/client/Client/Clients/Facebook/.svn/text-base/Facebook_Post.py.svn-base @@ -0,0 +1,21 @@ +class Post(object): + def __init__(self,crawl_id,post_id,user,post_type,creation_date,creation_time,updated_date,updated_time,comments_count,likes_count,message=None,link=None,picture=None,icon=None,comments=[],likes=[],sentiment=None,entities=[],ontologies=[]): + self.id = post_id + self.CrawlId = crawl_id + self.text = message + self.user = user + self.type = post_type + self.creation_date = creation_date + self.creation_time = creation_time + self.updated_date = updated_date + self.updated_time = updated_time + self.comments_count = comments_count + self.likes_count = likes_count + self.link = link + self.picture = picture + self.icon = icon + self.sentiment = sentiment + self.ontologies = ontologies + self.entities = entities + self.comments = comments + self.likes = likes \ No newline at end of file diff --git a/client/Client/Clients/Facebook/.svn/text-base/Facebook_User.py.svn-base b/client/Client/Clients/Facebook/.svn/text-base/Facebook_User.py.svn-base new file mode 100644 index 0000000..d12f6c2 --- /dev/null +++ b/client/Client/Clients/Facebook/.svn/text-base/Facebook_User.py.svn-base @@ -0,0 +1,5 @@ +class User(object): + def __init__(self,user_id,user_name,category=None): + self.id = user_id + self.name = user_name + self.category = category \ No newline at end of file diff --git a/client/Client/Clients/Facebook/.svn/text-base/__init__.py.svn-base b/client/Client/Clients/Facebook/.svn/text-base/__init__.py.svn-base new file mode 100644 index 0000000..e69de29 diff --git a/client/Client/Clients/Facebook/Facebook_Comment.py b/client/Client/Clients/Facebook/Facebook_Comment.py new file mode 100644 index 0000000..db65fa1 --- /dev/null +++ b/client/Client/Clients/Facebook/Facebook_Comment.py @@ -0,0 +1,12 @@ +class Comment(object): + def __init__(self,comment_id,user,message,creation_date,creation_time,likes_count,user_likes,can_remove,sentiment=None,ontologies=[],entities=[]): + self.id = comment_id + self.user = user + self.text = message + self.creation_date = creation_date + self.creation_time = creation_time + self.likes_count = likes_count + self.can_remove = can_remove + self.sentiment = sentiment + self.ontologies = ontologies + self.entities = entities \ No newline at end of file diff --git a/client/Client/Clients/Facebook/Facebook_Post.py b/client/Client/Clients/Facebook/Facebook_Post.py new file mode 100644 index 0000000..3eec898 --- /dev/null +++ b/client/Client/Clients/Facebook/Facebook_Post.py @@ -0,0 +1,21 @@ +class Post(object): + def __init__(self,crawl_id,post_id,user,post_type,creation_date,creation_time,updated_date,updated_time,comments_count,likes_count,message=None,link=None,picture=None,icon=None,comments=[],likes=[],sentiment=None,entities=[],ontologies=[]): + self.id = post_id + self.CrawlId = crawl_id + self.text = message + self.user = user + self.type = post_type + self.creation_date = creation_date + self.creation_time = creation_time + self.updated_date = updated_date + self.updated_time = updated_time + self.comments_count = comments_count + self.likes_count = likes_count + self.link = link + self.picture = picture + self.icon = icon + self.sentiment = sentiment + self.ontologies = ontologies + self.entities = entities + self.comments = comments + self.likes = likes \ No newline at end of file diff --git a/client/Client/Clients/Facebook/Facebook_User.py b/client/Client/Clients/Facebook/Facebook_User.py new file mode 100644 index 0000000..d12f6c2 --- /dev/null +++ b/client/Client/Clients/Facebook/Facebook_User.py @@ -0,0 +1,5 @@ +class User(object): + def __init__(self,user_id,user_name,category=None): + self.id = user_id + self.name = user_name + self.category = category \ No newline at end of file diff --git a/client/Client/Clients/Facebook/__init__.py b/client/Client/Clients/Facebook/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/client/Client/Clients/Twitter/.svn/all-wcprops b/client/Client/Clients/Twitter/.svn/all-wcprops new file mode 100644 index 0000000..c35f0cd --- /dev/null +++ b/client/Client/Clients/Twitter/.svn/all-wcprops @@ -0,0 +1,23 @@ +K 25 +svn:wc:ra_dav:version-url +V 55 +/!svn/ver/433/crawl/client/trunk/Client/Clients/Twitter +END +Tweet.py +K 25 +svn:wc:ra_dav:version-url +V 64 +/!svn/ver/433/crawl/client/trunk/Client/Clients/Twitter/Tweet.py +END +__init__.py +K 25 +svn:wc:ra_dav:version-url +V 67 +/!svn/ver/433/crawl/client/trunk/Client/Clients/Twitter/__init__.py +END +Twitter_user.py +K 25 +svn:wc:ra_dav:version-url +V 71 +/!svn/ver/433/crawl/client/trunk/Client/Clients/Twitter/Twitter_user.py +END diff --git a/client/Client/Clients/Twitter/.svn/entries b/client/Client/Clients/Twitter/.svn/entries new file mode 100644 index 0000000..5b69473 --- /dev/null +++ b/client/Client/Clients/Twitter/.svn/entries @@ -0,0 +1,130 @@ +10 + +dir +436 +http://svn.trendak.com/crawl/client/trunk/Client/Clients/Twitter +http://svn.trendak.com + + + +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + +82768435-6001-4b23-9c5b-483360495a41 + +Tweet.py +file + + + + +2012-10-06T13:20:12.000000Z +4424ebc51e2c50997cba14e8c0cd699a +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +1405 + +__init__.py +file + + + + +2012-10-06T13:20:12.000000Z +68b329da9893e34099c7d8ad5cb9c940 +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +1 + +Twitter_user.py +file + + + + +2012-10-06T13:20:12.000000Z +44191904a272c167f3e1c4b52a364e91 +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +684 + diff --git a/client/Client/Clients/Twitter/.svn/text-base/Tweet.py.svn-base b/client/Client/Clients/Twitter/.svn/text-base/Tweet.py.svn-base new file mode 100644 index 0000000..a46f76f --- /dev/null +++ b/client/Client/Clients/Twitter/.svn/text-base/Tweet.py.svn-base @@ -0,0 +1,34 @@ +class Tweet(object): + def __init__(self,crawl_id,tweet_id,User=None,text='',creation_time=None,creation_date=None,source=None,links=None,hashtags=None,mentions=None,in_reply_to_Tweet=None,in_reply_to_User=None,retweet_count=None,ontologies=None,entities=None,sentiment=None,retweeters=None): + self.CrawlId = crawl_id + self.id = tweet_id + self.text = text + self.creation_time = creation_time + self.creation_date = creation_date + self.source = source + self.links = links + if not(self.links == []): + self.include_links = 1 + else: + self.include_links = 0 + self.hashtags = hashtags + self.ontologies = ontologies + self.entities = entities + self.sentiment = sentiment + self.in_reply_to_Tweet = in_reply_to_Tweet + self.in_reply_to_User = in_reply_to_User + self.mentions = mentions + if self.in_reply_to_Tweet or self.in_reply_to_User: + self.is_reply = 1 + else: + self.is_reply = 0 + if not(self.mentions == []) and not(self.is_reply == 1): + self.is_mention = 1 + else: + self.is_mention = 0 + self.retweet_count = retweet_count + self.User = User + self.retweeters = retweeters + self.hour = 0 + if self.creation_time: + self.hour = int(self.creation_time.split(":")[0]) diff --git a/client/Client/Clients/Twitter/.svn/text-base/Twitter_user.py.svn-base b/client/Client/Clients/Twitter/.svn/text-base/Twitter_user.py.svn-base new file mode 100644 index 0000000..9916acf --- /dev/null +++ b/client/Client/Clients/Twitter/.svn/text-base/Twitter_user.py.svn-base @@ -0,0 +1,14 @@ +class User (object): + def __init__(self,user_id,screen_name,user_name=None,friends_count=None,followers_count=None,listed_count=None,Tweets_count=None,creation_time=None,creation_date=None,description=None,favourites_count=None): + self.id = user_id + self.screen_name = screen_name + self.user_name = user_name + self.friends_count = friends_count + self.followers_count = followers_count + self.listed_count = listed_count + self.Tweets_count = Tweets_count + self.creation_time = creation_time + self.creation_date = creation_date + self.description = description + self.favourites_count = favourites_count + diff --git a/client/Client/Clients/Twitter/.svn/text-base/__init__.py.svn-base b/client/Client/Clients/Twitter/.svn/text-base/__init__.py.svn-base new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/client/Client/Clients/Twitter/.svn/text-base/__init__.py.svn-base @@ -0,0 +1 @@ + diff --git a/client/Client/Clients/Twitter/Tweet.py b/client/Client/Clients/Twitter/Tweet.py new file mode 100644 index 0000000..a46f76f --- /dev/null +++ b/client/Client/Clients/Twitter/Tweet.py @@ -0,0 +1,34 @@ +class Tweet(object): + def __init__(self,crawl_id,tweet_id,User=None,text='',creation_time=None,creation_date=None,source=None,links=None,hashtags=None,mentions=None,in_reply_to_Tweet=None,in_reply_to_User=None,retweet_count=None,ontologies=None,entities=None,sentiment=None,retweeters=None): + self.CrawlId = crawl_id + self.id = tweet_id + self.text = text + self.creation_time = creation_time + self.creation_date = creation_date + self.source = source + self.links = links + if not(self.links == []): + self.include_links = 1 + else: + self.include_links = 0 + self.hashtags = hashtags + self.ontologies = ontologies + self.entities = entities + self.sentiment = sentiment + self.in_reply_to_Tweet = in_reply_to_Tweet + self.in_reply_to_User = in_reply_to_User + self.mentions = mentions + if self.in_reply_to_Tweet or self.in_reply_to_User: + self.is_reply = 1 + else: + self.is_reply = 0 + if not(self.mentions == []) and not(self.is_reply == 1): + self.is_mention = 1 + else: + self.is_mention = 0 + self.retweet_count = retweet_count + self.User = User + self.retweeters = retweeters + self.hour = 0 + if self.creation_time: + self.hour = int(self.creation_time.split(":")[0]) diff --git a/client/Client/Clients/Twitter/Twitter_user.py b/client/Client/Clients/Twitter/Twitter_user.py new file mode 100644 index 0000000..9916acf --- /dev/null +++ b/client/Client/Clients/Twitter/Twitter_user.py @@ -0,0 +1,14 @@ +class User (object): + def __init__(self,user_id,screen_name,user_name=None,friends_count=None,followers_count=None,listed_count=None,Tweets_count=None,creation_time=None,creation_date=None,description=None,favourites_count=None): + self.id = user_id + self.screen_name = screen_name + self.user_name = user_name + self.friends_count = friends_count + self.followers_count = followers_count + self.listed_count = listed_count + self.Tweets_count = Tweets_count + self.creation_time = creation_time + self.creation_date = creation_date + self.description = description + self.favourites_count = favourites_count + diff --git a/client/Client/Clients/Twitter/__init__.py b/client/Client/Clients/Twitter/__init__.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/client/Client/Clients/Twitter/__init__.py @@ -0,0 +1 @@ + diff --git a/client/Client/Clients/__init__.py b/client/Client/Clients/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/client/Client/Common.py b/client/Client/Common.py new file mode 100644 index 0000000..c34c24a --- /dev/null +++ b/client/Client/Common.py @@ -0,0 +1,2 @@ +EOM="\n\n###" + diff --git a/client/Client/Config.py b/client/Client/Config.py new file mode 100644 index 0000000..c6c4d02 --- /dev/null +++ b/client/Client/Config.py @@ -0,0 +1,12 @@ +import ConfigParser +import os + + +mainPath=os.path.dirname(os.path.abspath( __file__ ))[:-6]+'' + +config = ConfigParser.RawConfigParser() +config.read(os.path.join(mainPath ,'config' ,'config.cfg')) + +ServerHost=config.get('Server', 'ServerHost') +ServerPort=config.get('Server','ServerPort') +Owner=config.get('Client','ID') diff --git a/client/Client/Connect.py b/client/Client/Connect.py new file mode 100644 index 0000000..bc1747f --- /dev/null +++ b/client/Client/Connect.py @@ -0,0 +1,48 @@ +import socket,base64,time,sys,subprocess +import Config +EOM="\n\n###" + +def Send (message): + try: + message = message.encode('utf-8') + except: + message = message.decode('utf-8') + global domain,port + if (isAlive(Config.ServerHost,int(Config.ServerPort))): + client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) + client.connect((Config.ServerHost,int(Config.ServerPort))) + client.send(message+EOM) + chunks=[] + i=0 + while (1): + #i+=1 + buf=client.recv(10000) + if len(buf)<5: + chunks[-1]+=buf + else: + chunks.append(str(buf)) + if (EOM in chunks[-1]): + res="".join(chunks)[:-5] + break + return res + + +def isAlive(domain,port): + client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) + secondTime=False + while (1): + try: + client.connect((domain,port)) + client.send("TEST: HELLO\n\n###") + client.close() + if secondTime: + print "Connected To:", domain + break + except IOError: + import time + time.sleep(5) + secondTime=True + print "Trying again...." + return True + +#isAlive('127.0.0.1',5000) diff --git a/client/Client/README b/client/Client/README new file mode 100644 index 0000000..36ad4fc --- /dev/null +++ b/client/Client/README @@ -0,0 +1,6 @@ +[Server] +ServerHost: HOSTNAME/IP OF CRAWL SERVER +ServerPort: CRAWL SERVER PORT + +[Client] +Owner: NAME TO SEND FOR CRAWL SERVER diff --git a/client/Client/__init__.py b/client/Client/__init__.py new file mode 100644 index 0000000..3806f70 --- /dev/null +++ b/client/Client/__init__.py @@ -0,0 +1,3 @@ +#! /usr/bin/env python + +from Client import * diff --git a/client/Client/my b/client/Client/my new file mode 100644 index 0000000..74623d4 --- /dev/null +++ b/client/Client/my @@ -0,0 +1,6 @@ +-----BEGIN PUBLIC KEY----- +MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDN7vNOsnnfZlF1EJvtNX4pmu4w +hFQB771iHF1tMcb/t+QO9iHdOO8kirvHWAVY4uf7GsgXujYNNQaG/8O64BRTHSs0 +LZIWtr4OiBjKTF8aLn7kXbMCZ/I7vDm0WKNATN8VpLJxDv/78UMbZN1yM0qIFAME +g9M7HZyvoMh+ieCNZwIDAQAB +-----END PUBLIC KEY----- \ No newline at end of file diff --git a/client/__init__.py b/client/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/client/config/.svn/all-wcprops b/client/config/.svn/all-wcprops new file mode 100644 index 0000000..8d7319c --- /dev/null +++ b/client/config/.svn/all-wcprops @@ -0,0 +1,11 @@ +K 25 +svn:wc:ra_dav:version-url +V 39 +/!svn/ver/433/crawl/client/trunk/config +END +config.cfg +K 25 +svn:wc:ra_dav:version-url +V 50 +/!svn/ver/433/crawl/client/trunk/config/config.cfg +END diff --git a/client/config/.svn/entries b/client/config/.svn/entries new file mode 100644 index 0000000..d5a814f --- /dev/null +++ b/client/config/.svn/entries @@ -0,0 +1,62 @@ +10 + +dir +436 +http://svn.trendak.com/crawl/client/trunk/config +http://svn.trendak.com + + + +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + +82768435-6001-4b23-9c5b-483360495a41 + +config.cfg +file + + + + +2012-10-06T13:20:12.000000Z +84fa997113a4600f5b2d466e7cfd3293 +2012-10-06T13:29:56.184943Z +433 +mkalioby + + + + + + + + + + + + + + + + + + + + + +68 + diff --git a/client/config/.svn/text-base/config.cfg.svn-base b/client/config/.svn/text-base/config.cfg.svn-base new file mode 100644 index 0000000..d79cf07 --- /dev/null +++ b/client/config/.svn/text-base/config.cfg.svn-base @@ -0,0 +1,6 @@ +[Server] +ServerHost: localhost +ServerPort: 5555 + +[Client] +ID: user1 diff --git a/client/config/config.cfg b/client/config/config.cfg new file mode 100644 index 0000000..871f6d2 --- /dev/null +++ b/client/config/config.cfg @@ -0,0 +1,6 @@ +[Server] +ServerHost: localhost +ServerPort: 5000 + +[Client] +ID: user1 diff --git a/client/test.py b/client/test.py new file mode 100644 index 0000000..76c7e00 --- /dev/null +++ b/client/test.py @@ -0,0 +1,69 @@ +__author__ = 'mohamed' +import Client.Client as Client +def test_clone(): + c=Client("git") + return c.Clone("git@github.com:mkalioby/CD_Project.git","/tmp/CD_Project/","""-----BEGIN RSA PRIVATE KEY----- +MIIEpQIBAAKCAQEAs53ey/L9eX7WKi7UtlJo+1Rw9DmWj5XLIWfn9FOyUNFeUOS9 +DcgTe7dFMfpiTMBXQ2mzdgN7NtlxPZts7cIF3YXkftPHz5Afhezi6PXgfJOZcfkN +srLzvfxChG2q7+v4Ktar+jbj/Y59JYvPJTBBUWlPDhqVgLMhaA3kFtIeg+7AesUW +M1Ituuk+zWl+hzQyZk4tyZ9fKrJqhu1UxQnYi1CTWlXx42E8Xzk9iV3UGfimdYl+ +jTgD7S+bvoFgQYysRp7AubiW2DTMcUt8Yh/Za89WFhHqy8R/nMW6ek+0O1Ze1LAd +orbg3hasBrQgTgP1Vp/LnDVjFKJ/0KLkgJCaRwIDAQABAoIBAQCZodcHq3eTjCGz +Qws+R470Km3S988IUZ/FmxKTsWM8LVj26C+ssg24LDJLZVbfP0Vkq+yMbL3fVG2/ +vEmXs/VAXV3r/UlTCHtuGgicKnMxGy6MhfJpfxds0XAzxXoIbVV/js7a3kh0gIQa +sVMlA/laoTC1Z5eo1Y8laXxG6MKhJQ7U/KS9KK3SWT+XZxEkaiV03TyvgdWWYsbA +QiUKUa+oCPKxgVUDVERsnrDL9e47Pma6ct7VJWc12rXUDhGhoF0CloGI4QoSfOGG +7lOENljsBhsQjr41Mm0iVob8KRDJ+dkvdl8a/BMJB4tFIhsrMp3gqSRNyRRlFpJq +ZeR4bvxBAoGBAOCUJpo02QVDys+wPAOw52GxfpW0HBqLDPua6NVaf8L+vLjBtFte +Cp4XDtjgoFm3tNnr/NLhegf9jrERa0spgPK7jTQ3edNTJbyiyR8QWgeqRuravIzr +ZClq0FMHTNGamW1e2hstL2nhCIqJID4wdt8J2dXX+uIOFZ5xsmYXD/mzAoGBAMy/ +SqpZPNykPmSpek9q8g3VbJ0tYHas6B9fIoqvYH+aIRXYOFZ0MpiUEiVVAgtGn5DM +gros1kvlY9metdLSLpXVzYnhjY5YawBx0iVDZ/ARsePgR76tCrmMXaHR2wolDi6v +0aHIFWAYJv3PpaNJqKqByjZBaLXvvS6HMxDHTusdAoGBAIlt/+V0G65eGvlXhpJX +qnCdNrKT4nLXzt0VohAV7oM8ce66Ew2qkeLGh35uj5H3moOVJ0VBV/UV1EFFQJxh +TJi97x4aKMIKathx4ZPR5NY1/Gnx61ptHgE+bTeyCu9lpShJ2DyzPQWVAS4N1h5Y +eBXrKFP1dIDrT42DVEGnMU6DAoGBAL3gVLT/xvJzmq0tgpEuA8YSfASTdVb5aNbX +Gih1Fc+gNziT6UM7xUQ8ZUubtyaP2yCkmENhm2aNF/lUNxiI9MzdlxxcQTOWCb1C +0Pjftv8q2ccTUlWhEkYaxyZvgGu7C5j+UjFvZWtVWqucquZwQ+vEK6v/IsU+zDnf +Bdt0ilp9AoGAbQ0JvhO7UozrP+x6cYjccOm76pDGnuPzByIlm6Hmckce6wjOJKUv +/S2BW1etxhhSt33YcDl5EGeLNUeITSTs0B6CkmhEAopnQfBotBAJBlu/uWF6mQSp +u7Kcu+PqQ1vWMOTM6GpWEAd6Xol2WvP6WolIH4udOR05i/l7dhXRM6Q= +-----END RSA PRIVATE KEY-----""") + +def test_pull(): + c=Client("git") + return c.Pull("git@github.com:mkalioby/CD_Project.git","/tmp/CD_Project/","""-----BEGIN RSA PRIVATE KEY----- +MIIEpQIBAAKCAQEAs53ey/L9eX7WKi7UtlJo+1Rw9DmWj5XLIWfn9FOyUNFeUOS9 +DcgTe7dFMfpiTMBXQ2mzdgN7NtlxPZts7cIF3YXkftPHz5Afhezi6PXgfJOZcfkN +srLzvfxChG2q7+v4Ktar+jbj/Y59JYvPJTBBUWlPDhqVgLMhaA3kFtIeg+7AesUW +M1Ituuk+zWl+hzQyZk4tyZ9fKrJqhu1UxQnYi1CTWlXx42E8Xzk9iV3UGfimdYl+ +jTgD7S+bvoFgQYysRp7AubiW2DTMcUt8Yh/Za89WFhHqy8R/nMW6ek+0O1Ze1LAd +orbg3hasBrQgTgP1Vp/LnDVjFKJ/0KLkgJCaRwIDAQABAoIBAQCZodcHq3eTjCGz +Qws+R470Km3S988IUZ/FmxKTsWM8LVj26C+ssg24LDJLZVbfP0Vkq+yMbL3fVG2/ +vEmXs/VAXV3r/UlTCHtuGgicKnMxGy6MhfJpfxds0XAzxXoIbVV/js7a3kh0gIQa +sVMlA/laoTC1Z5eo1Y8laXxG6MKhJQ7U/KS9KK3SWT+XZxEkaiV03TyvgdWWYsbA +QiUKUa+oCPKxgVUDVERsnrDL9e47Pma6ct7VJWc12rXUDhGhoF0CloGI4QoSfOGG +7lOENljsBhsQjr41Mm0iVob8KRDJ+dkvdl8a/BMJB4tFIhsrMp3gqSRNyRRlFpJq +ZeR4bvxBAoGBAOCUJpo02QVDys+wPAOw52GxfpW0HBqLDPua6NVaf8L+vLjBtFte +Cp4XDtjgoFm3tNnr/NLhegf9jrERa0spgPK7jTQ3edNTJbyiyR8QWgeqRuravIzr +ZClq0FMHTNGamW1e2hstL2nhCIqJID4wdt8J2dXX+uIOFZ5xsmYXD/mzAoGBAMy/ +SqpZPNykPmSpek9q8g3VbJ0tYHas6B9fIoqvYH+aIRXYOFZ0MpiUEiVVAgtGn5DM +gros1kvlY9metdLSLpXVzYnhjY5YawBx0iVDZ/ARsePgR76tCrmMXaHR2wolDi6v +0aHIFWAYJv3PpaNJqKqByjZBaLXvvS6HMxDHTusdAoGBAIlt/+V0G65eGvlXhpJX +qnCdNrKT4nLXzt0VohAV7oM8ce66Ew2qkeLGh35uj5H3moOVJ0VBV/UV1EFFQJxh +TJi97x4aKMIKathx4ZPR5NY1/Gnx61ptHgE+bTeyCu9lpShJ2DyzPQWVAS4N1h5Y +eBXrKFP1dIDrT42DVEGnMU6DAoGBAL3gVLT/xvJzmq0tgpEuA8YSfASTdVb5aNbX +Gih1Fc+gNziT6UM7xUQ8ZUubtyaP2yCkmENhm2aNF/lUNxiI9MzdlxxcQTOWCb1C +0Pjftv8q2ccTUlWhEkYaxyZvgGu7C5j+UjFvZWtVWqucquZwQ+vEK6v/IsU+zDnf +Bdt0ilp9AoGAbQ0JvhO7UozrP+x6cYjccOm76pDGnuPzByIlm6Hmckce6wjOJKUv +/S2BW1etxhhSt33YcDl5EGeLNUeITSTs0B6CkmhEAopnQfBotBAJBlu/uWF6mQSp +u7Kcu+PqQ1vWMOTM6GpWEAd6Xol2WvP6WolIH4udOR05i/l7dhXRM6Q= +-----END RSA PRIVATE KEY-----""") + +def testTagsList(): + c=Client("git") + return c.ListTags("/tmp/SGP_Registry") +if __name__=="__main__": + #print test_clone() + #print test_pull() + print testTagsList() diff --git a/deployer/Common.py b/deployer/Common.py deleted file mode 100755 index d6807c5..0000000 --- a/deployer/Common.py +++ /dev/null @@ -1,25 +0,0 @@ -import subprocess -EOM = "\n\n###" - - - -def run(executer,raiseError=True,id=None): - PIPE = subprocess.PIPE - p = subprocess.Popen(executer, stdout=PIPE, stderr=PIPE, shell=True) - (stdout, stderr) = p.communicate() - st = stderr - if id: - f = open("/tmp/" + id + ".err", 'w') - f.write(st) - f.flush() - f.close() - f = open("/tmp/" + id + ".out", 'w') - f.write(stdout) - f.flush() - f.close() - - if len(stderr) > 0: - if raiseError: - raise StandardError(stderr[5:]) - return "ERR:"+stderr - return stdout diff --git a/exampleConfig/registry.yaml b/exampleConfig/registry.yaml new file mode 100644 index 0000000..9fec9c6 --- /dev/null +++ b/exampleConfig/registry.yaml @@ -0,0 +1,16 @@ +files: + - source: / + destination: /var/www/SGP_Registry2/ + +permissions: + - object: /var/www/SGP_Registry2/ + owner: mohamed + group: users + mode: 755 + type: directory + +events: + afterInstall: + - location: "/var/www/SGP_Registry2/manage.py runserver 0.0.0.0:8001" + interpreter: python + wait: False diff --git a/server/Common.py b/server/Common.py index 322f4cd..a6a8af7 100755 --- a/server/Common.py +++ b/server/Common.py @@ -18,6 +18,7 @@ def run(executer, id=None): f.flush() f.close() - if len(stderr) > 0: + if len(stderr) > 0 and "fatal" in stderr: return "ERR:"+stderr + if stdout=="": return "Done" return stdout diff --git a/server/Config.cfg b/server/Config.cfg index fa87941..b260646 100755 --- a/server/Config.cfg +++ b/server/Config.cfg @@ -1,4 +1,4 @@ [Server] port: 5000 -publicKey: /root/EHPC/client.pub +publicKey: client.pub diff --git a/server/Request.py b/server/Request.py index 233bcac..6ced27e 100755 --- a/server/Request.py +++ b/server/Request.py @@ -1,94 +1,108 @@ -import socket,threading,subprocess,os,base64,xml.dom.minidom -def getOutputList(message): - doc = xml.dom.minidom.parseString(message) - folders=doc.getElementsByTagName("folder") - outputFilesList=[] - for folder in folders: - path=folder.getAttribute("path") - #print 'In folder:' , path - if (not os.path.exists(path)): os.makedirs(path) - outputs = folder.getElementsByTagName("output") - if (outputs!=None): - for output in outputs: - filename= output.getAttribute('filename') - outputFilesList.append(path+'/' +filename) - return outputFilesList +import socket, threading, subprocess, os, base64, xml.dom.minidom +import config + def parseRequest(message): - doc = xml.dom.minidom.parseString(message) - Job=doc.getElementsByTagName('job') - owner=Job[0].getAttribute('owner') - JobID=Job[0].getAttribute('id') - requestType=Job[0].getAttribute('type') - sec=Job[0].getAttribute('sec') - return {'JobID':JobID,"Owner":owner,"requestType":requestType,"sec":sec} - -def parseJob(message): - import os - allinputs=[] - alloutputs=[] - doc = xml.dom.minidom.parseString(message) - Job=doc.getElementsByTagName('job') - owner=Job[0].getAttribute('owner') - JobID=Job[0].getAttribute('id') - requestType=Job[0].getAttribute('type') - print 'Recieved New Job' + JobID + '.....' - command = base64.decodestring(doc.getElementsByTagName("command")[0].firstChild.nodeValue) - #print 'command:' + command - folders=doc.getElementsByTagName("folder") - if folders !=None: - for folder in folders: - path=folder.getAttribute("path") - #print 'In folder:' , path - if (not os.path.exists(path)): - os.makedirs(path) - run ("chmod 777 " + path) - inputs = folder.getElementsByTagName("input") - if (inputs!=None): - for input in inputs: - filename= input.getAttribute('filename') - text=input.firstChild.nodeValue - content=base64.decodestring(text) - #print "file '" , filename + "'\n" + content - allinputs.append(path+'/' +filename) - file= open(path+"/"+filename,'w') - file.write(content) - file.flush() - file.close() - outputs=folder.getElementsByTagName("output") - if (outputs!=None): - for out in outputs: - filename= out.getAttribute('filename') - alloutputs.append(path+'/'+filename) - global JOBS - #JOBS[JobID]=[owner,'R'] - #print "output files: " , str(outputFilesList) - return {"JobID":JobID,"Owner":owner, "command":command,"inputs":allinputs,"outputs":alloutputs} -# return [command,outputFilesList,id] -def run(excuter,id=None): + doc = xml.dom.minidom.parseString(message) + Job = doc.getElementsByTagName('job') + owner = Job[0].getAttribute('owner') + requestType = Job[0].getAttribute('type') + sec = Job[0].getAttribute('sec') + scm = Job[0].getAttribute('scm') + return {"Owner": owner, "requestType": requestType, "sec": sec,"scm":scm} + + +def getValue(node, name): + res = node.getElementsByTagName(name)[0].firstChild.nodeValue + if res == "None": + return None + return res + + +def parseCloneJob(message): + #print message + params = {} + optionsDict = {} + doc = xml.dom.minidom.parseString(message) + Job = doc.getElementsByTagName('job')[0] + repo= getValue(Job, 'repo') + key= getValue(Job, 'sshkey') + scm=Job.getAttribute("scm") + workdir= getValue(Job, 'workdir') + + requestType = Job.getAttribute('type') + owner = Job.getAttribute('owner') + """options = (Job.getElementsByTagName('option')) + for option in options: + name = option.getAttribute("name") + optionsDict[name] = option.firstChild.nodeValue + """ + print 'Recieved New Job from ' + owner + '.....' + params = {"repo":repo, "key": key,"workdir": workdir,"owner": owner, "requestType": requestType, + "scm":scm,"options": optionsDict} + return params + +def parsePullJob(message): + return parseListTagsJob(message) + +def parseListTagsJob(message): + params = {} + optionsDict = {} + doc = xml.dom.minidom.parseString(message) + Job = doc.getElementsByTagName('job')[0] + scm=Job.getAttribute("scm") + workdir= getValue(Job, 'workdir') + + requestType = Job.getAttribute('type') + owner = Job.getAttribute('owner') + """options = (Job.getElementsByTagName('option')) + for option in options: + name = option.getAttribute("name") + optionsDict[name] = option.firstChild.nodeValue + """ + print 'Recieved New Job from ' + owner + '.....' + params = {"workdir": workdir,"owner": owner, "requestType": requestType, + "scm":scm,"options": optionsDict} + return params - PIPE=subprocess.PIPE - p=subprocess.Popen(excuter,stdout=PIPE,stderr=PIPE,shell=True) - (stderr,stdout)= p.communicate() - st=stderr - if (id!=None): - f = open("/tmp/"+id+".err",'w') - f.write(st) - f.flush() - f.close() - f = open("/tmp/"+id+".out",'w') - f.write(stdout) - f.flush() - f.close() - return stderr -# if len(st)>0: - # f = open("/tmp/ToolService.err",'w') - # f.write(st) - # f.flush() -# f.close() - # return "Childerr:", st +def parseSwitchTagJob(message): + params = {} + optionsDict = {} + doc = xml.dom.minidom.parseString(message) + Job = doc.getElementsByTagName('job')[0] + scm=Job.getAttribute("scm") + workdir= getValue(Job, 'workdir') + tag=getValue(Job,"tag") + requestType = Job.getAttribute('type') + owner = Job.getAttribute('owner') + """options = (Job.getElementsByTagName('option')) + for option in options: + name = option.getAttribute("name") + optionsDict[name] = option.firstChild.nodeValue + """ + print 'Recieved New Job from ' + owner + '.....' + params = {"workdir": workdir,"owner": owner, "requestType": requestType,"tag":tag, + "scm":scm,"options": optionsDict} + return params - # else: - return stdout +def parseDeployJob(message): + params = {} + optionsDict = {} + doc = xml.dom.minidom.parseString(message) + Job = doc.getElementsByTagName('job')[0] + scm=Job.getAttribute("scm") + workdir= getValue(Job, 'workdir') + configFile=getValue(Job,"configFile") + requestType = Job.getAttribute('type') + owner = Job.getAttribute('owner') + """options = (Job.getElementsByTagName('option')) + for option in options: + name = option.getAttribute("name") + optionsDict[name] = option.firstChild.nodeValue + """ + print 'Recieved New Job from ' + owner + '.....' + params = {"workdir": workdir,"owner": owner, "requestType": requestType,"configFile":configFile, + "scm":scm,"options": optionsDict} + return params \ No newline at end of file diff --git a/server/__init__.py b/server/__init__.py new file mode 100644 index 0000000..91ba68b --- /dev/null +++ b/server/__init__.py @@ -0,0 +1 @@ +__author__ = 'mohamed' diff --git a/server/autodeploy-server.py b/server/autodeploy-server.py index 3257ae0..b56ea6f 100755 --- a/server/autodeploy-server.py +++ b/server/autodeploy-server.py @@ -7,8 +7,10 @@ import Response import Request import Common - - +import scm.Git as git +from deployer import autodeployer +import traceback +import yaml JOBS = {} EOM = Common.EOM @@ -33,7 +35,7 @@ def importKey(): def validReq(req): key = importKey() decrypted = key.decrypt(base64.decodestring(req["sec"])) - if (req["JobID"] + req["Owner"] == decrypted): + if (req["Owner"]+req["scm"]+req["requestType"] == decrypted): return True else: return False @@ -44,11 +46,13 @@ def HandleClient(clientsock): print name, ' Started.............' global EOM chunks = [] + cmd="" while 1: buf = clientsock.recv(2048) chunks.append(str(buf)) if (EOM in chunks[-1]): msg = "".join(chunks)[:-5] + print msg if (msg == "TEST: HELLO"): return req = Request.parseRequest(msg) @@ -57,16 +61,43 @@ def HandleClient(clientsock): print "invalid request" clientsock.close() return - if (req["requestType"] == "SUBMIT"): - job = Request.parseJob(msg) - global JOBS - if (req["Owner"] == "system" or req["Owner"] == "utils"): - res = Common.run(job["command"], req["JobID"]) - if req["Owner"] == "system": - Response.sendData(clientsock, "Done") - else: - Response.sendData(clientsock, res) - clientsock.close() + if (req["requestType"]=="CLONE"): + job = Request.parseCloneJob(msg) + if job["scm"]=="git": + gclient=git.GIT(job["repo"],job["workdir"]) + gclient.setKey(job["key"]) + cmd=gclient.get_clone_cmd() + elif (req["requestType"] == "PULL"): + job = Request.parsePullJob(msg) + if job["scm"]=="git": + gclient=git.GIT(workdir=job["workdir"]) + cmd=gclient.get_pull_cmd() + elif req["requestType"]=="LIST-TAGS": + job = Request.parseListTagsJob(msg) + if job["scm"]=="git": + gclient=git.GIT(workdir=job["workdir"]) + cmd=gclient.get_list_tags_cmd() + elif req["requestType"]=="SWITCH-TAG": + job = Request.parseSwitchTagJob(msg) + if job["scm"]=="git": + gclient=git.GIT(workdir=job["workdir"]) + cmd=gclient.get_switch_to_tag_cmd(tag=job["tag"]) + + elif req["requestType"]=="DEPLOY": + print msg + job = Request.parseDeployJob(msg) + try: + config=yaml.safe_load(open(job["configFile"])) + autodeployer.deploy(config,job["workdir"]) + res="Done" + except Exception as e: + res="ERR:"+traceback.format_exc() + if cmd!="": + print cmd + res=Common.run(cmd) + Response.sendData(clientsock,res) + print "Ended,",res + clientsock.close() break diff --git a/server/client.pub b/server/client.pub new file mode 100755 index 0000000..efade45 --- /dev/null +++ b/server/client.pub @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICWwIBAAKBgQDN7vNOsnnfZlF1EJvtNX4pmu4whFQB771iHF1tMcb/t+QO9iHd +OO8kirvHWAVY4uf7GsgXujYNNQaG/8O64BRTHSs0LZIWtr4OiBjKTF8aLn7kXbMC +Z/I7vDm0WKNATN8VpLJxDv/78UMbZN1yM0qIFAMEg9M7HZyvoMh+ieCNZwIDAQAB +AoGAY7ARbf4tyvwv4Hh60th7S06pkSjttcZFKjJK86oOCAoPx0JU4E9ITKsv/W7Z +n86vt7meNQY6ViheEYnMSTFiBH+k2WuxqCBoKS0K7JwRIEl5jBroRnd5F2MypxFv +hAEf0GGkyp8oar8zoSl7MRelTzuReSlFe+vsjSVfMmagsyECQQDlA8WuTiv4iHXN +t3LDbtKwOymnR3LYy0d1mNPtDPyYu+JyScggSXbb6GB6KvL71k0tvpGx/leyRDxU +wFvsy+BXAkEA5jLuD6ASAgenMdqq18lLHIvO4dzJbS8Mg405w2rGdEUkxfanbpZr +t2qG6LF1nYtNIx7lXbdxFuuR8/wAMPFRcQJAIV8xWTsO8UKBWB7ZXF0z2nZklXm1 +5J2KpjpE95Ai5ubKErlprjrGVTlBhcvoaIZL7NSOSo+zm8iRug/l1VXINQJAEXbT +sMPIGfdSq+mXBH/0/tlsfJ4veeUT4fcY5sZ2/+MvAwXPdghba7LdQVIVRjqHQ57Y +b9+26LI+hHAd45irQQJAcmI+f45pemwpowxX1IRDaubmmBZURLmbGlXar1E4Jby0 +h16tDIwtDwWXZxKwL88j3vtifXVzIC6ppazFHagVYQ== +-----END RSA PRIVATE KEY----- \ No newline at end of file diff --git a/server/deployer/Common.py b/server/deployer/Common.py new file mode 100755 index 0000000..986cda3 --- /dev/null +++ b/server/deployer/Common.py @@ -0,0 +1,28 @@ +import subprocess +EOM = "\n\n###" + + + +def run(executer,raiseError=True,id=None,wait=True): + PIPE = subprocess.PIPE + p = subprocess.Popen(executer, stdout=PIPE, stderr=PIPE, shell=True) + if wait: + (stdout, stderr) = p.communicate() + st = stderr + if id: + f = open("/tmp/" + id + ".err", 'w') + f.write(st) + f.flush() + f.close() + f = open("/tmp/" + id + ".out", 'w') + f.write(stdout) + f.flush() + f.close() + + if len(stderr) > 0: + if raiseError: + raise StandardError(stderr[5:]) + return "ERR:"+stderr + return stdout + else: + return p diff --git a/server/deployer/__init__.py b/server/deployer/__init__.py new file mode 100644 index 0000000..91ba68b --- /dev/null +++ b/server/deployer/__init__.py @@ -0,0 +1 @@ +__author__ = 'mohamed' diff --git a/deployer/autodeployer.py b/server/deployer/autodeployer.py similarity index 76% rename from deployer/autodeployer.py rename to server/deployer/autodeployer.py index eb7dca1..bed3e67 100644 --- a/deployer/autodeployer.py +++ b/server/deployer/autodeployer.py @@ -1,11 +1,12 @@ __author__ = 'mohamed' import sys -import yaml -import shutil import os + +import yaml import Common + debug=False slient=False @@ -17,6 +18,7 @@ def printNotication(message): def runEvents(config,event,raiseErrorOnStdErr=True): if event in config["events"].keys(): for script in config["events"][event]: + wait=True cmd=script["location"] if "interpreter" in script.keys(): cmd="%s %s"%(script["interpreter"],cmd) @@ -24,30 +26,29 @@ def runEvents(config,event,raiseErrorOnStdErr=True): if not script["run-as"]=="root": cmd="su %s -c %s"%(script["run-as"],cmd) if not slient: print "Running:", cmd - Common.run(cmd,raiseErrorOnStdErr) + if "wait" in script.keys(): + wait=script["wait"] + Common.run(cmd,raiseErrorOnStdErr,wait=wait) -def handleFiles(files): +def handleFiles(files,workdir): for file in files: - if file["destination"].endswith("/"): + if file["destination"].endswith("/") and not file["source"].endswith("/"): if not os.path.exists(file["destination"]): os.makedirs(file["destination"]) if file["source"].endswith("/"): - copyMethod=shutil.copytree - else: - copyMethod=shutil.copy - copyMethod(workdir+file["source"],file["destination"]) + Common.run("sudo rsync -rz --delete --exclude='.git' %s %s"%(workdir+file["source"],file["destination"])) def handlePermissions(permissions,raiseErrorOnStdErr): for permission in permissions: if "owner" in permission.keys(): - cmd="chown %s:%s %s"%(permission["owner"],permission["group"],permission["object"]) + cmd="sudo chown %s:%s %s"%(permission["owner"],permission["group"],permission["object"]) if "dir" in permission["type"].lower(): cmd += " -R" if debug: print " ", cmd Common.run(cmd,raiseErrorOnStdErr) if "mode" in permission.keys(): - cmd="chmod %s %s"%(permission["mode"],permission["object"]) + cmd="sudo chmod %s %s"%(permission["mode"],permission["object"]) if "dir" in permission["type"].lower(): cmd += " -R" if debug: print " ",cmd @@ -59,7 +60,7 @@ def deploy(config,workdir=".",raiseErrorOnStdErr=True): printNotication("Starting Deployment") if not slient: print " Copying Files" - handleFiles(config["files"]) + handleFiles(config["files"],workdir) if not slient: print " Copying done" if not slient: print " Setting Permissions" @@ -70,7 +71,7 @@ def deploy(config,workdir=".",raiseErrorOnStdErr=True): printNotication("Starting After Install Scripts") runEvents(config,"afterInstall",raiseErrorOnStdErr) - + return "Done" if __name__=="__main__": config=None workdir=None @@ -79,6 +80,7 @@ def deploy(config,workdir=".",raiseErrorOnStdErr=True): if "--config" in arg: yamlFile=arg.split("=")[1] config=yaml.safe_load(open(yamlFile)) + print config elif "--workdir" in arg: workdir=arg.split("=")[1] elif "--no-stderr" in arg: @@ -87,6 +89,8 @@ def deploy(config,workdir=".",raiseErrorOnStdErr=True): slient=True elif "--debug" in arg: debug=True - + if not config or not workdir: + print "--config and --workdir should be set" + exit() deploy(config,workdir,stdErr) diff --git a/server/scm/BaseSCM.py b/server/scm/BaseSCM.py new file mode 100644 index 0000000..d40e8a5 --- /dev/null +++ b/server/scm/BaseSCM.py @@ -0,0 +1,12 @@ +__author__ = 'mohamed' + + +class BaseSCM(): + def get_clone_cmd(self): + pass + def get_pull_cmd(self): + pass + def get_list_tags_cmd(self): + pass + def get_switch_to_tag_cmd(self): + pass diff --git a/server/scm/Git.py b/server/scm/Git.py new file mode 100644 index 0000000..da7dc48 --- /dev/null +++ b/server/scm/Git.py @@ -0,0 +1,26 @@ +__author__ = 'mohamed' +from BaseSCM import BaseSCM + + +class GIT(BaseSCM): + + def __init__(self,workdir,repo=""): + self.workdir=workdir + self.repo=repo + def setKey(self,key): + from os.path import expanduser + home = expanduser("~") + keyfile=home+"/.ssh/id_rsa" + Common.run("chmod 700 %s"%keyfile) + f=open(keyfile,"w") + f.write(key) + f.close() + Common.run("chmod 400 %s"%keyfile) + def get_clone_cmd(self): + return "git clone %s %s"%(self.repo,self.workdir) + def get_pull_cmd(self): + return "cd %s; git pull"%self.workdir + def get_list_tags_cmd(self): + return "cd %s; git tag -l"%self.workdir + def get_switch_to_tag_cmd(self,tag): + return "cd %s; git checkout tags/%s"%(self.workdir,tag) \ No newline at end of file diff --git a/server/scm/__init__.py b/server/scm/__init__.py new file mode 100644 index 0000000..91ba68b --- /dev/null +++ b/server/scm/__init__.py @@ -0,0 +1 @@ +__author__ = 'mohamed' diff --git a/webapp/__init__.py b/webapp/__init__.py new file mode 100644 index 0000000..91ba68b --- /dev/null +++ b/webapp/__init__.py @@ -0,0 +1 @@ +__author__ = 'mohamed' diff --git a/webapp/autoDeploy/autoDeploy/settings.py b/webapp/autoDeploy/autoDeploy/settings.py index 6645ce5..0b2bb2f 100644 --- a/webapp/autoDeploy/autoDeploy/settings.py +++ b/webapp/autoDeploy/autoDeploy/settings.py @@ -37,7 +37,9 @@ 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', - 'autodeploy' + 'autodeploy', + 'django_tables2', + 'django_tables2_reports' ) MIDDLEWARE_CLASSES = ( diff --git a/webapp/autoDeploy/autoDeploy/urls.py b/webapp/autoDeploy/autoDeploy/urls.py index 684188a..79e0ce9 100644 --- a/webapp/autoDeploy/autoDeploy/urls.py +++ b/webapp/autoDeploy/autoDeploy/urls.py @@ -21,4 +21,9 @@ url(r'^$','autodeploy.views.projects'), url(r'add_project','autodeploy.views.add_project'), url(r'add_server','autodeploy.views.add_server'), + url(r'add_sshkey','autodeploy.views.add_ssh_key'), + url(r'clone/','autodeploy.views.clone'), + url(r'deploy/','autodeploy.views.deploy'), + url(r'deploy2/','autodeploy.views.deploy2'), + url(r'deploy3/','autodeploy.views.deploy3'), ] diff --git a/webapp/autoDeploy/autodeploy/client b/webapp/autoDeploy/autodeploy/client new file mode 120000 index 0000000..97ac563 --- /dev/null +++ b/webapp/autoDeploy/autodeploy/client @@ -0,0 +1 @@ +/home/mohamed/autoDeploy/autoDeploy/client/ \ No newline at end of file diff --git a/webapp/autoDeploy/autodeploy/forms.py b/webapp/autoDeploy/autodeploy/forms.py index c2c2e1f..a68e963 100644 --- a/webapp/autoDeploy/autodeploy/forms.py +++ b/webapp/autoDeploy/autodeploy/forms.py @@ -7,8 +7,17 @@ class addProjectsForm(forms.ModelForm): repo_type=forms.ChoiceField(choices=repo_type,label="Repo Type") class Meta: model= models.Project - fields=("name","repo","working_dir","repo_type") + fields=("name","repo","working_dir","repo_type","sshKey") class addServerForm(forms.ModelForm): class Meta: model=models.Server - fields=('name','dns','port') \ No newline at end of file + fields=('name','dns','port') +class addSSHKeyForm(forms.ModelForm): + class Meta: + model=models.sshKey + fields=('name','key') + +class CloneForm(forms.Form): + server=forms.ModelChoiceField(queryset=models.Server.objects.all(),label="Server") + + diff --git a/webapp/autoDeploy/autodeploy/migrations/0005_auto_20150509_0744.py b/webapp/autoDeploy/autodeploy/migrations/0005_auto_20150509_0744.py new file mode 100644 index 0000000..0e9b880 --- /dev/null +++ b/webapp/autoDeploy/autodeploy/migrations/0005_auto_20150509_0744.py @@ -0,0 +1,27 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('autodeploy', '0004_auto_20150509_0522'), + ] + + operations = [ + migrations.CreateModel( + name='sshKey', + fields=[ + ('name', models.CharField(max_length=50, serialize=False, primary_key=True)), + ('key', models.TextField()), + ], + ), + migrations.AddField( + model_name='project', + name='sshKey', + field=models.ForeignKey(default='NULL', to='autodeploy.sshKey'), + preserve_default=False, + ), + ] diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index ffe3aab..9aeb9b2 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -1,4 +1,19 @@ from django.db import models +from datetime import datetime +class sshKey(models.Model): + name=models.CharField(max_length=50,primary_key=True) + key=models.TextField() + + def __unicode__(self): + return self.name + + +class working_directory(models.Model): + name=models.CharField(max_length=50,primary_key=True) + path=models.CharField(max_length=1000) + +def __unicode__(self): + return self.name class Project(models.Model): @@ -7,13 +22,22 @@ class Project(models.Model): repo = models.CharField(max_length=255, blank=True) lastCommit = models.CharField(max_length=32,blank=True) lastTag=models.CharField(max_length=255,blank=True) - lastCommitDate = models.DateTimeField(blank=True) + lastCommitDate = models.DateTimeField(blank=True,default="1970-01-01") working_dir=models.FileField(blank=True) configFile=models.FileField(blank=True) - lastUpdate=models.DateTimeField(blank=True) + lastUpdate=models.DateTimeField(blank=True,default=datetime.now()) + sshKey=models.ForeignKey(sshKey,to_field="name",verbose_name="SSH Key") + + def __unicode__(self): + return self.name + class Server(models.Model): name=models.CharField(max_length=50,primary_key=True) dns=models.CharField(max_length=50) port=models.IntegerField(default=4567) + def __unicode__(self): + return self.name + + diff --git a/webapp/autoDeploy/autodeploy/tables.py b/webapp/autoDeploy/autodeploy/tables.py new file mode 100644 index 0000000..ca0939c --- /dev/null +++ b/webapp/autoDeploy/autodeploy/tables.py @@ -0,0 +1,13 @@ +import django_tables2 as tables +from django_tables2_reports.tables import TableReport +from models import * +__author__ = 'mohamed' + + +class ProjectReport(TableReport): + name=tables.Column(verbose_name="Project Name") + Operations=tables.TemplateColumn("  ") + class Meta: + model=Project + fields=('name','repo') + attrs = {"class": "paleblue"} diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 5e1be7a..94e1eab 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -1,16 +1,32 @@ from django.shortcuts import render,render_to_response from django.template import RequestContext +from django_tables2_reports.utils import create_report_http_response from forms import * from models import * +from tables import * from django.views.decorators.csrf import csrf_protect -def projects(request): - return render_to_response("projects.html",{},context_instance=RequestContext(request)) +from django_tables2_reports.config import RequestConfigReport +from client.Client import Client +from django.shortcuts import redirect +def projects(request): + xlstable=ProjectReport(Project.objects.all()) + table_to_report = RequestConfigReport(request, paginate={"per_page": 15}).configure(xlstable) + if table_to_report: + return create_report_http_response(table_to_report, request) + print xlstable + return render_to_response("projects.html",{"table":xlstable},context_instance=RequestContext(request)) +@csrf_protect def add_project(request): if request.method=="GET": return render_to_response("add_project.html",{"form":addProjectsForm()},context_instance=RequestContext(request)) else: - pass + form=addProjectsForm(request.POST) + if form.is_valid: + form.save() + return render_to_response("add_project.html",{form:form,"done":True},context_instance=RequestContext(request)) + else: + return render_to_response("add_project.html",{form:form,"error":True},context_instance=RequestContext(request)) @csrf_protect def add_server(request): if request.method=="GET": @@ -22,3 +38,52 @@ def add_server(request): return render_to_response("add_server.html",{"form":form,"done":True},context_instance=RequestContext(request)) else: return render_to_response("add_server.html",{"form":form,"error":True},context_instance=RequestContext(request)) + +@csrf_protect +def add_ssh_key(request): + if request.method=="GET": + return render_to_response("add_sshkey.html",{"form":addSSHKeyForm()},context_instance=RequestContext(request)) + else: + form=addSSHKeyForm(request.POST) + if form.is_valid: + form.save() + return render_to_response("add_sshkey.html",{"form":form,"done":True},context_instance=RequestContext(request)) + else: + return render_to_response("add_sshkey.html",{"form":form,"error":True},context_instance=RequestContext(request)) + +@csrf_protect +def clone(request): + if request.method=="GET": + project=Project.objects.get(name=request.GET["project"]) + return render_to_response("clone.html",{"form":CloneForm,"project_workdir":project.working_dir},context_instance=RequestContext(request)) + else: + project=Project.objects.get(name=request.POST["project"]) + form=CloneForm(request.POST) + if form.is_valid: + c=Client("git") + res=c.Clone(project.repo,project.working_dir,project.sshKey.key) + print res + return render_to_response("clone.html",{"form":form,"result":res},context_instance=RequestContext(request)) + +@csrf_protect +def deploy(request): + if request.method=="GET": + request.session["deploy_project"]=request.GET["project"] + return render_to_response("deploy.html",{"form":CloneForm},context_instance=RequestContext(request)) + else: + request.session["deploy_server"]=request.POST["server"] + return redirect("../deploy2/") +def deploy2(request): + if request.method=="GET": + c=Client("git") + project=Project.objects.get(name=request.session["deploy_project"]) + res=c.ListTags(project.working_dir) + return render_to_response("deploy2.html",{"tags":res.split("\n")},context_instance=RequestContext(request)) +def deploy3(request): + if request.method=="GET": + c=Client("git") + project=Project.objects.get(name=request.session["deploy_project"]) + res=c.SwitchTag(project.working_dir,request.GET["tag"]) + res=c.Deploy(project.working_dir,project.configFile) + return render_to_response("deploy2.html",{"result":res},context_instance=RequestContext(request)) + diff --git a/webapp/autoDeploy/static/css/screen.css b/webapp/autoDeploy/static/css/screen.css new file mode 100644 index 0000000..8f78519 --- /dev/null +++ b/webapp/autoDeploy/static/css/screen.css @@ -0,0 +1,141 @@ +table.paleblue { + + border-collapse: collapse; + border-color: #CCC; + border: 1px solid #DDD; + } + +table.paleblue, +table.paleblue + ul.pagination { + font: normal 13px 'Lucida Grande', Verdana, Helvetica, Arial, sans-serif; +} + +table.paleblue a:link, +table.paleblue a:visited, +table.paleblue + ul.pagination > li > a { + color: #5B80B2; + text-decoration: none; + font-weight: bold; +} + +table.paleblue a:hover { + color: #036; +} + +table.paleblue td, +table.paleblue th { + padding: 10px; + line-height: 13px; + border-bottom: 1px solid #EEE; + border-left: 1px solid #DDD; + text-align: left; + +} + +table.paleblue thead th:first-child, +table.paleblue thead td:first-child { + border-left: none !important; +} + +table.paleblue thead th, +table.paleblue thead td { + background: #FCFCFC url(../img/table_img/header-bg.png) left bottom repeat-x; + border-bottom: 1px solid #DDD; + padding: 10px 10px; + font-size: 13px; + vertical-align: middle; + color: #666; +} + +table.paleblue thead th > a:link, +table.paleblue thead th > a:visited { + color: #666; +} + +table.paleblue thead th.orderable > a { + padding-right: 20px; + background: url(../img/table_img/arrow-inactive-up.png) right center no-repeat; +} +table.paleblue thead th.orderable.asc > a { + background-image: url(../img/table_img/arrow-active-up.png); +} +table.paleblue thead th.orderable.desc > a { + background-image: url(../img/table_img/arrow-active-down.png); +} + +table.paleblue tr.odd { + background-color: #EDF3FE; +} + +table.paleblue tr.even { + background-color: white; +} + +table.paleblue + ul.pagination { + background: white url(../img/table_img/pagination-bg.gif) left 180% repeat-x; + overflow: auto; + margin: 0; + padding: 10px; + border: 1px solid #DDD; + list-style: none; +} + +table.paleblue + ul.pagination > li { + float: left; + line-height: 22px; + margin-left: 10px; +} + +table.paleblue + ul.pagination > li:first-child { + margin-left: 0; +} + +table.paleblue + ul.pagination > li.cardinality { + float: right; + color: #8d8d8d; +} + +table.paleblue > tbody > tr > td > span.true, +table.paleblue > tbody > tr > td > span.false { + background-position: top left; + background-repeat: no-repeat; + display: inline-block; + height: 10px; + overflow: hidden; + text-indent: -200px; + width: 10px; +} + +table.paleblue > tbody > tr > td > .missing { + background: transparent url(../img/table_img/missing.png) right center no-repeat; + color: #717171; + padding-right: 20px; +} + +table.paleblue > tbody > tr > td > .missing:hover { + color: #333; +} + +table.paleblue > tbody > tr > td > span.true { + background-image: url(../img/table_img/true.gif); +} + +table.paleblue > tbody > tr > td > span.false { + background-image: url(../img/table_img/false.gif); +} + +div.table-container { + display: inline-block; + +} + +.status{ + text-align: left !important; + white-space: nowrap !important; +} + +th.get_sample_tag +{ + white-space: nowrap !important; + +} \ No newline at end of file diff --git a/webapp/autoDeploy/templates/add_project.html b/webapp/autoDeploy/templates/add_project.html index 5ac6b16..68fd453 100644 --- a/webapp/autoDeploy/templates/add_project.html +++ b/webapp/autoDeploy/templates/add_project.html @@ -1,6 +1,15 @@ {% extends "base.html" %} {% block content %} -
+ {% if done %} +
+
Project Saved
+
+ {% endif %} + {% if error %} +
{{ form.errors }}
+ {% endif %} + + {% csrf_token %}
{{ form.as_table }} diff --git a/webapp/autoDeploy/templates/add_sshkey.html b/webapp/autoDeploy/templates/add_sshkey.html new file mode 100644 index 0000000..8b26556 --- /dev/null +++ b/webapp/autoDeploy/templates/add_sshkey.html @@ -0,0 +1,22 @@ +{% extends "base.html" %} +{% block content %} + {% if done %} +
+
Key Saved
+
+ {% endif %} + {% if error %} +
{{ form.errors }}
+ {% endif %} + + {% csrf_token %} +
+
+ {{ form.as_table }} +
+ +
+
+ + +{% endblock %} \ No newline at end of file diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 61afc0f..1b05f07 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -9,6 +9,7 @@ + {% block head %} {% endblock %} @@ -40,10 +41,10 @@ @@ -75,23 +81,7 @@ - - - - - - - - + diff --git a/webapp/autoDeploy/templates/clone.html b/webapp/autoDeploy/templates/clone.html new file mode 100644 index 0000000..be94437 --- /dev/null +++ b/webapp/autoDeploy/templates/clone.html @@ -0,0 +1,28 @@ +{% extends "base.html" %} +{% block content %} +
+

Clone Project

+ {% if result %} + {% if "ERR:" in result %} +
+ {% else %} +
+ {% endif %} + {{ result }}
+ {% endif %} +
+ {% csrf_token %} + + + + {{ form.as_table }} + + + +
Project{{ request.GET.project }}
The project will be clone to {{ project_workdir }} on the selected server.
+ + + +
+
+{% endblock %} \ No newline at end of file diff --git a/webapp/autoDeploy/templates/deploy.html b/webapp/autoDeploy/templates/deploy.html new file mode 100644 index 0000000..3c934a9 --- /dev/null +++ b/webapp/autoDeploy/templates/deploy.html @@ -0,0 +1,19 @@ +{% extends "base.html"%} +{% block content %} +
+

Clone Project

+
+ {% csrf_token %} + + + + {{ form.as_table }} + + +
Project{{ request.GET.project }}
+ + + +
+
+{% endblock %} \ No newline at end of file diff --git a/webapp/autoDeploy/templates/deploy2.html b/webapp/autoDeploy/templates/deploy2.html new file mode 100644 index 0000000..1448a9c --- /dev/null +++ b/webapp/autoDeploy/templates/deploy2.html @@ -0,0 +1,27 @@ +{% extends "base.html"%} +{% block content %} +
+

Deploy Project

+ + {% if result %} + {% if "ERR:" in result %} +
+ {% else %} +
+ {% endif %} + {{ result }}
+ + {% else %} + Select Tag: +
+
    + {% for tag in tags %} + {% if tag != "" %} +
  • {{ tag }}
  • + {% endif %} + {% endfor %} +
+ + + {% endif %} +{% endblock %} \ No newline at end of file diff --git a/webapp/autoDeploy/templates/django-table2.html b/webapp/autoDeploy/templates/django-table2.html new file mode 100644 index 0000000..bc997ac --- /dev/null +++ b/webapp/autoDeploy/templates/django-table2.html @@ -0,0 +1,77 @@ +{% spaceless %} +{% load django_tables2 %} +{% load i18n %} +{% if table.page %} +
+{% endif %} + {% with table.page.paginator.count as total %} +{% with table.page.object_list|length as count %} +{% block pagination %} +
    + {% if table.page.has_previous %} + {% nospaceless %}{% block pagination.previous %}{% endblock pagination.previous %}{% endnospaceless %} + {% endif %} + + {% if table.page.has_previous or table.page.has_next %} + {% nospaceless %}{% block pagination.current %}
  • {% blocktrans with table.page.number as current and table.paginator.num_pages as total %}Page of {{ total }}{% endblocktrans %}
  • {% endblock pagination.current %}{% endnospaceless %} + {% endif %} + + {% if table.page.has_next %} + {% nospaceless %}{% block pagination.next %}{% endblock pagination.next %}{% endnospaceless %} + {% endif %} + + {% nospaceless %}{% block pagination.cardinality %}
  • {% if total != count %}{% blocktrans %}{{ count }} of {{ total }}{% endblocktrans %}{% else %}{{ total }}{% endif %} +
  • {% endblock pagination.cardinality %}{% endnospaceless %} +
+{% endblock pagination %} +{% endwith %} +{% endwith %} + +{% block table %} + + {% nospaceless %} + {% block table.thead %} + + + {% for column in table.columns %} + {% if column.orderable %} + {{ column.header }} + {% else %} + {{ column.header }} + {% endif %} + {% endfor %} + + + {% endblock table.thead %} + {% block table.tbody %} + + {% for row in table.page.object_list|default:table.rows %} {# support pagination #} + {% block table.tbody.row %} + {# avoid cycle for Django 1.2-1.6 compatibility #} + {% for column, cell in row.items %} + {% if column.localize == None %}{{ cell }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %} + {% endfor %} + + {% endblock table.tbody.row %} + {% empty %} + {% if table.empty_text %} + {% block table.tbody.empty_text %} + {{ table.empty_text }} + {% endblock table.tbody.empty_text %} + {% endif %} + {% endfor %} + + {% endblock table.tbody %} + {% block table.tfoot %} + + {% endblock table.tfoot %} + {% endnospaceless %} + +{% endblock table %} + + +{% if table.page %} +
+{% endif %} + +{% endspaceless %} diff --git a/webapp/autoDeploy/templates/projects.html b/webapp/autoDeploy/templates/projects.html index 9d5a660..6a3c2f1 100644 --- a/webapp/autoDeploy/templates/projects.html +++ b/webapp/autoDeploy/templates/projects.html @@ -1,4 +1,7 @@ {% extends "base.html" %} +{% load render_table from django_tables2 %} {% block content %} -

Projects

+

Projects

+ {% render_table table "table.html" %} +
{% endblock %} \ No newline at end of file diff --git a/webapp/autoDeploy/templates/table.html b/webapp/autoDeploy/templates/table.html new file mode 100644 index 0000000..862b369 --- /dev/null +++ b/webapp/autoDeploy/templates/table.html @@ -0,0 +1,19 @@ + +{% extends "django-table2.html" %} + +{% load i18n django_tables2 %} + +{% block pagination %} + + {% block table.report %} + {% if table.is_configured %} + {% for label, format in table.formats %} + + + + {% endfor %} +
+ {% endif %} + {% endblock table.report %} + {{ block.super }} +{% endblock %} From cc4f74ff9910cbb39d451544e686a53e0622df17 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 9 May 2015 16:07:50 +0300 Subject: [PATCH 002/108] Added sudoers.d step --- Installation.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Installation.md b/Installation.md index 8cc3db2..3a414b1 100644 --- a/Installation.md +++ b/Installation.md @@ -6,8 +6,9 @@ This document shows how to install autoDeploy on Ubuntu System ```sh # adduser --system --home /opt/autodeploy/home --shell /bin/bash autodeploy ``` -2. Add autodeploy to admins. +2. Add autodeploy to sudoers. ```sh -# adduser autodeploy adm +# adduser autodeploy sudo ``` -3. +3. Copy the file in UnixConfig to /etc/sudoers.d/ + From 6c44ef2ec9276b21a7fe9e31285341ec1e450b31 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sun, 10 May 2015 17:37:52 +0300 Subject: [PATCH 003/108] Close #5, Close #6 --- webapp/autoDeploy/autodeploy/forms.py | 2 +- .../migrations/0006_auto_20150510_1427.py | 47 +++++++++++++++++++ .../migrations/0007_auto_20150510_1427.py | 20 ++++++++ webapp/autoDeploy/autodeploy/models.py | 2 + webapp/autoDeploy/autodeploy/tables.py | 4 +- 5 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 webapp/autoDeploy/autodeploy/migrations/0006_auto_20150510_1427.py create mode 100644 webapp/autoDeploy/autodeploy/migrations/0007_auto_20150510_1427.py diff --git a/webapp/autoDeploy/autodeploy/forms.py b/webapp/autoDeploy/autodeploy/forms.py index a68e963..13c8146 100644 --- a/webapp/autoDeploy/autodeploy/forms.py +++ b/webapp/autoDeploy/autodeploy/forms.py @@ -7,7 +7,7 @@ class addProjectsForm(forms.ModelForm): repo_type=forms.ChoiceField(choices=repo_type,label="Repo Type") class Meta: model= models.Project - fields=("name","repo","working_dir","repo_type","sshKey") + fields=("name","repo","repo_link","working_dir","repo_type","sshKey","deployment_link") class addServerForm(forms.ModelForm): class Meta: model=models.Server diff --git a/webapp/autoDeploy/autodeploy/migrations/0006_auto_20150510_1427.py b/webapp/autoDeploy/autodeploy/migrations/0006_auto_20150510_1427.py new file mode 100644 index 0000000..8b17c27 --- /dev/null +++ b/webapp/autoDeploy/autodeploy/migrations/0006_auto_20150510_1427.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime + + +class Migration(migrations.Migration): + + dependencies = [ + ('autodeploy', '0005_auto_20150509_0744'), + ] + + operations = [ + migrations.CreateModel( + name='working_directory', + fields=[ + ('name', models.CharField(max_length=50, serialize=False, primary_key=True)), + ('path', models.CharField(max_length=1000)), + ], + ), + migrations.AddField( + model_name='project', + name='deployment_link', + field=models.URLField(blank=True), + ), + migrations.AddField( + model_name='project', + name='repo_link', + field=models.URLField(blank=True), + ), + migrations.AlterField( + model_name='project', + name='lastCommitDate', + field=models.DateTimeField(default=b'1970-01-01', blank=True), + ), + migrations.AlterField( + model_name='project', + name='lastUpdate', + field=models.DateTimeField(default=datetime.datetime(2015, 5, 10, 14, 27, 1, 48900), blank=True), + ), + migrations.AlterField( + model_name='project', + name='sshKey', + field=models.ForeignKey(verbose_name=b'SSH Key', to='autodeploy.sshKey'), + ), + ] diff --git a/webapp/autoDeploy/autodeploy/migrations/0007_auto_20150510_1427.py b/webapp/autoDeploy/autodeploy/migrations/0007_auto_20150510_1427.py new file mode 100644 index 0000000..8f0d42e --- /dev/null +++ b/webapp/autoDeploy/autodeploy/migrations/0007_auto_20150510_1427.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime + + +class Migration(migrations.Migration): + + dependencies = [ + ('autodeploy', '0006_auto_20150510_1427'), + ] + + operations = [ + migrations.AlterField( + model_name='project', + name='lastUpdate', + field=models.DateTimeField(default=datetime.datetime(2015, 5, 10, 14, 27, 14, 363617), blank=True), + ), + ] diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index 9aeb9b2..0e23bc0 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -27,6 +27,8 @@ class Project(models.Model): configFile=models.FileField(blank=True) lastUpdate=models.DateTimeField(blank=True,default=datetime.now()) sshKey=models.ForeignKey(sshKey,to_field="name",verbose_name="SSH Key") + repo_link=models.URLField(blank=True) + deployment_link=models.URLField(blank=True) def __unicode__(self): return self.name diff --git a/webapp/autoDeploy/autodeploy/tables.py b/webapp/autoDeploy/autodeploy/tables.py index ca0939c..9a6efb6 100644 --- a/webapp/autoDeploy/autodeploy/tables.py +++ b/webapp/autoDeploy/autodeploy/tables.py @@ -7,7 +7,9 @@ class ProjectReport(TableReport): name=tables.Column(verbose_name="Project Name") Operations=tables.TemplateColumn("  ") + repo_link=tables.TemplateColumn("{{ record.repo_link }} ") + deployment_link=tables.TemplateColumn("{{ record.deployment_link }} ") class Meta: model=Project - fields=('name','repo') + fields=('name','repo_link','deployment_link') attrs = {"class": "paleblue"} From fb9481040039887802c8f338ffc0bb814fe14362 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Mon, 11 May 2015 19:50:32 +0300 Subject: [PATCH 004/108] Closes #16, Closes #15 --- webapp/autoDeploy/autodeploy/forms.py | 2 +- .../migrations/0008_auto_20150511_1637.py | 30 +++++++++++++++++++ webapp/autoDeploy/autodeploy/models.py | 3 +- webapp/autoDeploy/autodeploy/views.py | 6 ++-- webapp/autoDeploy/templates/add_server.html | 5 ++++ 5 files changed, 41 insertions(+), 5 deletions(-) create mode 100644 webapp/autoDeploy/autodeploy/migrations/0008_auto_20150511_1637.py diff --git a/webapp/autoDeploy/autodeploy/forms.py b/webapp/autoDeploy/autodeploy/forms.py index 13c8146..7dd65ac 100644 --- a/webapp/autoDeploy/autodeploy/forms.py +++ b/webapp/autoDeploy/autodeploy/forms.py @@ -11,7 +11,7 @@ class Meta: class addServerForm(forms.ModelForm): class Meta: model=models.Server - fields=('name','dns','port') + fields=('name','ip','port','DNS') class addSSHKeyForm(forms.ModelForm): class Meta: model=models.sshKey diff --git a/webapp/autoDeploy/autodeploy/migrations/0008_auto_20150511_1637.py b/webapp/autoDeploy/autodeploy/migrations/0008_auto_20150511_1637.py new file mode 100644 index 0000000..3bb648e --- /dev/null +++ b/webapp/autoDeploy/autodeploy/migrations/0008_auto_20150511_1637.py @@ -0,0 +1,30 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime + + +class Migration(migrations.Migration): + + dependencies = [ + ('autodeploy', '0007_auto_20150510_1427'), + ] + + operations = [ + migrations.RenameField( + model_name='server', + old_name='dns', + new_name='ip', + ), + migrations.AddField( + model_name='server', + name='DNS', + field=models.CharField(max_length=50, blank=True), + ), + migrations.AlterField( + model_name='project', + name='lastUpdate', + field=models.DateTimeField(default=datetime.datetime(2015, 5, 11, 16, 37, 3, 358918), blank=True), + ), + ] diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index 0e23bc0..bc2870a 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -36,8 +36,9 @@ def __unicode__(self): class Server(models.Model): name=models.CharField(max_length=50,primary_key=True) - dns=models.CharField(max_length=50) + ip=models.CharField(max_length=50) port=models.IntegerField(default=4567) + DNS=models.CharField(max_length=50,blank=True) def __unicode__(self): return self.name diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 94e1eab..994a770 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -22,7 +22,7 @@ def add_project(request): return render_to_response("add_project.html",{"form":addProjectsForm()},context_instance=RequestContext(request)) else: form=addProjectsForm(request.POST) - if form.is_valid: + if form.is_valid(): form.save() return render_to_response("add_project.html",{form:form,"done":True},context_instance=RequestContext(request)) else: @@ -33,7 +33,7 @@ def add_server(request): return render_to_response("add_server.html",{"form":addServerForm},context_instance=RequestContext(request)) else: form=addServerForm(request.POST) - if form.is_valid: + if form.is_valid(): form.save() return render_to_response("add_server.html",{"form":form,"done":True},context_instance=RequestContext(request)) else: @@ -45,7 +45,7 @@ def add_ssh_key(request): return render_to_response("add_sshkey.html",{"form":addSSHKeyForm()},context_instance=RequestContext(request)) else: form=addSSHKeyForm(request.POST) - if form.is_valid: + if form.is_valid(): form.save() return render_to_response("add_sshkey.html",{"form":form,"done":True},context_instance=RequestContext(request)) else: diff --git a/webapp/autoDeploy/templates/add_server.html b/webapp/autoDeploy/templates/add_server.html index 1adb79d..32d7684 100644 --- a/webapp/autoDeploy/templates/add_server.html +++ b/webapp/autoDeploy/templates/add_server.html @@ -1,13 +1,18 @@ {% extends "base.html" %} {% block content %} +
{% if done %}
Server Saved
{% endif %} + {% if error %} + +
{{ form.errors }}
{% endif %} +

Add Servers

{% csrf_token %}
From 379da653f08b676f2158a1493af6cfb49af8818c Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Mon, 11 May 2015 20:47:10 +0300 Subject: [PATCH 005/108] Update YAML.md --- YAML.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/YAML.md b/YAML.md index 149b078..2e091f0 100644 --- a/YAML.md +++ b/YAML.md @@ -89,12 +89,12 @@ It should be in the following format: ```yaml beforeInstall: - - location: /home/mohamed/autoDeploy/autoDeploy/exampleConfig/EventsHandler/delDir.sh + - location: EventsHandler/delDir.sh run-as: www-data interpreter: bash ``` -+ **location**: the full path of the script to run. ++ **location**: the relative path of the script to run. + **run-as**: the username of the user who will run this command (optional). + **interpreter**: the name of the interpreter that should be used to run the script (optional but highly recommended) From 36ca04de1bd3dba3c2776027370e64b9f07faea5 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Mon, 11 May 2015 20:53:01 +0300 Subject: [PATCH 006/108] Fixed: location in events is relative to workdir --- server/deployer/autodeployer.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/server/deployer/autodeployer.py b/server/deployer/autodeployer.py index bed3e67..22eeb3f 100644 --- a/server/deployer/autodeployer.py +++ b/server/deployer/autodeployer.py @@ -15,11 +15,11 @@ def printNotication(message): print message print "="*len(message) -def runEvents(config,event,raiseErrorOnStdErr=True): +def runEvents(config,workdir,event,raiseErrorOnStdErr=True): if event in config["events"].keys(): for script in config["events"][event]: wait=True - cmd=script["location"] + cmd=workdir+script["location"] if "interpreter" in script.keys(): cmd="%s %s"%(script["interpreter"],cmd) if "run-as" in script.keys(): @@ -55,8 +55,9 @@ def handlePermissions(permissions,raiseErrorOnStdErr): Common.run(cmd,raiseErrorOnStdErr) def deploy(config,workdir=".",raiseErrorOnStdErr=True): + if workdir[-1] != '/': workdir += "/" printNotication("Running Before Install scripts:") - runEvents(config,"beforeInstall") + runEvents(config,workdir,"beforeInstall",raiseErrorOnStdErr) printNotication("Starting Deployment") if not slient: print " Copying Files" @@ -70,7 +71,7 @@ def deploy(config,workdir=".",raiseErrorOnStdErr=True): printNotication("Deployment Done.......") printNotication("Starting After Install Scripts") - runEvents(config,"afterInstall",raiseErrorOnStdErr) + runEvents(config,workdir,"afterInstall",raiseErrorOnStdErr) return "Done" if __name__=="__main__": config=None From d43334de14bfdaa91ef75b85e57f98de2cbe54c7 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Tue, 12 May 2015 08:39:10 +0300 Subject: [PATCH 007/108] Closes #13, Closes 17, Adds a media directory for the uploaded directory setting in settings.py --- webapp/autoDeploy/autoDeploy/settings.py | 3 ++ webapp/autoDeploy/autodeploy/forms.py | 43 +++++++++++++++++++- webapp/autoDeploy/autodeploy/models.py | 2 +- webapp/autoDeploy/autodeploy/views.py | 8 ++-- webapp/autoDeploy/static/css/autodeploy.css | 26 ++++++++++++ webapp/autoDeploy/templates/add_project.html | 4 +- webapp/autoDeploy/templates/add_sshkey.html | 2 + webapp/autoDeploy/templates/base.html | 1 + 8 files changed, 81 insertions(+), 8 deletions(-) create mode 100644 webapp/autoDeploy/static/css/autodeploy.css diff --git a/webapp/autoDeploy/autoDeploy/settings.py b/webapp/autoDeploy/autoDeploy/settings.py index 0b2bb2f..7340984 100644 --- a/webapp/autoDeploy/autoDeploy/settings.py +++ b/webapp/autoDeploy/autoDeploy/settings.py @@ -110,3 +110,6 @@ STATIC_URL = BASE_URL+ 'static/' PROJECTS_DIR='/opt/autodeploy/projects/' + +MEDIA_ROOT = os.path.join(BASE_DIR, 'media') +MEDIA_URL = '/media/' diff --git a/webapp/autoDeploy/autodeploy/forms.py b/webapp/autoDeploy/autodeploy/forms.py index 7dd65ac..05ed658 100644 --- a/webapp/autoDeploy/autodeploy/forms.py +++ b/webapp/autoDeploy/autodeploy/forms.py @@ -1,20 +1,59 @@ __author__ = 'mohamed' from django import forms import models +import os +import autoDeploy.settings as settings repo_type=[('git','git')] +def saveFile(file,project_name): + if file=='': + print "No File to save." + return '' + if not os.path.exists(settings.MEDIA_ROOT+"/"+project_name): + os.makedirs(settings.MEDIA_ROOT+"/"+project_name) + fpath=settings.MEDIA_ROOT+"/"+project_name+"/"+file.name + with open(fpath, 'wb+') as destination: + for chunk in file.chunks(): + destination.write(chunk) + return fpath + class addProjectsForm(forms.ModelForm): - working_dir=forms.CharField(label="Working Directory") + working_dir=forms.CharField(label="Working Directory",widget=forms.TextInput(attrs={'class':'form-control','size':30})) repo_type=forms.ChoiceField(choices=repo_type,label="Repo Type") + cfile=forms.FileField(label="Config File") + name = forms.CharField(label='Project Name',widget=forms.TextInput(attrs={'class':'form-control','size':30})) + repo_link= forms.CharField(label='Repo Link',widget=forms.TextInput(attrs={'class':'form-control','size':30})) + repo= forms.CharField(label='Repo',widget=forms.TextInput(attrs={'class':'form-control','size':30})) + deployment_link= forms.CharField(label='Deployment Link',widget=forms.TextInput(attrs={'class':'form-control','size':30})) + + def save(self,files,name): + P= models.Project() + P.name=self.cleaned_data["name"] + P.deployment_link=self.cleaned_data["deployment_link"] + P.repo=self.cleaned_data["repo"] + P.repo_link=self.cleaned_data["repo_link"] + P.repo_type=self.cleaned_data["repo_type"] + P.working_dir=self.cleaned_data["working_dir"] + P.sshKey=self.cleaned_data["sshKey"] + print "Files is ",files + P.configFile = saveFile(files.get('cfile',''),name) + P.save() class Meta: model= models.Project - fields=("name","repo","repo_link","working_dir","repo_type","sshKey","deployment_link") + fields=("name","repo","repo_link","working_dir","repo_type","sshKey","deployment_link","cfile") + class addServerForm(forms.ModelForm): + ip=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','size':30}),label="Hostname/IP") class Meta: model=models.Server + widgets={"name":forms.TextInput(attrs={'class':'form-control','size':30}), + "DNS":forms.TextInput(attrs={'class':'form-control','size':5}) + } fields=('name','ip','port','DNS') class addSSHKeyForm(forms.ModelForm): class Meta: model=models.sshKey + widgets={'name':forms.TextInput(attrs={'class':'form-control','size':30}), + 'key':forms.Textarea(attrs={'class':'form-control'})} fields=('name','key') class CloneForm(forms.Form): diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index bc2870a..b6240d9 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -28,7 +28,7 @@ class Project(models.Model): lastUpdate=models.DateTimeField(blank=True,default=datetime.now()) sshKey=models.ForeignKey(sshKey,to_field="name",verbose_name="SSH Key") repo_link=models.URLField(blank=True) - deployment_link=models.URLField(blank=True) + deployment_link=models.CharField(max_length=200,blank=True) def __unicode__(self): return self.name diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 994a770..9fcd751 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -21,12 +21,12 @@ def add_project(request): if request.method=="GET": return render_to_response("add_project.html",{"form":addProjectsForm()},context_instance=RequestContext(request)) else: - form=addProjectsForm(request.POST) + form=addProjectsForm(request.POST,request.FILES) if form.is_valid(): - form.save() - return render_to_response("add_project.html",{form:form,"done":True},context_instance=RequestContext(request)) + form.save(request.FILES,form.cleaned_data["name"]) + return render_to_response("add_project.html",{"form":form,"done":True},context_instance=RequestContext(request)) else: - return render_to_response("add_project.html",{form:form,"error":True},context_instance=RequestContext(request)) + return render_to_response("add_project.html",{"form":form,"error":True},context_instance=RequestContext(request)) @csrf_protect def add_server(request): if request.method=="GET": diff --git a/webapp/autoDeploy/static/css/autodeploy.css b/webapp/autoDeploy/static/css/autodeploy.css new file mode 100644 index 0000000..efe3b53 --- /dev/null +++ b/webapp/autoDeploy/static/css/autodeploy.css @@ -0,0 +1,26 @@ +.errorlist +{display: none} +.alert-danger .errorlist +{display: block} +.form-control { + background-color: #fff; + background-image: none; + border: 1px solid #ccc; + border-radius: 4px; + box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset; + color: #555; + display: block; + font-size: 14px; + height: 34px; + line-height: 1.42857; + margin: 5px; + padding: 6px 12px; + transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s; + width: 100%; +} +input, button, select, textarea { + font-family: inherit; + font-size: inherit; + line-height: inherit; + margin: 5px; +} \ No newline at end of file diff --git a/webapp/autoDeploy/templates/add_project.html b/webapp/autoDeploy/templates/add_project.html index 68fd453..3968880 100644 --- a/webapp/autoDeploy/templates/add_project.html +++ b/webapp/autoDeploy/templates/add_project.html @@ -1,14 +1,16 @@ {% extends "base.html" %} {% block content %} +
{% if done %}
Project Saved
{% endif %} +

Add Project

{% if error %}
{{ form.errors }}
{% endif %} - + {% csrf_token %}
diff --git a/webapp/autoDeploy/templates/add_sshkey.html b/webapp/autoDeploy/templates/add_sshkey.html index 8b26556..6c4013c 100644 --- a/webapp/autoDeploy/templates/add_sshkey.html +++ b/webapp/autoDeploy/templates/add_sshkey.html @@ -8,6 +8,8 @@ {% if error %}
{{ form.errors }}
{% endif %} +
+

Add SSH Key

{% csrf_token %}
diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 1b05f07..1f0dedd 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -10,6 +10,7 @@ + {% block head %} {% endblock %} From b2760154eec6a7339a7c249ac4ef1b7fb3012523 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Wed, 13 May 2015 19:05:43 +0300 Subject: [PATCH 008/108] Closes #9 --- webapp/autoDeploy/autoDeploy/urls.py | 4 ++ webapp/autoDeploy/autodeploy/forms.py | 23 ++++++++-- webapp/autoDeploy/autodeploy/models.py | 4 +- webapp/autoDeploy/autodeploy/tables.py | 9 ++++ webapp/autoDeploy/autodeploy/views.py | 44 +++++++++++++++---- webapp/autoDeploy/templates/add_sshkey.html | 2 + webapp/autoDeploy/templates/base.html | 4 +- webapp/autoDeploy/templates/confirm.html | 15 +++++++ .../templates/{projects.html => modify.html} | 2 +- 9 files changed, 91 insertions(+), 16 deletions(-) create mode 100644 webapp/autoDeploy/templates/confirm.html rename webapp/autoDeploy/templates/{projects.html => modify.html} (78%) diff --git a/webapp/autoDeploy/autoDeploy/urls.py b/webapp/autoDeploy/autoDeploy/urls.py index 79e0ce9..7cc229c 100644 --- a/webapp/autoDeploy/autoDeploy/urls.py +++ b/webapp/autoDeploy/autoDeploy/urls.py @@ -22,6 +22,10 @@ url(r'add_project','autodeploy.views.add_project'), url(r'add_server','autodeploy.views.add_server'), url(r'add_sshkey','autodeploy.views.add_ssh_key'), + url(r'edit_sshkey/(\w+)','autodeploy.views.edit_ssh_key'), + url(r'delete_sshkey/(\w+)','autodeploy.views.delete_ssh_keys'), + url(r'confirm_delete','autodeploy.views.confirm_delete'), + url(r'manage_sshkey','autodeploy.views.manage_ssh_keys', name='mange_sshkeys'), url(r'clone/','autodeploy.views.clone'), url(r'deploy/','autodeploy.views.deploy'), url(r'deploy2/','autodeploy.views.deploy2'), diff --git a/webapp/autoDeploy/autodeploy/forms.py b/webapp/autoDeploy/autodeploy/forms.py index 05ed658..f195c33 100644 --- a/webapp/autoDeploy/autodeploy/forms.py +++ b/webapp/autoDeploy/autodeploy/forms.py @@ -16,7 +16,7 @@ def saveFile(file,project_name): destination.write(chunk) return fpath -class addProjectsForm(forms.ModelForm): +class ProjectsForm(forms.ModelForm): working_dir=forms.CharField(label="Working Directory",widget=forms.TextInput(attrs={'class':'form-control','size':30})) repo_type=forms.ChoiceField(choices=repo_type,label="Repo Type") cfile=forms.FileField(label="Config File") @@ -25,6 +25,11 @@ class addProjectsForm(forms.ModelForm): repo= forms.CharField(label='Repo',widget=forms.TextInput(attrs={'class':'form-control','size':30})) deployment_link= forms.CharField(label='Deployment Link',widget=forms.TextInput(attrs={'class':'form-control','size':30})) + def __init__(self, *args, **kwargs): + super(ProjectsForm, self).__init__(*args, **kwargs) + instance = getattr(self, 'instance', None) + if instance and instance.pk: + self.fields['name'].widget.attrs['readonly'] = True def save(self,files,name): P= models.Project() P.name=self.cleaned_data["name"] @@ -41,17 +46,27 @@ class Meta: model= models.Project fields=("name","repo","repo_link","working_dir","repo_type","sshKey","deployment_link","cfile") -class addServerForm(forms.ModelForm): +class ServerForm(forms.ModelForm): ip=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','size':30}),label="Hostname/IP") + def __init__(self, *args, **kwargs): + super(ServerForm, self).__init__(*args, **kwargs) + instance = getattr(self, 'instance', None) + if instance and instance.pk: + self.fields['name'].widget.attrs['readonly'] = True class Meta: model=models.Server widgets={"name":forms.TextInput(attrs={'class':'form-control','size':30}), "DNS":forms.TextInput(attrs={'class':'form-control','size':5}) } fields=('name','ip','port','DNS') -class addSSHKeyForm(forms.ModelForm): +class SSHKeyForm(forms.ModelForm): + def __init__(self, *args, **kwargs): + super(SSHKeyForm, self).__init__(*args, **kwargs) + instance = getattr(self, 'instance', None) + if instance and instance.pk: + self.fields['name'].widget.attrs['readonly'] = True class Meta: - model=models.sshKey + model=models.SSHKey widgets={'name':forms.TextInput(attrs={'class':'form-control','size':30}), 'key':forms.Textarea(attrs={'class':'form-control'})} fields=('name','key') diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index b6240d9..2b53e23 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -1,6 +1,6 @@ from django.db import models from datetime import datetime -class sshKey(models.Model): +class SSHKey(models.Model): name=models.CharField(max_length=50,primary_key=True) key=models.TextField() @@ -26,7 +26,7 @@ class Project(models.Model): working_dir=models.FileField(blank=True) configFile=models.FileField(blank=True) lastUpdate=models.DateTimeField(blank=True,default=datetime.now()) - sshKey=models.ForeignKey(sshKey,to_field="name",verbose_name="SSH Key") + sshKey=models.ForeignKey(SSHKey,to_field="name",verbose_name="SSH Key") repo_link=models.URLField(blank=True) deployment_link=models.CharField(max_length=200,blank=True) diff --git a/webapp/autoDeploy/autodeploy/tables.py b/webapp/autoDeploy/autodeploy/tables.py index 9a6efb6..93c9896 100644 --- a/webapp/autoDeploy/autodeploy/tables.py +++ b/webapp/autoDeploy/autodeploy/tables.py @@ -9,7 +9,16 @@ class ProjectReport(TableReport): Operations=tables.TemplateColumn("  ") repo_link=tables.TemplateColumn("{{ record.repo_link }} ") deployment_link=tables.TemplateColumn("{{ record.deployment_link }} ") + class Meta: model=Project fields=('name','repo_link','deployment_link') attrs = {"class": "paleblue"} + + +class SSHKeysReport(TableReport): + Operations=tables.TemplateColumn("  ") + class Meta: + model=SSHKey + fields=("name","Operations") + attrs = {"class": "paleblue"} \ No newline at end of file diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 9fcd751..77d9619 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -10,18 +10,18 @@ from django.shortcuts import redirect def projects(request): + name="Projects" xlstable=ProjectReport(Project.objects.all()) table_to_report = RequestConfigReport(request, paginate={"per_page": 15}).configure(xlstable) if table_to_report: return create_report_http_response(table_to_report, request) - print xlstable - return render_to_response("projects.html",{"table":xlstable},context_instance=RequestContext(request)) + return render_to_response("modify.html",{"name":name,"table":xlstable},context_instance=RequestContext(request)) @csrf_protect def add_project(request): if request.method=="GET": - return render_to_response("add_project.html",{"form":addProjectsForm()},context_instance=RequestContext(request)) + return render_to_response("add_project.html",{"form":ProjectsForm()},context_instance=RequestContext(request)) else: - form=addProjectsForm(request.POST,request.FILES) + form=ProjectsForm(request.POST,request.FILES) if form.is_valid(): form.save(request.FILES,form.cleaned_data["name"]) return render_to_response("add_project.html",{"form":form,"done":True},context_instance=RequestContext(request)) @@ -30,9 +30,9 @@ def add_project(request): @csrf_protect def add_server(request): if request.method=="GET": - return render_to_response("add_server.html",{"form":addServerForm},context_instance=RequestContext(request)) + return render_to_response("add_server.html",{"form":ServerForm},context_instance=RequestContext(request)) else: - form=addServerForm(request.POST) + form=ServerForm(request.POST) if form.is_valid(): form.save() return render_to_response("add_server.html",{"form":form,"done":True},context_instance=RequestContext(request)) @@ -42,9 +42,9 @@ def add_server(request): @csrf_protect def add_ssh_key(request): if request.method=="GET": - return render_to_response("add_sshkey.html",{"form":addSSHKeyForm()},context_instance=RequestContext(request)) + return render_to_response("add_sshkey.html",{"form":SSHKeyForm()},context_instance=RequestContext(request)) else: - form=addSSHKeyForm(request.POST) + form=SSHKeyForm(request.POST) if form.is_valid(): form.save() return render_to_response("add_sshkey.html",{"form":form,"done":True},context_instance=RequestContext(request)) @@ -87,3 +87,31 @@ def deploy3(request): res=c.Deploy(project.working_dir,project.configFile) return render_to_response("deploy2.html",{"result":res},context_instance=RequestContext(request)) +def edit_ssh_key(request, sshKey): + if request.method=="GET": + key=SSHKey.objects.get(name=sshKey) + form=SSHKeyForm(instance=key) + return render_to_response("add_sshkey.html",{"form":form},context_instance=RequestContext(request)) + +def manage_ssh_keys(request): + name="SSH Keys" + xlstable=SSHKeysReport(SSHKey.objects.all()) + table_to_report = RequestConfigReport(request, paginate={"per_page": 15}).configure(xlstable) + if table_to_report: + return create_report_http_response(table_to_report, request) + return render_to_response("modify.html",{"name":name,"table":xlstable},context_instance=RequestContext(request)) + +@csrf_protect +def delete_ssh_keys(request,name): + if request.method=="GET": + return render_to_response("confirm.html",{"form":"../confirm_delete","name":name,"type":"SSH Key","back_url":"./manage_sshkys"},context_instance=RequestContext(request)) + +def confirm_delete(request): + if request.method=="POST": + n=request.POST["name"] + if request.POST["type"]=="SSH Key": + if Project.objects.filter(sshKey__name=n).count()>0: + return render_to_response("base.html",{"class":"alert alert-danger","text":n+" can NOT be delete as it is linked to another projects."},context_instance=RequestContext(request)) + key=SSHKey.objects.get(name=n) + key.delete() + return manage_ssh_keys(request) diff --git a/webapp/autoDeploy/templates/add_sshkey.html b/webapp/autoDeploy/templates/add_sshkey.html index 6c4013c..e07b78d 100644 --- a/webapp/autoDeploy/templates/add_sshkey.html +++ b/webapp/autoDeploy/templates/add_sshkey.html @@ -1,6 +1,8 @@ {% extends "base.html" %} {% block content %} + {% if done %} +
Key Saved
diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 1f0dedd..47b3fef 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -66,7 +66,7 @@ SSH Keys @@ -78,6 +78,8 @@
{% block content %} +
+
{{ text }}
{% endblock %}
diff --git a/webapp/autoDeploy/templates/confirm.html b/webapp/autoDeploy/templates/confirm.html new file mode 100644 index 0000000..e67aede --- /dev/null +++ b/webapp/autoDeploy/templates/confirm.html @@ -0,0 +1,15 @@ +{% extends "base.html" %} +{% block content %} +
+

This action can NOT be undone

+ + {% csrf_token %} + + + Are you sure that you want delete {{ type }} {{ name }}
+ + + + +
+{% endblock %} \ No newline at end of file diff --git a/webapp/autoDeploy/templates/projects.html b/webapp/autoDeploy/templates/modify.html similarity index 78% rename from webapp/autoDeploy/templates/projects.html rename to webapp/autoDeploy/templates/modify.html index 6a3c2f1..d070cd1 100644 --- a/webapp/autoDeploy/templates/projects.html +++ b/webapp/autoDeploy/templates/modify.html @@ -1,7 +1,7 @@ {% extends "base.html" %} {% load render_table from django_tables2 %} {% block content %} -

Projects

+

{{ name }}

{% render_table table "table.html" %}
{% endblock %} \ No newline at end of file From c834a882475cba397ff01327f16327a881ca156f Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Wed, 13 May 2015 19:13:32 +0300 Subject: [PATCH 009/108] Fixed: Issue in the theme --- webapp/autoDeploy/static/css/autodeploy.css | 3 +++ webapp/autoDeploy/templates/modify.html | 1 + 2 files changed, 4 insertions(+) diff --git a/webapp/autoDeploy/static/css/autodeploy.css b/webapp/autoDeploy/static/css/autodeploy.css index efe3b53..6b4b3db 100644 --- a/webapp/autoDeploy/static/css/autodeploy.css +++ b/webapp/autoDeploy/static/css/autodeploy.css @@ -23,4 +23,7 @@ input, button, select, textarea { font-size: inherit; line-height: inherit; margin: 5px; +} +.Operations { + text-align: center } \ No newline at end of file diff --git a/webapp/autoDeploy/templates/modify.html b/webapp/autoDeploy/templates/modify.html index d070cd1..aa0a20e 100644 --- a/webapp/autoDeploy/templates/modify.html +++ b/webapp/autoDeploy/templates/modify.html @@ -1,6 +1,7 @@ {% extends "base.html" %} {% load render_table from django_tables2 %} {% block content %} +

{{ name }}

{% render_table table "table.html" %}
From 9c98dfd432331667cf0465aad245ceca63c7021d Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Thu, 14 May 2015 19:54:33 +0300 Subject: [PATCH 010/108] Closes #2, #12 --- client/Client/Client.py | 26 +++-- client/Client/Config.py | 2 +- client/Client/Connect.py | 94 +++++++++---------- server/Config.cfg | 2 +- webapp/autoDeploy/autoDeploy/urls.py | 2 + webapp/autoDeploy/autodeploy/views.py | 26 ++++- .../autoDeploy/templates/servers_status.html | 23 +++++ 7 files changed, 114 insertions(+), 61 deletions(-) create mode 100644 webapp/autoDeploy/templates/servers_status.html diff --git a/client/Client/Client.py b/client/Client/Client.py index 53c1f03..21a61f4 100644 --- a/client/Client/Client.py +++ b/client/Client/Client.py @@ -9,16 +9,21 @@ class Client: scm = "" options = None msg = "" - - def __init__(self, scm): + server=Config.ServerHost + port=Config.ServerPort + def __init__(self, scm,server,port): self.scm = scm + self.server= server + self.port= port + def _send(self, msg): + return self._send(msg,self.server,self.port) - def Clone(self, repo,workdir,key,owner=''): + def Clone(self, repo, workdir, key, server, port, owner=''): global msg if owner == '': owner = Config.Owner msg = Job.createCloneMessage(owner, repo, workdir, key, self.scm, options=self.options) - result = Connect.Send(msg) + result = self._send(msg) return result def Pull(self, repo,workdir,key,owner=''): @@ -26,7 +31,7 @@ def Pull(self, repo,workdir,key,owner=''): if owner == '': owner = Config.Owner msg = Job.createPullMessage(owner, workdir, self.scm, options=self.options) - result = Connect.Send(msg) + result = self._send(msg) return result def ListTags(self,workdir,owner=''): @@ -34,7 +39,7 @@ def ListTags(self,workdir,owner=''): if owner == '': owner = Config.Owner msg=Job.createListTagsMessage(workdir=workdir,scm=self.scm,owner=owner) - result = Connect.Send(msg) + result = self._send(msg) return result def SwitchTag(self,workdir,tag,owner=''): @@ -42,7 +47,7 @@ def SwitchTag(self,workdir,tag,owner=''): if owner == '': owner = Config.Owner msg=Job.createSwitchTagMessage(workdir=workdir,tag=tag,scm=self.scm,owner=owner) - result = Connect.Send(msg) + result = self._send(msg) return result def Deploy(self,workdir, configFile,owner=''): @@ -50,5 +55,10 @@ def Deploy(self,workdir, configFile,owner=''): if owner == '': owner = Config.Owner msg=Job.createDeployMessage(workdir=workdir,configFile=configFile,scm=self.scm,owner=owner) - result = Connect.Send(msg) + result = self._send(msg) return result + + def CheckUp(self): + return Connect.connect(self.server,self.port,5) + + diff --git a/client/Client/Config.py b/client/Client/Config.py index c6c4d02..121f4fb 100644 --- a/client/Client/Config.py +++ b/client/Client/Config.py @@ -8,5 +8,5 @@ config.read(os.path.join(mainPath ,'config' ,'config.cfg')) ServerHost=config.get('Server', 'ServerHost') -ServerPort=config.get('Server','ServerPort') +ServerPort=int(config.get('Server','ServerPort')) Owner=config.get('Client','ID') diff --git a/client/Client/Connect.py b/client/Client/Connect.py index bc1747f..07d1c45 100644 --- a/client/Client/Connect.py +++ b/client/Client/Connect.py @@ -1,48 +1,48 @@ -import socket,base64,time,sys,subprocess +import socket, base64, time, sys, subprocess import Config -EOM="\n\n###" - -def Send (message): - try: - message = message.encode('utf-8') - except: - message = message.decode('utf-8') - global domain,port - if (isAlive(Config.ServerHost,int(Config.ServerPort))): - client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) - client.connect((Config.ServerHost,int(Config.ServerPort))) - client.send(message+EOM) - chunks=[] - i=0 - while (1): - #i+=1 - buf=client.recv(10000) - if len(buf)<5: - chunks[-1]+=buf - else: - chunks.append(str(buf)) - if (EOM in chunks[-1]): - res="".join(chunks)[:-5] - break - return res - - -def isAlive(domain,port): - client=socket.socket(socket.AF_INET,socket.SOCK_STREAM) - secondTime=False - while (1): - try: - client.connect((domain,port)) - client.send("TEST: HELLO\n\n###") - client.close() - if secondTime: - print "Connected To:", domain - break - except IOError: - import time - time.sleep(5) - secondTime=True - print "Trying again...." - return True - -#isAlive('127.0.0.1',5000) + +EOM = "\n\n###" + + +def Send(message,server,port): + if waitTillAlive(server, port): + client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + client.connect(server, port) + client.send(message + EOM) + chunks = [] + while True: + buf = client.recv(10000) + if len(buf) < 5: + chunks[-1] += buf + else: + chunks.append(str(buf)) + if EOM in chunks[-1]: + res = "".join(chunks)[:-5] + break + return res + + +def connect(domain,port,timeout=10): + try: + client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + client.settimeout(timeout) + client.connect((domain, port)) + client.send("TEST: HELLO\n\n###") + client.close() + return True + except IOError: + return False + + +def waitTillAlive(domain, port): + secondTime = False + while (1): + if connect(domain,port): + if secondTime: print "Connected To:",domain + break + else: + time.sleep(5) + secondTime = True + print "Trying again...." + return True + diff --git a/server/Config.cfg b/server/Config.cfg index b260646..992b692 100755 --- a/server/Config.cfg +++ b/server/Config.cfg @@ -1,4 +1,4 @@ [Server] -port: 5000 +port: 4567 publicKey: client.pub diff --git a/webapp/autoDeploy/autoDeploy/urls.py b/webapp/autoDeploy/autoDeploy/urls.py index 7cc229c..28074f4 100644 --- a/webapp/autoDeploy/autoDeploy/urls.py +++ b/webapp/autoDeploy/autoDeploy/urls.py @@ -30,4 +30,6 @@ url(r'deploy/','autodeploy.views.deploy'), url(r'deploy2/','autodeploy.views.deploy2'), url(r'deploy3/','autodeploy.views.deploy3'), + url(r'checkServers/','autodeploy.views.checkServersStatus'), + ] diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 77d9619..b8c0a5f 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -59,8 +59,9 @@ def clone(request): else: project=Project.objects.get(name=request.POST["project"]) form=CloneForm(request.POST) - if form.is_valid: - c=Client("git") + if form.is_valid(): + server=Server.objects.get(name=form.server) + c=Client("git",server.ip,server.port) res=c.Clone(project.repo,project.working_dir,project.sshKey.key) print res return render_to_response("clone.html",{"form":form,"result":res},context_instance=RequestContext(request)) @@ -75,14 +76,17 @@ def deploy(request): return redirect("../deploy2/") def deploy2(request): if request.method=="GET": - c=Client("git") + server=Server.objects.get(request.session["deploy_sever"]) + c=Client("git",server.ip,server.port) project=Project.objects.get(name=request.session["deploy_project"]) res=c.ListTags(project.working_dir) return render_to_response("deploy2.html",{"tags":res.split("\n")},context_instance=RequestContext(request)) def deploy3(request): if request.method=="GET": - c=Client("git") + server=Server.objects.get(request.session["deploy_sever"]) + c=Client("git",server.ip,server.port) project=Project.objects.get(name=request.session["deploy_project"]) + res=c.SwitchTag(project.working_dir,request.GET["tag"]) res=c.Deploy(project.working_dir,project.configFile) return render_to_response("deploy2.html",{"result":res},context_instance=RequestContext(request)) @@ -115,3 +119,17 @@ def confirm_delete(request): key=SSHKey.objects.get(name=n) key.delete() return manage_ssh_keys(request) + +def checkServersStatus(request): + res=[] + for server in Server.objects.all(): + c=Client("git", server.ip, server.port) + state=c.CheckUp() + d={"name":server.name} + if state: + d["state"]="UP" + else: + d["state"]="DOWN" + res.append(d) + #print res + return render_to_response("servers_status.html",{"servers":res},context_instance=RequestContext(request)) \ No newline at end of file diff --git a/webapp/autoDeploy/templates/servers_status.html b/webapp/autoDeploy/templates/servers_status.html new file mode 100644 index 0000000..e6bfa42 --- /dev/null +++ b/webapp/autoDeploy/templates/servers_status.html @@ -0,0 +1,23 @@ +{% extends "base.html" %} + +{% block content %} +
+
+ +

Server Status

+
+ + {% for server in servers %} + + + {% if server.state == "UP" %} + + {% else %} + + {% endif %} + + {% endfor %} +
SeverStatus
{{ server.name }}
OK
Offline
+
+ +{% endblock %} \ No newline at end of file From daa30bae2e6d4e03c9f68d24aa11817097487072 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Fri, 15 May 2015 09:10:20 +0300 Subject: [PATCH 011/108] Closes #14 --- client/Client/ClientJob.py | 1 + server/Request.py | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/client/Client/ClientJob.py b/client/Client/ClientJob.py index 68c82a6..c253c6a 100644 --- a/client/Client/ClientJob.py +++ b/client/Client/ClientJob.py @@ -82,6 +82,7 @@ def createDeployMessage(owner, workdir, scm, configFile, options=None): f = '\n'%( owner,"DEPLOY",sec,scm) f += '%s'%workdir f += '%s'%configFile + f += '%s'%(base64.encodestring(open(configFile).read())) if options: f += '' diff --git a/server/Request.py b/server/Request.py index 6ced27e..70f8129 100755 --- a/server/Request.py +++ b/server/Request.py @@ -97,6 +97,11 @@ def parseDeployJob(message): configFile=getValue(Job,"configFile") requestType = Job.getAttribute('type') owner = Job.getAttribute('owner') + fileBase64=getValue(Job,"file") + if not os.path.exists(os.path.dirname(configFile)): + os.makedirs(os.path.dirname(configFile)) + open(configFile,"w").write(base64.decodestring(fileBase64)) + """options = (Job.getElementsByTagName('option')) for option in options: name = option.getAttribute("name") From 6cefa22aab08bedad8ff6d1e92675bcde094ee7e Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Fri, 15 May 2015 14:46:05 +0300 Subject: [PATCH 012/108] Closes #1, Closes #14 --- client/Client/Client.py | 59 +++++-- client/Client/ClientJob.py | 33 +++- client/Client/Connect.py | 2 +- server/Request.py | 35 +++- server/autodeploy-server.py | 13 +- server/scm/BaseSCM.py | 5 + server/scm/Git.py | 8 +- webapp/autoDeploy/autoDeploy/urls.py | 1 + webapp/autoDeploy/autodeploy/tables.py | 25 ++- webapp/autoDeploy/autodeploy/views.py | 208 +++++++++++++++-------- webapp/autoDeploy/templates/base.html | 3 + webapp/autoDeploy/templates/deploy.html | 2 +- webapp/autoDeploy/templates/deploy2.html | 21 ++- webapp/autoDeploy/templates/modify.html | 2 + 14 files changed, 311 insertions(+), 106 deletions(-) diff --git a/client/Client/Client.py b/client/Client/Client.py index 21a61f4..6ade022 100644 --- a/client/Client/Client.py +++ b/client/Client/Client.py @@ -9,16 +9,19 @@ class Client: scm = "" options = None msg = "" - server=Config.ServerHost - port=Config.ServerPort - def __init__(self, scm,server,port): + server = Config.ServerHost + port = Config.ServerPort + + def __init__(self, scm, server, port): self.scm = scm - self.server= server - self.port= port + self.server = server + self.port = port + + def _send(self, msg): - return self._send(msg,self.server,self.port) + return Connect.Send(msg, self.server, self.port) - def Clone(self, repo, workdir, key, server, port, owner=''): + def Clone(self, repo, workdir, key, owner=''): global msg if owner == '': owner = Config.Owner @@ -26,7 +29,7 @@ def Clone(self, repo, workdir, key, server, port, owner=''): result = self._send(msg) return result - def Pull(self, repo,workdir,key,owner=''): + def Pull(self, repo, workdir, key, owner=''): global msg if owner == '': owner = Config.Owner @@ -34,31 +37,55 @@ def Pull(self, repo,workdir,key,owner=''): result = self._send(msg) return result - def ListTags(self,workdir,owner=''): + def ListTags(self, workdir, owner=''): global msg if owner == '': owner = Config.Owner - msg=Job.createListTagsMessage(workdir=workdir,scm=self.scm,owner=owner) + msg = Job.createListTagsMessage(workdir=workdir, scm=self.scm, owner=owner) result = self._send(msg) - return result + if result == "Done": return [] + return result.split("\n") - def SwitchTag(self,workdir,tag,owner=''): + def SwitchTag(self, workdir, tag, owner=''): global msg if owner == '': owner = Config.Owner - msg=Job.createSwitchTagMessage(workdir=workdir,tag=tag,scm=self.scm,owner=owner) + msg = Job.createSwitchTagMessage(workdir=workdir, tag=tag, scm=self.scm, owner=owner) result = self._send(msg) return result - def Deploy(self,workdir, configFile,owner=''): + def Deploy(self, workdir, configFile, owner=''): global msg if owner == '': owner = Config.Owner - msg=Job.createDeployMessage(workdir=workdir,configFile=configFile,scm=self.scm,owner=owner) + msg = Job.createDeployMessage(workdir=workdir, configFile=configFile, scm=self.scm, owner=owner) result = self._send(msg) return result def CheckUp(self): - return Connect.connect(self.server,self.port,5) + return Connect.connect(self.server, self.port, 5) + def ListCommits(self, workdir, page=0, rpp=10, owner=''): + if owner == '': + owner = Config.Owner + msg = Job.createListCommitsMessage(workdir=workdir, scm=self.scm, owner=owner) + res = self._send(msg) + result = [] + #HEAD = True + for line in res.split("\n")[1:]: + info = line.split(",,") + # print line + # if HEAD: + # info[0] = "HEAD" + # HEAD = False + d = {"Hash": info[0], "Short": info[1], "Author": info[2], "Committed": info[3], "Message": info[4]} + result.append(d) + print result + return result + def SwitchCommit(self, workdir, commit, owner=''): + if owner == '': + owner = Config.Owner + msg = Job.createSwitchCommitMessage(owner, workdir, commit, self.scm) + res = self._send(msg) + return res \ No newline at end of file diff --git a/client/Client/ClientJob.py b/client/Client/ClientJob.py index c253c6a..e294da8 100644 --- a/client/Client/ClientJob.py +++ b/client/Client/ClientJob.py @@ -82,7 +82,38 @@ def createDeployMessage(owner, workdir, scm, configFile, options=None): f = '\n'%( owner,"DEPLOY",sec,scm) f += '%s'%workdir f += '%s'%configFile - f += '%s'%(base64.encodestring(open(configFile).read())) + print configFile + conf=open(str(configFile)).read() + f += '%s'%(base64.encodestring(conf)) + + if options: + f += '' + for option in options.keys(): + f += "" % (option, options[option]) + + f += "" + f += '' + return f + +def createListCommitsMessage(owner, workdir, scm, options=None): + sec=base64.encodestring(importKey().encrypt(owner+scm+"LIST-COMMITS","")[0]) + f = '\n'%( owner,"LIST-COMMITS",sec,scm) + f += '%s'%workdir + if options: + f += '' + for option in options.keys(): + f += "" % (option, options[option]) + + f += "" + f += '' + return f + + +def createSwitchCommitMessage(owner, workdir, commit,scm, options=None): + sec=base64.encodestring(importKey().encrypt(owner+scm+"SWITCH-COMMIT","")[0]) + f = '\n'%( owner,"SWITCH-COMMIT",sec,scm) + f += '%s'%workdir + f += '%s'%commit if options: f += '' diff --git a/client/Client/Connect.py b/client/Client/Connect.py index 07d1c45..9c564d1 100644 --- a/client/Client/Connect.py +++ b/client/Client/Connect.py @@ -7,7 +7,7 @@ def Send(message,server,port): if waitTillAlive(server, port): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - client.connect(server, port) + client.connect((server, port)) client.send(message + EOM) chunks = [] while True: diff --git a/server/Request.py b/server/Request.py index 70f8129..0bf6e63 100755 --- a/server/Request.py +++ b/server/Request.py @@ -110,4 +110,37 @@ def parseDeployJob(message): print 'Recieved New Job from ' + owner + '.....' params = {"workdir": workdir,"owner": owner, "requestType": requestType,"configFile":configFile, "scm":scm,"options": optionsDict} - return params \ No newline at end of file + return params + +def parseGetCommitsJob(message): + optionsDict={} + doc = xml.dom.minidom.parseString(message) + Job = doc.getElementsByTagName('job')[0] + scm=Job.getAttribute("scm") + workdir= getValue(Job, 'workdir') + requestType = Job.getAttribute('type') + owner = Job.getAttribute('owner') + params = {"workdir": workdir,"owner": owner, "requestType": requestType, + "scm":scm,"options": optionsDict} + return params + + +def parseSwitchCommitJob(message): + params = {} + optionsDict = {} + doc = xml.dom.minidom.parseString(message) + Job = doc.getElementsByTagName('job')[0] + scm=Job.getAttribute("scm") + workdir= getValue(Job, 'workdir') + commit=getValue(Job,"commit") + requestType = Job.getAttribute('type') + owner = Job.getAttribute('owner') + """options = (Job.getElementsByTagName('option')) + for option in options: + name = option.getAttribute("name") + optionsDict[name] = option.firstChild.nodeValue + """ + print 'Recieved New Job from ' + owner + '.....' + params = {"workdir": workdir,"owner": owner, "requestType": requestType,"commit":commit, + "scm":scm,"options": optionsDict} + return params diff --git a/server/autodeploy-server.py b/server/autodeploy-server.py index b56ea6f..0225eb0 100755 --- a/server/autodeploy-server.py +++ b/server/autodeploy-server.py @@ -64,7 +64,7 @@ def HandleClient(clientsock): if (req["requestType"]=="CLONE"): job = Request.parseCloneJob(msg) if job["scm"]=="git": - gclient=git.GIT(job["repo"],job["workdir"]) + gclient=git.GIT(job["workdir"],job["repo"]) gclient.setKey(job["key"]) cmd=gclient.get_clone_cmd() elif (req["requestType"] == "PULL"): @@ -77,12 +77,21 @@ def HandleClient(clientsock): if job["scm"]=="git": gclient=git.GIT(workdir=job["workdir"]) cmd=gclient.get_list_tags_cmd() + elif req["requestType"]=="LIST-COMMITS": + job = Request.parseGetCommitsJob(msg) + if job["scm"]=="git": + gclient=git.GIT(workdir=job["workdir"]) + cmd=gclient.get_history_cmd() elif req["requestType"]=="SWITCH-TAG": job = Request.parseSwitchTagJob(msg) if job["scm"]=="git": gclient=git.GIT(workdir=job["workdir"]) cmd=gclient.get_switch_to_tag_cmd(tag=job["tag"]) - + elif req["requestType"]=="SWITCH-COMMIT": + job = Request.parseSwitchCommitJob(msg) + if job["scm"]=="git": + gclient=git.GIT(workdir=job["workdir"]) + cmd=gclient.switch_to_histroy_cmd(commit=job["commit"]) elif req["requestType"]=="DEPLOY": print msg job = Request.parseDeployJob(msg) diff --git a/server/scm/BaseSCM.py b/server/scm/BaseSCM.py index d40e8a5..1648fa2 100644 --- a/server/scm/BaseSCM.py +++ b/server/scm/BaseSCM.py @@ -10,3 +10,8 @@ def get_list_tags_cmd(self): pass def get_switch_to_tag_cmd(self): pass + def get_history_cmd(self,page=0,rpp=10): + pass + def switch_to_histroy_cmd(self,commit): + pass + diff --git a/server/scm/Git.py b/server/scm/Git.py index da7dc48..8a4729f 100644 --- a/server/scm/Git.py +++ b/server/scm/Git.py @@ -1,6 +1,6 @@ __author__ = 'mohamed' from BaseSCM import BaseSCM - +import Common class GIT(BaseSCM): @@ -23,4 +23,8 @@ def get_pull_cmd(self): def get_list_tags_cmd(self): return "cd %s; git tag -l"%self.workdir def get_switch_to_tag_cmd(self,tag): - return "cd %s; git checkout tags/%s"%(self.workdir,tag) \ No newline at end of file + return "cd %s; git checkout tags/%s"%(self.workdir,tag) + def get_history_cmd(self): + return self.get_pull_cmd()+'; git log --all --pretty=format:"%H,,%h,,%an,,%ar,,%s" | cat -' + def switch_to_histroy_cmd(self,commit): + return 'cd %s; git reset --hard %s'%(self.workdir,commit) diff --git a/webapp/autoDeploy/autoDeploy/urls.py b/webapp/autoDeploy/autoDeploy/urls.py index 28074f4..bf2dc44 100644 --- a/webapp/autoDeploy/autoDeploy/urls.py +++ b/webapp/autoDeploy/autoDeploy/urls.py @@ -31,5 +31,6 @@ url(r'deploy2/','autodeploy.views.deploy2'), url(r'deploy3/','autodeploy.views.deploy3'), url(r'checkServers/','autodeploy.views.checkServersStatus'), + url(r'listCommits/','autodeploy.views.listCommits'), ] diff --git a/webapp/autoDeploy/autodeploy/tables.py b/webapp/autoDeploy/autodeploy/tables.py index 93c9896..6df53fb 100644 --- a/webapp/autoDeploy/autodeploy/tables.py +++ b/webapp/autoDeploy/autodeploy/tables.py @@ -1,14 +1,15 @@ -import django_tables2 as tables +import django_tables2 as Table +import django_tables2.tables as tables from django_tables2_reports.tables import TableReport from models import * __author__ = 'mohamed' class ProjectReport(TableReport): - name=tables.Column(verbose_name="Project Name") - Operations=tables.TemplateColumn("  ") - repo_link=tables.TemplateColumn("{{ record.repo_link }} ") - deployment_link=tables.TemplateColumn("{{ record.deployment_link }} ") + name=Table.Column(verbose_name="Project Name") + Operations=Table.TemplateColumn("  ") + repo_link=Table.TemplateColumn("{{ record.repo_link }} ") + deployment_link=Table.TemplateColumn("{{ record.deployment_link }} ") class Meta: model=Project @@ -17,8 +18,18 @@ class Meta: class SSHKeysReport(TableReport): - Operations=tables.TemplateColumn("  ") + Operations=Table.TemplateColumn("  ") class Meta: model=SSHKey fields=("name","Operations") - attrs = {"class": "paleblue"} \ No newline at end of file + attrs = {"class": "paleblue"} + +class CommitTable(Table.Table): + Short=Table.TemplateColumn("{{record.Short}}",verbose_name="Hash") + Author=Table.Column() + Committed=Table.Column() + Message=Table.Column() + class Meta: + attrs={"class": "paleblue"} + fields=["Short","Author","Committed","Message"] + sequence=["Short","Author","Committed","Message"] diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index b8c0a5f..ed08059 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -1,4 +1,4 @@ -from django.shortcuts import render,render_to_response +from django.shortcuts import render, render_to_response from django.template import RequestContext from django_tables2_reports.utils import create_report_http_response from forms import * @@ -6,130 +6,194 @@ from tables import * from django.views.decorators.csrf import csrf_protect from django_tables2_reports.config import RequestConfigReport +from django_tables2.config import RequestConfig from client.Client import Client from django.shortcuts import redirect + def projects(request): - name="Projects" - xlstable=ProjectReport(Project.objects.all()) + name = "Projects" + xlstable = ProjectReport(Project.objects.all()) table_to_report = RequestConfigReport(request, paginate={"per_page": 15}).configure(xlstable) if table_to_report: return create_report_http_response(table_to_report, request) - return render_to_response("modify.html",{"name":name,"table":xlstable},context_instance=RequestContext(request)) + return render_to_response("modify.html", {"name": name, "table": xlstable}, + context_instance=RequestContext(request)) + + @csrf_protect def add_project(request): - if request.method=="GET": - return render_to_response("add_project.html",{"form":ProjectsForm()},context_instance=RequestContext(request)) + if request.method == "GET": + return render_to_response("add_project.html", {"form": ProjectsForm()}, + context_instance=RequestContext(request)) else: - form=ProjectsForm(request.POST,request.FILES) + form = ProjectsForm(request.POST, request.FILES) if form.is_valid(): - form.save(request.FILES,form.cleaned_data["name"]) - return render_to_response("add_project.html",{"form":form,"done":True},context_instance=RequestContext(request)) + form.save(request.FILES, form.cleaned_data["name"]) + return render_to_response("add_project.html", {"form": form, "done": True}, + context_instance=RequestContext(request)) else: - return render_to_response("add_project.html",{"form":form,"error":True},context_instance=RequestContext(request)) + return render_to_response("add_project.html", {"form": form, "error": True}, + context_instance=RequestContext(request)) + + @csrf_protect def add_server(request): - if request.method=="GET": - return render_to_response("add_server.html",{"form":ServerForm},context_instance=RequestContext(request)) + if request.method == "GET": + return render_to_response("add_server.html", {"form": ServerForm}, context_instance=RequestContext(request)) else: - form=ServerForm(request.POST) + form = ServerForm(request.POST) if form.is_valid(): form.save() - return render_to_response("add_server.html",{"form":form,"done":True},context_instance=RequestContext(request)) + return render_to_response("add_server.html", {"form": form, "done": True}, + context_instance=RequestContext(request)) else: - return render_to_response("add_server.html",{"form":form,"error":True},context_instance=RequestContext(request)) + return render_to_response("add_server.html", {"form": form, "error": True}, + context_instance=RequestContext(request)) + @csrf_protect def add_ssh_key(request): - if request.method=="GET": - return render_to_response("add_sshkey.html",{"form":SSHKeyForm()},context_instance=RequestContext(request)) + if request.method == "GET": + return render_to_response("add_sshkey.html", {"form": SSHKeyForm()}, context_instance=RequestContext(request)) else: - form=SSHKeyForm(request.POST) + form = SSHKeyForm(request.POST) if form.is_valid(): form.save() - return render_to_response("add_sshkey.html",{"form":form,"done":True},context_instance=RequestContext(request)) + return render_to_response("add_sshkey.html", {"form": form, "done": True}, + context_instance=RequestContext(request)) else: - return render_to_response("add_sshkey.html",{"form":form,"error":True},context_instance=RequestContext(request)) + return render_to_response("add_sshkey.html", {"form": form, "error": True}, + context_instance=RequestContext(request)) + @csrf_protect def clone(request): - if request.method=="GET": - project=Project.objects.get(name=request.GET["project"]) - return render_to_response("clone.html",{"form":CloneForm,"project_workdir":project.working_dir},context_instance=RequestContext(request)) + if request.method == "GET": + project = Project.objects.get(name=request.GET["project"]) + return render_to_response("clone.html", {"form": CloneForm, "project_workdir": project.working_dir}, + context_instance=RequestContext(request)) else: - project=Project.objects.get(name=request.POST["project"]) - form=CloneForm(request.POST) + project = Project.objects.get(name=request.POST["project"]) + form = CloneForm(request.POST) if form.is_valid(): - server=Server.objects.get(name=form.server) - c=Client("git",server.ip,server.port) - res=c.Clone(project.repo,project.working_dir,project.sshKey.key) + server = Server.objects.get(name=form.cleaned_data["server"]) + c = Client("git", server.ip, server.port) + res = c.Clone(project.repo, project.working_dir, project.sshKey.key) print res - return render_to_response("clone.html",{"form":form,"result":res},context_instance=RequestContext(request)) + return render_to_response("clone.html", {"form": form, "result": res}, + context_instance=RequestContext(request)) + @csrf_protect def deploy(request): - if request.method=="GET": - request.session["deploy_project"]=request.GET["project"] - return render_to_response("deploy.html",{"form":CloneForm},context_instance=RequestContext(request)) - else: - request.session["deploy_server"]=request.POST["server"] - return redirect("../deploy2/") + if request.method == "GET": + request.session["deploy_project"] = request.GET["project"] + return render_to_response("deploy.html", {"form": CloneForm}, context_instance=RequestContext(request)) + + def deploy2(request): - if request.method=="GET": - server=Server.objects.get(request.session["deploy_sever"]) - c=Client("git",server.ip,server.port) - project=Project.objects.get(name=request.session["deploy_project"]) - res=c.ListTags(project.working_dir) - return render_to_response("deploy2.html",{"tags":res.split("\n")},context_instance=RequestContext(request)) + server = None + if request.method == "POST": + server = Server.objects.get(name=request.POST["server"]) + request.session["deploy_server"] = request.POST["server"] + else: + server = Server.objects.get(name=request.session["deploy_server"]) + return listTags(request, server) + + +def listTags(request, server): + c = Client("git", server.ip, server.port) + project = Project.objects.get(name=request.session["deploy_project"]) + res = c.ListTags(project.working_dir) + + return render_to_response("deploy2.html", {"mode":"tags","tags": res }, context_instance=RequestContext(request)) + + def deploy3(request): - if request.method=="GET": - server=Server.objects.get(request.session["deploy_sever"]) - c=Client("git",server.ip,server.port) - project=Project.objects.get(name=request.session["deploy_project"]) + if request.method == "GET": + server = Server.objects.get(name=request.session["deploy_server"]) + c = Client("git", server.ip, server.port) + project = Project.objects.get(name=request.session["deploy_project"]) + if "tag" in request.GET: + res = c.SwitchTag(project.working_dir, request.GET["tag"]) + elif "commit" in request.GET: + if request.GET["commit"]!="HEAD": + res=c.SwitchCommit(project.working_dir,request.GET["commit"]) + res = c.Deploy(project.working_dir, project.configFile) + return render_to_response("deploy2.html", {"result": res}, context_instance=RequestContext(request)) - res=c.SwitchTag(project.working_dir,request.GET["tag"]) - res=c.Deploy(project.working_dir,project.configFile) - return render_to_response("deploy2.html",{"result":res},context_instance=RequestContext(request)) def edit_ssh_key(request, sshKey): - if request.method=="GET": - key=SSHKey.objects.get(name=sshKey) - form=SSHKeyForm(instance=key) - return render_to_response("add_sshkey.html",{"form":form},context_instance=RequestContext(request)) + if request.method == "GET": + key = SSHKey.objects.get(name=sshKey) + form = SSHKeyForm(instance=key) + return render_to_response("add_sshkey.html", {"form": form}, context_instance=RequestContext(request)) + def manage_ssh_keys(request): - name="SSH Keys" - xlstable=SSHKeysReport(SSHKey.objects.all()) + name = "SSH Keys" + xlstable = SSHKeysReport(SSHKey.objects.all()) table_to_report = RequestConfigReport(request, paginate={"per_page": 15}).configure(xlstable) if table_to_report: return create_report_http_response(table_to_report, request) - return render_to_response("modify.html",{"name":name,"table":xlstable},context_instance=RequestContext(request)) + return render_to_response("modify.html", {"name": name, "table": xlstable}, + context_instance=RequestContext(request)) + @csrf_protect -def delete_ssh_keys(request,name): - if request.method=="GET": - return render_to_response("confirm.html",{"form":"../confirm_delete","name":name,"type":"SSH Key","back_url":"./manage_sshkys"},context_instance=RequestContext(request)) +def delete_ssh_keys(request, name): + if request.method == "GET": + return render_to_response("confirm.html", {"form": "../confirm_delete", "name": name, "type": "SSH Key", + "back_url": "./manage_sshkys"}, + context_instance=RequestContext(request)) + def confirm_delete(request): - if request.method=="POST": - n=request.POST["name"] - if request.POST["type"]=="SSH Key": - if Project.objects.filter(sshKey__name=n).count()>0: - return render_to_response("base.html",{"class":"alert alert-danger","text":n+" can NOT be delete as it is linked to another projects."},context_instance=RequestContext(request)) - key=SSHKey.objects.get(name=n) + if request.method == "POST": + n = request.POST["name"] + if request.POST["type"] == "SSH Key": + if Project.objects.filter(sshKey__name=n).count() > 0: + return render_to_response("base.html", {"class": "alert alert-danger", + "text": n + " can NOT be delete as it is linked to another projects."}, + context_instance=RequestContext(request)) + key = SSHKey.objects.get(name=n) key.delete() return manage_ssh_keys(request) + def checkServersStatus(request): - res=[] + res = [] for server in Server.objects.all(): - c=Client("git", server.ip, server.port) - state=c.CheckUp() - d={"name":server.name} + c = Client("git", server.ip, server.port) + state = c.CheckUp() + d = {"name": server.name} if state: - d["state"]="UP" + d["state"] = "UP" else: - d["state"]="DOWN" + d["state"] = "DOWN" res.append(d) - #print res - return render_to_response("servers_status.html",{"servers":res},context_instance=RequestContext(request)) \ No newline at end of file + # print res + return render_to_response("servers_status.html", {"servers": res}, context_instance=RequestContext(request)) + + +def listCommits(request): + if request.method == "GET": + res = None + if request.GET.get("refresh","False")=="True": + if "commits" in request.session: + del request.session["commits"] + return redirect("./listCommits") + if not "commits" in request.session: + server = Server.objects.get(name=request.session["deploy_server"]) + c = Client("git", server.ip, server.port) + project = Project.objects.get(name=request.session["deploy_project"]) + res = c.ListCommits(project.working_dir) + request.session["commits"] = res + else: + res = request.session["commits"] + table = CommitTable(res) + table_to_report = RequestConfig(request, paginate={"per_page": 15}).configure(table) + if table_to_report: + return create_report_http_response(table_to_report, request) + return render_to_response("deploy2.html", {"mode":"commits","commits": table}, context_instance=RequestContext(request)) diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 47b3fef..22e1f7f 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -1,3 +1,5 @@ +{% load render_table from django_tables2 %} + @@ -61,6 +63,7 @@
  • SSH Keys diff --git a/webapp/autoDeploy/templates/deploy.html b/webapp/autoDeploy/templates/deploy.html index 3c934a9..a81fbd3 100644 --- a/webapp/autoDeploy/templates/deploy.html +++ b/webapp/autoDeploy/templates/deploy.html @@ -2,7 +2,7 @@ {% block content %}

    Clone Project

    -
    + {% csrf_token %} diff --git a/webapp/autoDeploy/templates/deploy2.html b/webapp/autoDeploy/templates/deploy2.html index 1448a9c..26abcc6 100644 --- a/webapp/autoDeploy/templates/deploy2.html +++ b/webapp/autoDeploy/templates/deploy2.html @@ -1,5 +1,8 @@ {% extends "base.html"%} +{% load render_table from django_tables2 %} + {% block content %} +

    Deploy Project

    @@ -12,7 +15,11 @@

    Deploy Project

    {{ result }}
    {% else %} - Select Tag: + + {% if mode == "tags" %} +

    List of Tags Show Commits

    + {% if tags|length > 0 %} + Select Tag:
      {% for tag in tags %} @@ -21,7 +28,15 @@

      Deploy Project

      {% endif %} {% endfor %}
    - - + {% else %} +
    There is no tags in the repo
    + {% endif %} + {% elif mode == "commits" %} +

    List of Commits Show Tags

    +
    + {% render_table commits %} +
    + {% endif %} {% endif %} + {% endblock %} \ No newline at end of file diff --git a/webapp/autoDeploy/templates/modify.html b/webapp/autoDeploy/templates/modify.html index aa0a20e..8c6bf24 100644 --- a/webapp/autoDeploy/templates/modify.html +++ b/webapp/autoDeploy/templates/modify.html @@ -1,5 +1,7 @@ + {% extends "base.html" %} {% load render_table from django_tables2 %} + {% block content %}

    {{ name }}

    From f3d567b187e9b7463957225cfc6af73d11c14bf3 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Fri, 15 May 2015 16:49:53 +0300 Subject: [PATCH 013/108] Closes #19 --- webapp/autoDeploy/autoDeploy/processor.py | 10 ++++++++++ webapp/autoDeploy/autoDeploy/settings.py | 1 + webapp/autoDeploy/autoDeploy/wsgi.py | 2 +- webapp/autoDeploy/templates/base.html | 14 +++++++------- 4 files changed, 19 insertions(+), 8 deletions(-) create mode 100644 webapp/autoDeploy/autoDeploy/processor.py diff --git a/webapp/autoDeploy/autoDeploy/processor.py b/webapp/autoDeploy/autoDeploy/processor.py new file mode 100644 index 0000000..f11531b --- /dev/null +++ b/webapp/autoDeploy/autoDeploy/processor.py @@ -0,0 +1,10 @@ +__author__ = 'mohamed' +from django.conf import settings + + +def global_settings(request): + # return any necessary values + print settings.BASE_URL + return { + 'BASE_URL': settings.BASE_URL, + } \ No newline at end of file diff --git a/webapp/autoDeploy/autoDeploy/settings.py b/webapp/autoDeploy/autoDeploy/settings.py index 7340984..e27e747 100644 --- a/webapp/autoDeploy/autoDeploy/settings.py +++ b/webapp/autoDeploy/autoDeploy/settings.py @@ -67,6 +67,7 @@ 'django.contrib.auth.context_processors.auth', 'django.core.context_processors.static', 'django.contrib.messages.context_processors.messages', + 'autoDeploy.processor.global_settings' ], }, }, diff --git a/webapp/autoDeploy/autoDeploy/wsgi.py b/webapp/autoDeploy/autoDeploy/wsgi.py index d66a2c4..3b136b6 100644 --- a/webapp/autoDeploy/autoDeploy/wsgi.py +++ b/webapp/autoDeploy/autoDeploy/wsgi.py @@ -11,6 +11,6 @@ from django.core.wsgi import get_wsgi_application -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "autoDeploy.settings") +os.environ["DJANGO_SETTINGS_MODULE"]= "autoDeploy.settings" application = get_wsgi_application() diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 22e1f7f..738e0fe 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -50,10 +50,10 @@ Projects @@ -61,15 +61,15 @@
  • Servers
  • SSH Keys
  • From e4ee96cf2a384bf2648c6eca25eca3c62ee9deac Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Fri, 15 May 2015 16:53:29 +0300 Subject: [PATCH 014/108] Update README.md --- README.md | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9a4faa0..6a2b9da 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ The project will have the following componemts: * **Deployment Client** (which can communicate with the server giving it the scripts to run). * **Deployment Interface** (to see the progress and it can be used to deploy certain code versions). -The deployment configuration will be based on YAML Format, the multiple values can be seprated by ','. +The deployment configuration will be based on YAML Format. The client should be callable from CI systems (like Jenkins) to deploy the code after a successful build. @@ -26,8 +26,15 @@ Every event should have the following format: ```yaml events: event-name - location: script-location (can be seprated by ',') - runas: user-name + - location: script-location + runas: user-name ``` ## Requirments ## +### For the Server: * pyyaml (>3.0) +* pycrypto + +### For the web-application +* django 1.8.1+ +* django-table-2 +* django-table-report From 681ea8352a477b45b10af2779e316882c14164cb Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Fri, 15 May 2015 18:03:31 +0300 Subject: [PATCH 015/108] Closes #20 --- webapp/autoDeploy/autoDeploy/urls.py | 3 +++ webapp/autoDeploy/autodeploy/api.py | 17 ++++++++++++++ webapp/autoDeploy/autodeploy/views.py | 15 ++++--------- webapp/autoDeploy/static/img/loading.gif | Bin 0 -> 6494 bytes webapp/autoDeploy/static/js/functions.js | 22 ++++++++++++++++++ webapp/autoDeploy/templates/base.html | 27 +++++++++++++++++++++-- 6 files changed, 71 insertions(+), 13 deletions(-) create mode 100644 webapp/autoDeploy/autodeploy/api.py create mode 100644 webapp/autoDeploy/static/img/loading.gif create mode 100644 webapp/autoDeploy/static/js/functions.js diff --git a/webapp/autoDeploy/autoDeploy/urls.py b/webapp/autoDeploy/autoDeploy/urls.py index bf2dc44..811cb80 100644 --- a/webapp/autoDeploy/autoDeploy/urls.py +++ b/webapp/autoDeploy/autoDeploy/urls.py @@ -33,4 +33,7 @@ url(r'checkServers/','autodeploy.views.checkServersStatus'), url(r'listCommits/','autodeploy.views.listCommits'), + + url(r'api/checkServers','autodeploy.api.checkServers') + ] diff --git a/webapp/autoDeploy/autodeploy/api.py b/webapp/autoDeploy/autodeploy/api.py new file mode 100644 index 0000000..cb55740 --- /dev/null +++ b/webapp/autoDeploy/autodeploy/api.py @@ -0,0 +1,17 @@ +__author__ = 'mohamed' +from models import * +import simplejson +from client.Client import Client +from django.http import HttpResponse + +def checkServers(request): + res = {} + for server in Server.objects.all(): + c = Client("git", server.ip, server.port) + state = c.CheckUp() + #d = {"name": server.name} + if state: + res[server.name] = "UP" + else: + res[server.name] = "DOWN" + return HttpResponse(simplejson.dumps(res)) \ No newline at end of file diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index ed08059..3bea6dd 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -162,19 +162,12 @@ def confirm_delete(request): return manage_ssh_keys(request) + + def checkServersStatus(request): - res = [] - for server in Server.objects.all(): - c = Client("git", server.ip, server.port) - state = c.CheckUp() - d = {"name": server.name} - if state: - d["state"] = "UP" - else: - d["state"] = "DOWN" - res.append(d) + # print res - return render_to_response("servers_status.html", {"servers": res}, context_instance=RequestContext(request)) + return render_to_response("base.html", {"title":"Servers Health","function":"checkServers","data":"","ajax": True}, context_instance=RequestContext(request)) def listCommits(request): diff --git a/webapp/autoDeploy/static/img/loading.gif b/webapp/autoDeploy/static/img/loading.gif new file mode 100644 index 0000000000000000000000000000000000000000..1bff25aef8697b312d427c7c0d0ea80330687813 GIT binary patch literal 6494 zcma)>cT^Mk`o`mA3QhuqDhNVAM7n^BAic-}3JTJTN|n$Pnt%aA=tZg^NK~41LJ$z7 zEul$oVnIQ{g0i5XtLW~!>yO?2-E+P7a!byc`D@Oc^M2-epYQX&F){mI-mxU`S+e|-A7m6u7Cdd>AMfji?1ZU;*J~JSQ{Bw8mlTPV|QRM7>VC^8wGp0 zg?f1s&-sLsh;F`a5&l7Lo=QG}XM->jKZ85bt)~>WuB}(AVldcWIojucR~|8|?b2A? z2g*AS;rk5ni848&?X({U;VqA*pL&}AYSImpFP`Y zm-i4JMLx`R_psVL&2_>Co1^+S88h!P30l@d29eTxLZVTcD+WdYfHv_KT+klm`jrZm0%=1C1`$@3dA&cx|vIZ1;RJAYH-YUUob!9Skdsr z#}-I3}0A~5@b0CSk#`}oS--7uExpSq9qbuw8A)C3EtCcn@pO!zoe)IXg zS{9Ody2lCTZr>}EQPP`4*n5;=+E{Arw{wfuzw-F{cOK7sC)^knd$5gvA}Ofvl`Kbv zfmRWLDswEopqEHmkvjNXpCm-(XU|VJMosX`^AWZ3HsX)Hrde~SattyvLlkjlD{=a@ z%sfoja?)pT=+`jk;}NoCePcC%7OO1_OM@!5DKzM$$-&FPq8GfyVx>ZfF{wECg3l=n zLoTlqP&QH>rbF-qgTc$bW?HvT=7;6-kcgSreQWulJ7T0J6PXSPQO}yx$^dH{?a<<{73dreEA>eKYcDEjVn+}HlnbS`6NG}3b0>w?-^H2!~FYTlD#TZ!3!--e47-oPs4wyH4 zBJL0ap?HMwdDnEcngJJ>H*b_W?6cs#;&}y39n|B8?#_}2gvr&&m?Ne-Zq$6HI<1ZXks4$+--%O8Wk$l|R|k6>Q7ooBsJr zFT&VHj$U_;M27@@6)M^;3alBHJ68T6!s)8f9FCt^Jf!i+9T4v+Gdk{_dYYi`>Q#1M z$wPT@h<1W8m#gg#Vu|Xf<+0ZQrw10wsf)p6MbP4$th_Yjk4B%|O>+#D5Yz4Etd80+I$blI_p;cVW8#t&DZmAAE(1=2Chuyg!_$B(mz(IyU zM^#sMFkdIJ4<5fTG(7jH^X{%m-o;1H<`45#zBZ)~4n8KVeOTMr_3`7UU%&kJ`&SGW z6*XlQv*S4anMuO`&_5j0t{xoMgE`VDLJ|YA31o#kb%Z;Q4Lx>p$mDWbI`eb1?&Y8SIU{|=o)1xhvMRYp?Mfi__?R77u%JuZ;XJLm6DzVI4>gt64Vz1g7E4;g>z>?kzxokpnS=m#IAxp>f5y_GSrj%~SsVk48}Hh)r@|*K zr1WFeAWLP?>b$FPkQsbIMO;lzG!i`@%?G;%dE1AJ7o8M8bGcL)8*<>Pi5_=;0Um1N zKUVD!PFCjks=VARkWd|ayO7Y`G{~#c=S3VIx!H~Gtxgjh-UU{N*c_z@Pd6aIJUP*p zDED$+^}$M~&ocSR#xA3^`PZAfR;!s`-rmD)FO&bb6{ze^-1dT5`Mcq+8V~(`j3UIS zX>yv`# zfrCi~52U4~cec?tZ8SV)7W!Hp6BGrGON0?447C&wh^fjQ*AEL9h{YvXNyW$oJ7&ZQ z+4y=V*eG!q9%Tq0!k*0aJt~+f4`ORHqOy1^iIPnwOiR8T6`-m02TrKT*WtjaK_0Mg z*yzLrzsq#ZJ>g)@M^7dm4nKSTtju!h#Y)ri(>HI|H{QMf>BGm(PoIDO<=X}_K(?>` zr*EqF8r!Nq0yT*Le#hx&)j~>^S@Kdd(!0*3J0&GyUoFN_sH!ixT?tu%2Of;sSKUuf zD_&pheb0Y?w*is5(I2^$Kp4yh2+MFW^=aVqDQfd!(1>8Ef`l_0NuG`3nR8vc_acXm|#Vl}N#bvIRsx#h^Jf|xI&Mjv;sLfs) z6`g1Pgv@P@t~S3JZGOM3#*+Le8=W||Es3}PNP@8>yN8rIPqKqbc7NaQq{x%;a*S8S zvRF5dIqgpHM}^EZT!gqx#ShGls)my;{BPirp)D(yQ~B z0kW}HOAIz5w_I{`wD)Fz?|A;&Cgw@!m+vcf{QW>NmDsVJS$_Ej!MMjtu{E{CPDn~Q zzsOBNzUZot!uj=Qy(_;7#WT>m;h+Woz*zBIwXHch;@QhFZk4 z7^@E?PLK5ca`9}&%MWE#3kBXq(_kPtnx^3l#3c%NoJz|SbUvT!l7)hCmk=N$Unn(A z{{lCN1<2=8D!3smHd3(&r~tgU5G-Po5|`l22{TDnnoSM(rm{q+?Y4M8ZCXLa;U;nB zRb9BL1vl?8O>07A+km}H*1mqsJlfWN?M;O^8~gsJO0;Q?wk&nyL*%1Dj7T@U!KKQo zoUl~(LdU;L|1*Pq=G|5k@4p4o@wM1C-c=>%YGi5NaGSqh9Y*v-f}6so;!7>#$^GR! z()!_80{=vo*{k5NbWL>ByWS^2=;n8;%Ia_AI1p)dZ#(LAQuD3fqVDVrHC3BD*Yli4 zak0A)OOF zuNxL?1zrIRvTVwaz&$ybM&;Ui^~>^&Y6DkVBsB3eBXyY0fJgAa(v4G(F!vr0n=RMA zxWc$Nu~2lki<(ux^!{wwhZX8lPS>hYx~Qc3JeOu{L+1@PI{t<(#OopehV1-?s z&#lro9|w6l$C^Ea4$)q4^D{w9$mDokRlT&VEjx7WZmLqX(E6;_%DR zveCD`9&ZjgMK>;^_QS4O&&0R@B#OG%{X#5a6eo27u|MR_1H?;O>C%88%z2dvAXX+Q zR}sFRg3_EA`{06*Ej{Fy?W2K*Sac{BUn`Yb)yM`hoy{t@Q5XwgM#sBlhtXV5R{tGo zuyl^Ct2Ug4kdyRKxV|;AhFR6GW$5ep?KGGNl@)Jh;*5+AC#MDI=9I_EdGZ8lmo?JiBcq zs@2AP$<^}kC{LfhYcMZI64p&sD7|jubKb86{AW?}dAuDjhz*gj#y}u|&@BA+UyM@A z#)L`3Nao>;Yy?Y^U}TnOAnDvmHIh;I>hw%5C|A<@CMGGQIS3O|Al426{=PLan9>xf z_R+GAlO^5jHDyS;NgmbC-WJ6_ctpq7KeX@{iq&qi0(M}HKO#Ur@`t-R3*4WI z1n@(iCxSTAK(V8$Ygy+*`?5^6sk!FETB_u2)W$u~z5A969ZR`^!W|eJwGm9~tTT~{zgI!VJP22VF11a~G&~4w z2wakY?p`^!I6e0e+b|ClK7F`ndN}=|8NsqH_$KSg|9UR zW~VP1LfAaq@Sf4o(VR&}%i632RGZM%-M_ScJk$#LWpx}kO>1%PpJE z`~lZ^srS}c(ZDtI%IO}q$>5yVExo3&0j5Zqe^bYOv-4(N64NtJyqey%OG1;2xY>KS zX0l&!&y4y}EbU{Ci9(T@m5pZs{Z?7&0J^<%{#)btn>Zr4_>WM;<6;+Gi-l?IVw&Zp zcc7V9&{?8>SyJ^{gsm7=h;_DYQ38oS=GG-^Dgwnh+&t^|qbYm-L@Tw{Hk|Y3kD5nJAR*?kH~C)Y=vgSk%@_XfO25 z)DJ%Fl+<>gf4G4RqrXYG)rx39?RHb|TlE+712rX&&Sq_E91H)gPa?PoM(baDt{3;? zcE=iBUELay{DJGmW(P$}Pxdy25f#vQzn~7eBT!v}6npE_FS~Yb7pGqSr;7Vv%9y?ZhtZi%s4w<`2nUCvMB{!9p%}S^ zo9Br7wu#l#sFw0oyivAkXEyx-i!%PakaF-bAD4p|XWNzE3hZom85rp*LIDwYgZRTn z7SRe2ayH93Lq^Xi$kCYy<>3zLX$4`lfNO$R(U592jH79}MRL-fYG#S4VF_Ycy7v}| zX_^(071S+p3r?ypXK6JLiQQt3O?IZ0fz2(J?B1G(OcQVWr{n#&?8@Cfqqy;j4cGl4 zH7w>ctIhXIYclJvIYg5sw+)hS{!Qg|Btn3VXrE<2mld~iw@}B{Xh4_+TbI^Iq)vx+ zCvHpPl<#mZTY~`Lk+&2lIk8-Kc1em87wA9Ww(u+`3FDXFDDe4f%xT4F+68(U`MXjcOO1`UFpKaHUM%?AE`$a+KCxL% ztrdT{+-1G~UXOCE<)Kl7Soeh#Ub*z`kIB`4B{0mtEKQJ=#vA%|HJVRvavp?>4r&-L zDGL?H(1R57dxYnz|Lh zwjVAtlzd1^YE&9ajLamxIKCpeJXf*Ohk11;a;^XEMB2OeGYh!Q2W_vPZwB)8_^kk% zum4ESNfq0tgKyT_eh#K{#3T44B-LJ5g{QYU`&5}qXYswj-IlPd)Tbp$X3;21aM4mS zn4D_Em$h3{ylhEvm#9NS##1@tTDpXCPqMtHP=vkb+fP37C=#o`GWMkUw5lvXKJKXy zg~D;x-adE}JpiG)I&(p`c~F9q-bGby1{it%NFg>auskXkyeh4(Lb#C&*QkX%GxgG0lUf_SZZ}>&eWYD=E7oK1k zNB6vVt@CP~yfORBPp!nIQTxfO+JX>5|M}B#H&HT|xY!GVisL}apKI-GzzM);{qe8I HpTGYD^XReF literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/js/functions.js b/webapp/autoDeploy/static/js/functions.js new file mode 100644 index 0000000..dd531f4 --- /dev/null +++ b/webapp/autoDeploy/static/js/functions.js @@ -0,0 +1,22 @@ +/** + * Created by mohamed on 15/05/15. + */ + +function checkServers(servers) +{ + html='
    ' + html+='' + for (server in servers) { + + html += "" + + if (servers[server] == "UP") + html += '' + else + html += '' + + html += "" + } + html+='
    SeverStatus
    " + server + "
    OK
    Offline
    ' + $("#content").html(html) + } diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 738e0fe..57d4ef5 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -6,6 +6,7 @@ autoDeploy + @@ -15,6 +16,17 @@ {% block head %} {% endblock %} + + {% if ajax %} + + {% endif %} @@ -82,8 +94,19 @@
    {% block content %}
    -
    {{ text }}
    -{% endblock %} +
    +

    {{ title }}

    + {% if ajax %} +
    + +
    +
    + Please wait while your request is processed..... +
    + {% else %} +
    {{ text }}
    + {% endif %} + {% endblock %}
    From 4a9b3d4c1c2207e892ce89ea904e91d191a40594 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 16 May 2015 10:48:49 +0300 Subject: [PATCH 016/108] Closes #22 --- webapp/autoDeploy/autoDeploy/urls.py | 3 ++- webapp/autoDeploy/autodeploy/api.py | 14 ++++++++++++-- webapp/autoDeploy/autodeploy/views.py | 13 ++++++------- webapp/autoDeploy/static/js/functions.js | 13 +++++++++++++ webapp/autoDeploy/templates/base.html | 4 ++-- 5 files changed, 35 insertions(+), 12 deletions(-) diff --git a/webapp/autoDeploy/autoDeploy/urls.py b/webapp/autoDeploy/autoDeploy/urls.py index 811cb80..ea0a617 100644 --- a/webapp/autoDeploy/autoDeploy/urls.py +++ b/webapp/autoDeploy/autoDeploy/urls.py @@ -34,6 +34,7 @@ url(r'listCommits/','autodeploy.views.listCommits'), - url(r'api/checkServers','autodeploy.api.checkServers') + url(r'api/checkServers','autodeploy.api.checkServers'), + url(r'api/clone','autodeploy.api.clone'), ] diff --git a/webapp/autoDeploy/autodeploy/api.py b/webapp/autoDeploy/autodeploy/api.py index cb55740..65eb374 100644 --- a/webapp/autoDeploy/autodeploy/api.py +++ b/webapp/autoDeploy/autodeploy/api.py @@ -3,15 +3,25 @@ import simplejson from client.Client import Client from django.http import HttpResponse +from django.views.decorators.csrf import csrf_protect def checkServers(request): res = {} for server in Server.objects.all(): c = Client("git", server.ip, server.port) state = c.CheckUp() - #d = {"name": server.name} if state: res[server.name] = "UP" else: res[server.name] = "DOWN" - return HttpResponse(simplejson.dumps(res)) \ No newline at end of file + return HttpResponse(simplejson.dumps(res)) + +@csrf_protect +def clone(request): + scm = str(request.GET["scm"]) + ip = str(request.GET["ip"]) + port = int(request.GET["port"]) + project=Project.objects.get(name=request.GET["project_name"]) + c = Client(scm,ip,port) + res = c.Clone(project.repo, project.working_dir, project.sshKey.key) + return HttpResponse(res) \ No newline at end of file diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 3bea6dd..80d2865 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -9,7 +9,7 @@ from django_tables2.config import RequestConfig from client.Client import Client from django.shortcuts import redirect - +from django.template.context_processors import csrf def projects(request): name = "Projects" @@ -78,11 +78,10 @@ def clone(request): form = CloneForm(request.POST) if form.is_valid(): server = Server.objects.get(name=form.cleaned_data["server"]) - c = Client("git", server.ip, server.port) - res = c.Clone(project.repo, project.working_dir, project.sshKey.key) - print res - return render_to_response("clone.html", {"form": form, "result": res}, - context_instance=RequestContext(request)) + token=csrf(request).get("csrf_token") + data="{scm: '%s', ip: '%s', port: '%s', project_name: '%s',csrfmiddlewaretoken: '%s' }" % (project.repo_type,server.ip,server.port,project.name,token) + return render_to_response("base.html", {"ajax":True, "data": data, "dataType":"html", + "title":"Cloning "+ project.name, "function":"clone"}, context_instance=RequestContext(request)) @csrf_protect @@ -167,7 +166,7 @@ def confirm_delete(request): def checkServersStatus(request): # print res - return render_to_response("base.html", {"title":"Servers Health","function":"checkServers","data":"","ajax": True}, context_instance=RequestContext(request)) + return render_to_response("base.html", {"title":"Servers Health","function":"checkServers","dataType":"JSON","data":"","ajax": True}, context_instance=RequestContext(request)) def listCommits(request): diff --git a/webapp/autoDeploy/static/js/functions.js b/webapp/autoDeploy/static/js/functions.js index dd531f4..978a5af 100644 --- a/webapp/autoDeploy/static/js/functions.js +++ b/webapp/autoDeploy/static/js/functions.js @@ -20,3 +20,16 @@ function checkServers(servers) html+='' $("#content").html(html) } + + +function clone(data) { + html="" + console.log(data) + if (data == "Done") + html = "
    Cloning is succesful
    " + else + html = "
    " + data + "
    " + + + $("#content").html(html) +} \ No newline at end of file diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 57d4ef5..601528a 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -19,10 +19,10 @@ {% if ajax %} From 971f6e7c10d0c5f723c73f10d1120bf97f88cf30 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 16 May 2015 11:59:32 +0300 Subject: [PATCH 017/108] Closes # 21 --- client/Client/Client.py | 7 +++++-- exampleConfig/autodeploy.yaml | 18 ++++++++++++++++++ server/deployer/autodeployer.py | 11 ++++++++--- webapp/autoDeploy/autoDeploy/urls.py | 1 + webapp/autoDeploy/autodeploy/api.py | 18 +++++++++++++++++- webapp/autoDeploy/autodeploy/views.py | 15 +++++++-------- webapp/autoDeploy/static/js/functions.js | 19 +++++++++++++++++-- webapp/autoDeploy/templates/base.html | 2 +- webapp/autoDeploy/templates/deploy.html | 1 + 9 files changed, 75 insertions(+), 17 deletions(-) create mode 100644 exampleConfig/autodeploy.yaml diff --git a/client/Client/Client.py b/client/Client/Client.py index 6ade022..877be16 100644 --- a/client/Client/Client.py +++ b/client/Client/Client.py @@ -78,8 +78,11 @@ def ListCommits(self, workdir, page=0, rpp=10, owner=''): # if HEAD: # info[0] = "HEAD" # HEAD = False - d = {"Hash": info[0], "Short": info[1], "Author": info[2], "Committed": info[3], "Message": info[4]} - result.append(d) + try: + d = {"Hash": info[0], "Short": info[1], "Author": info[2], "Committed": info[3], "Message": info[4]} + result.append(d) + except: + print "Error while parsing line (%s)"%line print result return result diff --git a/exampleConfig/autodeploy.yaml b/exampleConfig/autodeploy.yaml new file mode 100644 index 0000000..4d37de5 --- /dev/null +++ b/exampleConfig/autodeploy.yaml @@ -0,0 +1,18 @@ +files: + - source: /webapp/autoDeploy/* + destination: /var/www/autodeploy/ + +permissions: + - object: /var/www/autodeploy/ + owner: mohamed + group: users + mode: 755 + type: directory + +events: + beforeInstall: + - location: "/bin/rm -r /var/www/autodeploy" + afterInstall: + - location: "/var/www/autodeploy/manage.py runserver 0.0.0.0:9002" + interpreter: python + wait: False diff --git a/server/deployer/autodeployer.py b/server/deployer/autodeployer.py index 22eeb3f..db8ce8a 100644 --- a/server/deployer/autodeployer.py +++ b/server/deployer/autodeployer.py @@ -19,7 +19,10 @@ def runEvents(config,workdir,event,raiseErrorOnStdErr=True): if event in config["events"].keys(): for script in config["events"][event]: wait=True - cmd=workdir+script["location"] + if not script["location"].startswith("/"): + cmd=workdir+script["location"] + else: + cmd=script["location"] if "interpreter" in script.keys(): cmd="%s %s"%(script["interpreter"],cmd) if "run-as" in script.keys(): @@ -35,8 +38,10 @@ def handleFiles(files,workdir): if file["destination"].endswith("/") and not file["source"].endswith("/"): if not os.path.exists(file["destination"]): os.makedirs(file["destination"]) - if file["source"].endswith("/"): - Common.run("sudo rsync -rz --delete --exclude='.git' %s %s"%(workdir+file["source"],file["destination"])) + #if file["source"].endswith("/"): + rsyn_cmd="sudo rsync -rz --delete --exclude='.git' %s %s"%(workdir+file["source"],file["destination"]) + print " %s"%rsyn_cmd + Common.run(rsyn_cmd) def handlePermissions(permissions,raiseErrorOnStdErr): for permission in permissions: diff --git a/webapp/autoDeploy/autoDeploy/urls.py b/webapp/autoDeploy/autoDeploy/urls.py index ea0a617..6fb1c2a 100644 --- a/webapp/autoDeploy/autoDeploy/urls.py +++ b/webapp/autoDeploy/autoDeploy/urls.py @@ -36,5 +36,6 @@ url(r'api/checkServers','autodeploy.api.checkServers'), url(r'api/clone','autodeploy.api.clone'), + url(r'api/deploy','autodeploy.api.deploy'), ] diff --git a/webapp/autoDeploy/autodeploy/api.py b/webapp/autoDeploy/autodeploy/api.py index 65eb374..1297306 100644 --- a/webapp/autoDeploy/autodeploy/api.py +++ b/webapp/autoDeploy/autodeploy/api.py @@ -24,4 +24,20 @@ def clone(request): project=Project.objects.get(name=request.GET["project_name"]) c = Client(scm,ip,port) res = c.Clone(project.repo, project.working_dir, project.sshKey.key) - return HttpResponse(res) \ No newline at end of file + return HttpResponse(res) + +@csrf_protect +def deploy(request): + server = Server.objects.get(name=request.session["deploy_server"]) + c = Client("git", server.ip, server.port) + project = Project.objects.get(name=request.session["deploy_project"]) + if "tag" in request.GET: + res = c.SwitchTag(project.working_dir, request.GET["tag"]) + elif "commit" in request.GET: + if request.GET["commit"]!="HEAD": + res=c.SwitchCommit(project.working_dir,request.GET["commit"]) + res = c.Deploy(project.working_dir, project.configFile) + if not "http://" in project.deployment_link: + return HttpResponse(res+",,http://"+server.DNS+project.deployment_link) + else: + return HttpResponse(res+",,"+project.deployment_link) diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 80d2865..5d38562 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -111,16 +111,15 @@ def listTags(request, server): def deploy3(request): if request.method == "GET": - server = Server.objects.get(name=request.session["deploy_server"]) - c = Client("git", server.ip, server.port) - project = Project.objects.get(name=request.session["deploy_project"]) + token=csrf(request).get("csrf_token") if "tag" in request.GET: - res = c.SwitchTag(project.working_dir, request.GET["tag"]) + data='{tag:"%s",csrfmiddlewaretoken:"%s"}'%(request.GET["tag"],token) elif "commit" in request.GET: - if request.GET["commit"]!="HEAD": - res=c.SwitchCommit(project.working_dir,request.GET["commit"]) - res = c.Deploy(project.working_dir, project.configFile) - return render_to_response("deploy2.html", {"result": res}, context_instance=RequestContext(request)) + data='{"commit":"%s",csrfmiddlewaretoken:"%s"}'%(request.GET["commit"],token) + + project=Project.objects.get(name=request.session["deploy_project"]) + server=Server.objects.get(name=request.session["deploy_server"]) + return render_to_response("base.html", {"ajax": True,"data":data,"dataType":"html","function":"deploy","title":"Deploying %s on %s"%(project.name,server.name)}, context_instance=RequestContext(request)) def edit_ssh_key(request, sshKey): diff --git a/webapp/autoDeploy/static/js/functions.js b/webapp/autoDeploy/static/js/functions.js index 978a5af..8d1379b 100644 --- a/webapp/autoDeploy/static/js/functions.js +++ b/webapp/autoDeploy/static/js/functions.js @@ -22,14 +22,29 @@ function checkServers(servers) } -function clone(data) { +function renderResult(data,success) { html="" console.log(data) if (data == "Done") - html = "
    Cloning is succesful
    " + html = "
    "+success+"
    " else html = "
    " + data + "
    " $("#content").html(html) +} + +function clone(data) +{ + renderResult(data,"Cloning is successful") +} +function deploy(data) +{ + if (data.indexOf("Done")>-1) + { + res = data.split(",,") + renderResult(res[0], "Deployment was successful. Visit " + res[1] + "") + } + else + renderResult(data,"Done.") } \ No newline at end of file diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 601528a..074b572 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -56,7 +56,7 @@ From f95b4171cc747c0f650577add2f581b1d37a101e Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Tue, 19 May 2015 19:35:49 +0300 Subject: [PATCH 029/108] Closes #7 --- webapp/autoDeploy/autodeploy/forms.py | 6 +++++- webapp/autoDeploy/autodeploy/models.py | 17 ++++++++++------- webapp/autoDeploy/autodeploy/views.py | 12 +++++++++--- webapp/checkUpdates.py | 1 + 4 files changed, 25 insertions(+), 11 deletions(-) create mode 100644 webapp/checkUpdates.py diff --git a/webapp/autoDeploy/autodeploy/forms.py b/webapp/autoDeploy/autodeploy/forms.py index f195c33..822a29c 100644 --- a/webapp/autoDeploy/autodeploy/forms.py +++ b/webapp/autoDeploy/autodeploy/forms.py @@ -4,6 +4,7 @@ import os import autoDeploy.settings as settings repo_type=[('git','git')] +update_style=[('commit',"commits"),("tag","tags")] def saveFile(file,project_name): if file=='': print "No File to save." @@ -19,6 +20,7 @@ def saveFile(file,project_name): class ProjectsForm(forms.ModelForm): working_dir=forms.CharField(label="Working Directory",widget=forms.TextInput(attrs={'class':'form-control','size':30})) repo_type=forms.ChoiceField(choices=repo_type,label="Repo Type") + update_style=forms.ChoiceField(choices=update_style,label="Update Style") cfile=forms.FileField(label="Config File") name = forms.CharField(label='Project Name',widget=forms.TextInput(attrs={'class':'form-control','size':30})) repo_link= forms.CharField(label='Repo Link',widget=forms.TextInput(attrs={'class':'form-control','size':30})) @@ -39,12 +41,14 @@ def save(self,files,name): P.repo_type=self.cleaned_data["repo_type"] P.working_dir=self.cleaned_data["working_dir"] P.sshKey=self.cleaned_data["sshKey"] + P.default_server=self.cleaned_data["default_server"] + P.update_style=self.cleaned_data["update_style"] print "Files is ",files P.configFile = saveFile(files.get('cfile',''),name) P.save() class Meta: model= models.Project - fields=("name","repo","repo_link","working_dir","repo_type","sshKey","deployment_link","cfile") + fields=("name","repo","repo_link","working_dir","update_style","default_server","repo_type","sshKey","deployment_link","cfile") class ServerForm(forms.ModelForm): ip=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','size':30}),label="Hostname/IP") diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index 5b28c74..adc2275 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -15,11 +15,21 @@ class working_directory(models.Model): def __unicode__(self): return self.name +class Server(models.Model): + name=models.CharField(max_length=50,primary_key=True) + ip=models.CharField(max_length=50) + port=models.IntegerField(default=4567) + DNS=models.CharField(max_length=50,blank=True) + def __unicode__(self): + return self.name + class Project(models.Model): name = models.CharField(max_length=50, blank=False,primary_key=True) repo_type=models.CharField(max_length=10,blank=True) repo = models.CharField(max_length=255, blank=True) + default_server=models.ForeignKey(Server,blank=True) + update_style=models.CharField(max_length=10,blank=True) lastCommit = models.CharField(max_length=32,blank=True) lastTag=models.CharField(max_length=255,blank=True) lastCommitDate = models.DateTimeField(blank=True,default="1970-01-01") @@ -34,13 +44,6 @@ def __unicode__(self): return self.name -class Server(models.Model): - name=models.CharField(max_length=50,primary_key=True) - ip=models.CharField(max_length=50) - port=models.IntegerField(default=4567) - DNS=models.CharField(max_length=50,blank=True) - def __unicode__(self): - return self.name class Deployment_Server(models.Model): datetime = models.DateTimeField() diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 13c2e9c..06514af 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -40,6 +40,8 @@ def add_project(request): project.repo_link=request.POST["repo_link"] project.sshKey=SSHKey.objects.get(name=request.POST["sshKey"]) project.working_dir=request.POST["working_dir"] + project.default_server=form.cleaned_data["default_server"] + project.update_style=form.cleaned_data["update_style"] if request.FILES.get("cfile","")!="": project.configFile=saveFile(request.FILES["cfile"],project.name) project.save() @@ -132,11 +134,15 @@ def deploy2(request): @login_required(redirect_field_name="redirect") def listTags(request, server): project = Project.objects.get(name=request.session["deploy_project"]) - c = Client("git", server.ip, server.port,key=project.sshKey.key) + c = Client(str(project.repo_type), server.ip, server.port,key=project.sshKey.key) res = c.ListTags(project.working_dir) - - return render_to_response("deploy2.html", {"mode":"tags","tags": res }, context_instance=RequestContext(request)) + print res + table=TagTable(res) + table_to_report = RequestConfig(request, paginate={"per_page": 15}).configure(table) + if table_to_report: + return create_report_http_response(table_to_report, request) + return render_to_response("deploy2.html", {"count":len(res),"mode":"tags","tags":table}, context_instance=RequestContext(request)) @login_required(redirect_field_name="redirect") def deploy3(request): diff --git a/webapp/checkUpdates.py b/webapp/checkUpdates.py new file mode 100644 index 0000000..91ba68b --- /dev/null +++ b/webapp/checkUpdates.py @@ -0,0 +1 @@ +__author__ = 'mohamed' From af72dbe7e52b9646aa19d734a6985cb37bc3ad35 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Tue, 19 May 2015 20:42:31 +0300 Subject: [PATCH 030/108] closes #4 --- client/autodeploy_client/Client.py | 22 +++++++++--- server/autodeploy-server.py | 22 ++++++++++++ server/scm/Git.py | 2 +- webapp/autoDeploy/autodeploy/api.py | 12 +++++-- .../migrations/0010_auto_20150519_1806.py | 36 +++++++++++++++++++ .../migrations/0011_auto_20150519_1811.py | 25 +++++++++++++ .../migrations/0012_auto_20150519_1943.py | 25 +++++++++++++ webapp/autoDeploy/autodeploy/models.py | 1 + webapp/autoDeploy/autodeploy/tables.py | 13 ++++++- webapp/autoDeploy/checkUpdates.py | 33 +++++++++++++++++ webapp/autoDeploy/static/css/autodeploy.css | 26 ++++++++++++++ webapp/autoDeploy/templates/base.html | 2 +- webapp/autoDeploy/templates/clone.html | 1 + webapp/autoDeploy/templates/deploy2.html | 14 ++------ webapp/checkUpdates.py | 1 - 15 files changed, 214 insertions(+), 21 deletions(-) create mode 100644 webapp/autoDeploy/autodeploy/migrations/0010_auto_20150519_1806.py create mode 100644 webapp/autoDeploy/autodeploy/migrations/0011_auto_20150519_1811.py create mode 100644 webapp/autoDeploy/autodeploy/migrations/0012_auto_20150519_1943.py create mode 100644 webapp/autoDeploy/checkUpdates.py delete mode 100644 webapp/checkUpdates.py diff --git a/client/autodeploy_client/Client.py b/client/autodeploy_client/Client.py index 9bfa591..000c4eb 100644 --- a/client/autodeploy_client/Client.py +++ b/client/autodeploy_client/Client.py @@ -3,7 +3,8 @@ import Connect import simplejson import xml.dom.minidom - +from operator import itemgetter +import datetime class Client: scm = "" @@ -46,8 +47,18 @@ def ListTags(self, workdir, owner=''): msg = Job.createListTagsMessage(workdir=workdir, scm=self.scm, key=self.sshkey, owner=owner) result = self._send(msg) if result == "Done": return [] - return result.split("\n") - + #print result + res=[] + for line in result.split("\n"): + if line=="": continue + info=line.split(",,") + Date=datetime.datetime.strptime(info[2][:-6],"%a %b %d %H:%M:%S %Y").strftime("%Y-%m-%d %H:%M:%S") + res.append({"Tag":info[0],"Tagger":info[1],"Date":Date,"Commit":info[3]}) + if len(res)>0: + newlist = sorted(res, key=itemgetter('Date'), reverse=True) + return newlist + else: + return [] def SwitchTag(self, workdir, tag, owner=''): global msg if owner == '': @@ -75,17 +86,20 @@ def ListCommits(self, workdir, page=0, rpp=10, owner=''): result = [] #HEAD = True for line in res.split("\n")[1:]: + if line=="": continue info = line.split(",,") # print line # if HEAD: # info[0] = "HEAD" # HEAD = False try: + d = {"Hash": info[0], "Short": info[1], "Author": info[2], "Committed": info[3], "Message": info[4]} result.append(d) + except: print "Error while parsing line (%s)"%line - print result + #print result return result def SwitchCommit(self, workdir, commit, owner=''): diff --git a/server/autodeploy-server.py b/server/autodeploy-server.py index 57fd8f2..17b7a3b 100755 --- a/server/autodeploy-server.py +++ b/server/autodeploy-server.py @@ -81,6 +81,28 @@ def HandleClient(clientsock): gclient=git.GIT(workdir=job["workdir"]) gclient.setKey(job["key"]) cmd=gclient.get_list_tags_cmd() + result=[] + res=Common.run(cmd) + if "ERR:" in res: + Response.sendData(clientsock,res) + else: + for line in res.split("\n"): + try: + cmd="cd %s; git show %s"%(job["workdir"],line) + res=Common.run(cmd) + lines=res.split("diff --git ")[0] + info=lines.split("\n") + #print info + tag=info[0][4:] + tagger=info[1].split(": ")[1].split("<")[0].strip() + date=info[2].split(": ")[1].strip() + commit=info[6].split("commit ")[1] + result.append(",,".join([tag,tagger,date,commit])) + except: + pass + Response.sendData(clientsock,"\n".join(result)) + return + elif req["requestType"]=="LIST-COMMITS": job = Request.parseGetCommitsJob(msg) if job["scm"]=="git": diff --git a/server/scm/Git.py b/server/scm/Git.py index 64e4333..9716658 100644 --- a/server/scm/Git.py +++ b/server/scm/Git.py @@ -25,7 +25,7 @@ def get_list_tags_cmd(self): def get_switch_to_tag_cmd(self,tag): return "cd %s; git checkout tags/%s"%(self.workdir,tag) def get_history_cmd(self): - return self.get_pull_cmd()+'; git log --all --pretty=format:"%H,,%h,,%an,,%ar,,%s" | cat -' + return self.get_pull_cmd()+'; git log --all --pretty=format:"%H,,%h,,%an,,%ar,,%s,,%cd" | cat -' def switch_to_histroy_cmd(self,commit): return 'cd %s; git reset --hard %s'%(self.workdir,commit) def commit_diff_cmd(self,commit): diff --git a/webapp/autoDeploy/autodeploy/api.py b/webapp/autoDeploy/autodeploy/api.py index 1df3641..36d7e1a 100644 --- a/webapp/autoDeploy/autodeploy/api.py +++ b/webapp/autoDeploy/autodeploy/api.py @@ -38,20 +38,28 @@ def deploy(request): res = c.SwitchTag(project.working_dir, request.GET["tag"]) D.update_type="tag" D.update_version=request.GET["tag"] + project.lastTag=request.GET["tag"] elif "commit" in request.GET: if request.GET["commit"] != "HEAD": res=c.SwitchCommit(project.working_dir,request.GET["commit"]) D.update_type="commit" D.update_version = request.GET["commit"] + project.lastCommit=request.GET["commit"] res = c.Deploy(project.working_dir, project.configFile) if not "ERR:" in res: D.datetime=timezone.now() D.has_new_version=False D.save() project.lastUpdate=timezone.now() + project.newVersion=False project.save() - if "http://" not in project.deployment_link: - return HttpResponse(res+",,http://"+server.DNS+project.deployment_link) + print project.deployment_link + if not "http://" in project.deployment_link: + print "in if" + link="http://"+server.DNS+project.deployment_link + print link + return HttpResponse(res+",,"+link) else: + print "in else" return HttpResponse(res+",,"+project.deployment_link) else: return res \ No newline at end of file diff --git a/webapp/autoDeploy/autodeploy/migrations/0010_auto_20150519_1806.py b/webapp/autoDeploy/autodeploy/migrations/0010_auto_20150519_1806.py new file mode 100644 index 0000000..511ac80 --- /dev/null +++ b/webapp/autoDeploy/autodeploy/migrations/0010_auto_20150519_1806.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime + + +class Migration(migrations.Migration): + + dependencies = [ + ('autodeploy', '0009_auto_20150517_1508'), + ] + + operations = [ + migrations.AddField( + model_name='project', + name='default_server', + field=models.ForeignKey(default='localhost', blank=True, to='autodeploy.Server'), + preserve_default=False, + ), + migrations.AlterField( + model_name='deployment_server', + name='datetime', + field=models.DateTimeField(), + ), + migrations.AlterField( + model_name='deployment_server', + name='has_new_version', + field=models.IntegerField(verbose_name=b'Updates Behind'), + ), + migrations.AlterField( + model_name='project', + name='lastUpdate', + field=models.DateTimeField(default=datetime.datetime(2015, 5, 19, 18, 5, 58, 418921), blank=True), + ), + ] diff --git a/webapp/autoDeploy/autodeploy/migrations/0011_auto_20150519_1811.py b/webapp/autoDeploy/autodeploy/migrations/0011_auto_20150519_1811.py new file mode 100644 index 0000000..c3a7c6b --- /dev/null +++ b/webapp/autoDeploy/autodeploy/migrations/0011_auto_20150519_1811.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime + + +class Migration(migrations.Migration): + + dependencies = [ + ('autodeploy', '0010_auto_20150519_1806'), + ] + + operations = [ + migrations.AddField( + model_name='project', + name='update_style', + field=models.CharField(max_length=10, blank=True), + ), + migrations.AlterField( + model_name='project', + name='lastUpdate', + field=models.DateTimeField(default=datetime.datetime(2015, 5, 19, 18, 11, 25, 191104), blank=True), + ), + ] diff --git a/webapp/autoDeploy/autodeploy/migrations/0012_auto_20150519_1943.py b/webapp/autoDeploy/autodeploy/migrations/0012_auto_20150519_1943.py new file mode 100644 index 0000000..7c79f95 --- /dev/null +++ b/webapp/autoDeploy/autodeploy/migrations/0012_auto_20150519_1943.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime + + +class Migration(migrations.Migration): + + dependencies = [ + ('autodeploy', '0011_auto_20150519_1811'), + ] + + operations = [ + migrations.AddField( + model_name='project', + name='newVersion', + field=models.BooleanField(default=False), + ), + migrations.AlterField( + model_name='project', + name='lastUpdate', + field=models.DateTimeField(default=datetime.datetime(2015, 5, 19, 19, 43, 49, 254988), blank=True), + ), + ] diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index adc2275..514ed62 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -39,6 +39,7 @@ class Project(models.Model): sshKey=models.ForeignKey(SSHKey,to_field="name",verbose_name="SSH Key") repo_link=models.URLField(blank=True) deployment_link=models.CharField(max_length=200,blank=True) + newVersion=models.BooleanField(default=False) def __unicode__(self): return self.name diff --git a/webapp/autoDeploy/autodeploy/tables.py b/webapp/autoDeploy/autodeploy/tables.py index 63b4568..71de51a 100644 --- a/webapp/autoDeploy/autodeploy/tables.py +++ b/webapp/autoDeploy/autodeploy/tables.py @@ -10,10 +10,11 @@ class ProjectReport(TableReport): Operations=Table.TemplateColumn("      ") repo_link=Table.TemplateColumn("{{ record.repo_link }} ") deployment_link=Table.TemplateColumn("{{ record.deployment_link }} ") + newVersion=Table.BooleanColumn(yesno="Yes,No") class Meta: model=Project - fields=('name','repo_link','lastUpdate','deployment_link') + fields=('name','repo_link',"newVersion",'lastUpdate','deployment_link') attrs = {"class": "paleblue"} @@ -43,6 +44,16 @@ class Meta: fields=["Short","Author","Committed","Message"] sequence=["Short","Author","Committed","Message"] +class TagTable(Table.Table): + ID=Table.TemplateColumn("{{record.Tag}}",verbose_name="Tag") + Tagger=Table.Column() + Date=Table.Column() + Commit=Table.Column() + class Meta: + attrs={"class": "paleblue"} + fields=["ID","Tagger","Date","Commit"] + sequence=["ID","Tagger","Date","Commit"] + class DeploymentHistory(TableReport): class Meta: model=Deployment_Server diff --git a/webapp/autoDeploy/checkUpdates.py b/webapp/autoDeploy/checkUpdates.py new file mode 100644 index 0000000..4a5b6ae --- /dev/null +++ b/webapp/autoDeploy/checkUpdates.py @@ -0,0 +1,33 @@ +#! /usr/bin/python +__author__ = 'mohamed' + +import os,django +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "autoDeploy.settings") +django.setup() + +from autodeploy.models import * +from autodeploy_client import Client + +for project in Project.objects.all(): + updateRequired=False + print "Checking %s on %s"%(project.name,project.default_server.DNS) + c=Client(str(project.repo_type),project.default_server.ip,project.default_server.port,project.sshKey.key) + if project.update_style=="commit": + commits=c.ListCommits(project.working_dir) + if project.lastCommit != commits[0]["Hash"]: + updateRequired=True + + else: + tags = c.ListTags(project.working_dir) + if len(tags)>0: + if project.lastTag != tags[0]["Tag"]: + updateRequired=True + else: + print "No Tags Found" + + if updateRequired: + project.newVersion=True + project.save() + print "Update Required" + else: + print "Already up-to-date." \ No newline at end of file diff --git a/webapp/autoDeploy/static/css/autodeploy.css b/webapp/autoDeploy/static/css/autodeploy.css index 6b4b3db..a83d897 100644 --- a/webapp/autoDeploy/static/css/autodeploy.css +++ b/webapp/autoDeploy/static/css/autodeploy.css @@ -26,4 +26,30 @@ input, button, select, textarea { } .Operations { text-align: center +} + +.table.paleblue > tbody > tr > td > span.true, table.paleblue > tbody > tr > td > span.true +{ + background-color: #f0ad4e; + border-color: #d6e9c6; + color: #ffffff; + border-radius: 4px; + padding: 10px; + text-indent: 0px; + overflow: visible; + width: auto; + height: auto; +} + +.table.paleblue > tbody > tr > td > span.true, table.paleblue > tbody > tr > td > span.false +{ + background-color: #5cb85c; + border-color: #ffffff; + color: #3c763d; + border-radius: 4px; + padding: 10px; + text-indent: 0px; + overflow: visible; + width: auto; + height: auto; } \ No newline at end of file diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 73c72e6..8b9832e 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -117,7 +117,7 @@

    {{ title }}

  • - + diff --git a/webapp/autoDeploy/templates/clone.html b/webapp/autoDeploy/templates/clone.html index be94437..6e61685 100644 --- a/webapp/autoDeploy/templates/clone.html +++ b/webapp/autoDeploy/templates/clone.html @@ -1,5 +1,6 @@ {% extends "base.html" %} {% block content %} +

    Clone Project

    {% if result %} diff --git a/webapp/autoDeploy/templates/deploy2.html b/webapp/autoDeploy/templates/deploy2.html index 26abcc6..678d3d4 100644 --- a/webapp/autoDeploy/templates/deploy2.html +++ b/webapp/autoDeploy/templates/deploy2.html @@ -17,17 +17,9 @@

    Deploy Project

    {% else %} {% if mode == "tags" %} -

    List of Tags Show Commits

    - {% if tags|length > 0 %} - Select Tag: -
    -
      - {% for tag in tags %} - {% if tag != "" %} -
    • {{ tag }}
    • - {% endif %} - {% endfor %} -
    +

    List of Tags Show Commits 

    + {% if count > 0 %} + {% render_table tags %} {% else %}
    There is no tags in the repo
    {% endif %} diff --git a/webapp/checkUpdates.py b/webapp/checkUpdates.py deleted file mode 100644 index 91ba68b..0000000 --- a/webapp/checkUpdates.py +++ /dev/null @@ -1 +0,0 @@ -__author__ = 'mohamed' From 2b2471f7f1bf77f2813ae903eb35622063a29f91 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Tue, 19 May 2015 20:53:49 +0300 Subject: [PATCH 031/108] Some Errors Fixing --- webapp/autoDeploy/autodeploy/forms.py | 2 +- webapp/autoDeploy/autodeploy/tables.py | 2 +- webapp/autoDeploy/autodeploy/views.py | 10 +++++++--- webapp/autoDeploy/checkUpdates.py | 0 webapp/autoDeploy/templates/base.html | 2 +- 5 files changed, 10 insertions(+), 6 deletions(-) mode change 100644 => 100755 webapp/autoDeploy/checkUpdates.py diff --git a/webapp/autoDeploy/autodeploy/forms.py b/webapp/autoDeploy/autodeploy/forms.py index 822a29c..8cb8bc2 100644 --- a/webapp/autoDeploy/autodeploy/forms.py +++ b/webapp/autoDeploy/autodeploy/forms.py @@ -76,6 +76,6 @@ class Meta: fields=('name','key') class CloneForm(forms.Form): - server=forms.ModelChoiceField(queryset=models.Server.objects.all(),label="Server") + server=forms.ModelChoiceField(queryset=models.Server.objects.all(),label="Server",required=True) diff --git a/webapp/autoDeploy/autodeploy/tables.py b/webapp/autoDeploy/autodeploy/tables.py index 71de51a..d4df698 100644 --- a/webapp/autoDeploy/autodeploy/tables.py +++ b/webapp/autoDeploy/autodeploy/tables.py @@ -9,7 +9,7 @@ class ProjectReport(TableReport): name=Table.Column(verbose_name="Project Name") Operations=Table.TemplateColumn("      ") repo_link=Table.TemplateColumn("{{ record.repo_link }} ") - deployment_link=Table.TemplateColumn("{{ record.deployment_link }} ") + deployment_link=Table.TemplateColumn("http://{{record.default_server.DNS}}{{ record.deployment_link }} ") newVersion=Table.BooleanColumn(yesno="Yes,No") class Meta: diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 06514af..250f086 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -11,7 +11,7 @@ from django.shortcuts import redirect from django.template.context_processors import csrf from django.contrib.auth.decorators import login_required - +from django.http import HttpResponseRedirect @login_required(redirect_field_name="redirect") def projects(request): @@ -125,8 +125,12 @@ def deploy(request): def deploy2(request): server = None if request.method == "POST": - server = Server.objects.get(name=request.POST["server"]) - request.session["deploy_server"] = request.POST["server"] + form=CloneForm(request.POST) + if form.is_valid(): + server = Server.objects.get(name=request.POST["server"]) + request.session["deploy_server"] = request.POST["server"] + else: + return HttpResponseRedirect("../deploy?project="+request.session["deploy_project"]) else: server = Server.objects.get(name=request.session["deploy_server"]) return listTags(request, server) diff --git a/webapp/autoDeploy/checkUpdates.py b/webapp/autoDeploy/checkUpdates.py old mode 100644 new mode 100755 diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 8b9832e..58bfbb2 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -67,7 +67,7 @@ Add Project
  • - Modify Projects + Manage Projects
  • From baeccaac3c99263866332b26812137e055a677b7 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Tue, 19 May 2015 20:59:04 +0300 Subject: [PATCH 032/108] Fixed Table Headings --- webapp/autoDeploy/autodeploy/tables.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/webapp/autoDeploy/autodeploy/tables.py b/webapp/autoDeploy/autodeploy/tables.py index d4df698..718c12d 100644 --- a/webapp/autoDeploy/autodeploy/tables.py +++ b/webapp/autoDeploy/autodeploy/tables.py @@ -8,10 +8,10 @@ class ProjectReport(TableReport): name=Table.Column(verbose_name="Project Name") Operations=Table.TemplateColumn("      ") - repo_link=Table.TemplateColumn("{{ record.repo_link }} ") - deployment_link=Table.TemplateColumn("http://{{record.default_server.DNS}}{{ record.deployment_link }} ") - newVersion=Table.BooleanColumn(yesno="Yes,No") - + repo_link=Table.TemplateColumn("{{ record.repo_link }} ",verbose_name="Source Link") + deployment_link=Table.TemplateColumn("http://{{record.default_server.DNS}}{{ record.deployment_link }} ",verbose_name="Deployment Link") + newVersion=Table.BooleanColumn(yesno="Yes,No",verbose_name=" Updates Avaliable") + lastUpdate=Table.Column(verbose_name="Last Update") class Meta: model=Project fields=('name','repo_link',"newVersion",'lastUpdate','deployment_link') From a3d56e9b01ac147dc515b0777c08d2f626ca5a2c Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Wed, 20 May 2015 10:12:49 +0300 Subject: [PATCH 033/108] Update Installation.md --- Installation.md | 37 ++++++++++++++++++++++++++++++++++--- 1 file changed, 34 insertions(+), 3 deletions(-) diff --git a/Installation.md b/Installation.md index 3a414b1..ecf323c 100644 --- a/Installation.md +++ b/Installation.md @@ -2,13 +2,44 @@ This document shows how to install autoDeploy on Ubuntu System -1. Create an autodeploy user +*. Create an autodeploy user ```sh # adduser --system --home /opt/autodeploy/home --shell /bin/bash autodeploy ``` -2. Add autodeploy to sudoers. +*. Add autodeploy to sudoers. ```sh # adduser autodeploy sudo ``` -3. Copy the file in UnixConfig to /etc/sudoers.d/ +*. Copy the file in UnixConfig to /etc/sudoers.d/ + +* Install the Client Library +```sh +# python setup.py install +``` + +* Install pyCrypto +```sh +# pip install python-pycrypto +``` + +* Install yaml +```sh +# pip install pyyaml +``` + +* Edit Server init script so that it points to installation directory + +* Copy server init script to /etc/init.d + +* Configure your database + * Edit Settings file. + * Create empty database in your DBMS. +```sh +python manage.py migrate +``` + + + + + From 118318e0be9877f3aba48c254c7ae1cb2847a687 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Wed, 20 May 2015 10:53:58 +0300 Subject: [PATCH 034/108] Bug Fix --- webapp/autoDeploy/autodeploy/views.py | 4 ++-- webapp/autoDeploy/static/img/csv_icon.png | Bin 0 -> 1798 bytes webapp/autoDeploy/static/img/xls_icon.png | Bin 0 -> 4352 bytes 3 files changed, 2 insertions(+), 2 deletions(-) create mode 100644 webapp/autoDeploy/static/img/csv_icon.png create mode 100644 webapp/autoDeploy/static/img/xls_icon.png diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 250f086..45ab5f1 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -40,8 +40,8 @@ def add_project(request): project.repo_link=request.POST["repo_link"] project.sshKey=SSHKey.objects.get(name=request.POST["sshKey"]) project.working_dir=request.POST["working_dir"] - project.default_server=form.cleaned_data["default_server"] - project.update_style=form.cleaned_data["update_style"] + project.default_server=Server.objects.get(name=request.POST["default_server"]) + project.update_style=request.POST["update_style"] if request.FILES.get("cfile","")!="": project.configFile=saveFile(request.FILES["cfile"],project.name) project.save() diff --git a/webapp/autoDeploy/static/img/csv_icon.png b/webapp/autoDeploy/static/img/csv_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..a097ab0c2c70f4f664416b27f9839b269c70a248 GIT binary patch literal 1798 zcmV+h2l@DkP)500001b5ch_0Itp) z=>Px#24YJ`L;(K){{a7>y{D4^000SaNLh0L01FcU01FcV0GgZ_00007bV*G`2iyk| z3kfTbGng0v00xFhL_t(o!_}8-j8)YY$A4>|a~T+h;X=?Nf^`O|7+`qRklG0p3?wD7 zAH*s#P5M$>{Xk69w4wF`k@SNlm=IzjDU{lv1w>|QV~rTCFhW434k!}_J3yr~4&c~f z9`}9rUj1srpGcY{9^vvw+bMAhe-(Ks#*IozyU#_pd>bdT*t*swl^B5Vap{uKt zSS*H!OjXtI8e>q^vcXcUm9R}j=KYBE?n&1F33-fF(Ojh zRZ$G4crPl&*$y3gpYHC9Pd)k6lUuLFGG?TPix)3^LsT9!Vr2M%LzWVxWF~8!s=62d zxP99%Zwd@>yO?mb4b(Ze>7_sI_!Yowd-vW5j1)Bxbxi>T z19_QXB7Xp?4r{FhL7>*!jjz1CbM5yZewgN_eb)yg1z|=+TNJ7g{w_lzj`kTlb{s(v zwO;-u>eT zSFfh6?c}xXrc0MDE*Fu13=3mQw|2=cQ$adaGRIzHqXXkJz zRvm%bd|P;L%f=0jbvRT24t5^*0N!XnJhC^MPqlOaGetmAz1op+J(sAU;9_`<58Tsu zbXb^OAHThIYJBp~HxtLQ)2e=-<@hjpNbeJhLc~MOT;8L@zF&qY{hOG zNTz2P>F0D;X9-R60%PmtT@dWg;cbT~nsh zSl7VL18?(I+lQ=}cQ4+cA(svKcHLYy{&g3xw;p1}ynA`~@IOiCGCZ*GK03~KF_1{I zeAYrvpFd9~7m!G0NTxFM^!3r(KR_at9$vuV%TpvvN}8p!=JUHee4#xc!VCMGc;vq2Odem05yQ`3+(lnnwVRoBp+>_MF}XGR_0xqAUk#||0hb_$b z+AY_XcK+b`4R7Xbu&TV1RmbexzfR-qx%i&PflrTfy8Apvgt}X&v25-FV!qFjQ*E61 zyaUe|0_RxK@J+0Bw46FIQm{%YOx*kH4MBxv(%IbMR3^O&q$1e0cKnNDpS7bv%y`8J za`NBjIB~WE1$^U`yyF_3kmAUsGFM zJ+qiB+@v_1$>sX`l8Lh-5=@Q9*X;hyhI3cVXFfl3c4;=q9rQd8&lrs7g)5W-TqJpr zlG8MD*eYmv$~#q59nQI?JL~Ho0$B6hdiJb)_Uie}U@GYW7;7=cRFndQjIf@7cYLfs;X+Tgx3{abS0o52r_;B{co;Zx$>>}VsVca!p7Gm1X{1DnE+emi=%F8}}l07*qoM6N<$g081v(f|Me literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/img/xls_icon.png b/webapp/autoDeploy/static/img/xls_icon.png new file mode 100644 index 0000000000000000000000000000000000000000..c6a0ec16dec30cfea3e82b91629c26a870624880 GIT binary patch literal 4352 zcmV+b5&!OqP)5000V4X+uL$P-t&- zZ*ypGa3D!TLm+T+Z)Rz1WdHzp+MQEpR8#2|J@?-9LQ9B%luK_?6$l_wLW_VDktQl3 z2@pz%A)(n7QNa;KMFbnjpojyGj)066Q7jCK3fKqaA)=0hqlk*i`{8?|Yu3E?=FR@K z*FNX0^PRKL2fzpnmPj*EHGmAMLLL#|gU7_i;p8qrfeIvW01ybXWFd3?BLM*Temp!Y zBESc}00DT@3kU$fO`E_l9Ebl8>Oz@Z0f2-7z;ux~O9+4z06=<WDR*FRcSTFz- zW=q650N5=6FiBTtNC2?60Km==3$g$R3;-}uh=nNt1bYBr$Ri_o0EC$U6h`t_Jn<{8 z5a%iY0C<_QJh>z}MS)ugEpZ1|S1ukX&Pf+56gFW3VVXcL!g-k)GJ!M?;PcD?0HBc- z5#WRK{dmp}uFlRjj{U%*%WZ25jX z{P*?XzTzZ-GF^d31o+^>%=Ap99M6&ogks$0k4OBs3;+Bb(;~!4V!2o<6ys46agIcq zjPo+3B8fthDa9qy|77CdEc*jK-!%ZRYCZvbku9iQV*~a}ClFY4z~c7+0P?$U!PF=S z1Au6Q;m>#f??3%Vpd|o+W=WE9003S@Bra6Svp>fO002awfhw>;8}z{#EWidF!3EsG z3;bXU&9EIRU@z1_9W=mEXoiz;4lcq~xDGvV5BgyU zp1~-*fe8db$Osc*A=-!mVv1NJjtCc-h4>-CNCXm#Bp}I%6j35eku^v$Qi@a{RY)E3 zJ#qp$hg?Rwkvqr$GJ^buyhkyVfwECO)C{#lxu`c9ghrwZ&}4KmnvWKso6vH!8a<3Q zq36)6Xb;+tK10Vaz~~qUGsJ8#F2=(`u{bOVlVi)VBCHIn#u~6ztOL7=^<&SmcLWlF zMZgI*1b0FpVIDz9SWH+>*hr`#93(Um+6gxa1B6k+CnA%mOSC4s5&6UzVlpv@SV$}* z))J2sFA#f(L&P^E5{W}HC%KRUNwK6<(h|}}(r!{C=`5+6G)NjFlgZj-YqAG9lq?`C z$c5yc>d>VnA`E_*3F2Qp##d8RZb=H01_mm@+|Cqnc9PsG(F5HIG_C zt)aG3uTh7n6Et<2In9F>NlT@zqLtGcXcuVrX|L#Xx)I%#9!{6gSJKPrN9dR61N3(c z4Tcqi$B1Vr8Jidf7-t!G7_XR2rWwr)$3XQ?}=hpK0&Z&W{| zep&sA23f;Q!%st`QJ}G3cbou<7-yIK2z4nfCCCtN2-XOGSWo##{8Q{ATurxr~;I`ytDs%xbip}RzP zziy}Qn4Z2~fSycmr`~zJ=lUFdFa1>gZThG6M+{g7vkW8#+YHVaJjFF}Z#*3@$J_By zLtVo_L#1JrVVB{Ak-5=4qt!-@Mh}c>#$4kh<88)m#-k<%CLtzEP3leVno>={htGUuD;o7bD)w_sX$S}eAxwzy?UvgBH(S?;#HZiQMoS*2K2 zT3xe7t(~nU*1N5{rxB;QPLocnp4Ml>u<^FZwyC!nu;thW+pe~4wtZn|Vi#w(#jeBd zlf9FDx_yoPJqHbk*$%56S{;6Kv~mM9!g3B(KJ}#RZ#@)!hR|78Dq|Iq-afF%KE1Brn_fm;Im z_u$xr8UFki1L{Ox>G0o)(&RAZ;=|I=wN2l97;cLaHH6leTB-XXa*h%dBOEvi`+x zi?=Txl?TadvyiL>SuF~-LZ;|cS}4~l2eM~nS7yJ>iOM;atDY;(?aZ^v+mJV$@1Ote z62cPUlD4IWOIIx&SmwQ~YB{nzae3Pc;}r!fhE@iwJh+OsDs9zItL;~pu715HdQEGA zUct(O!LkCy1<%NCg+}G`0PgpNm-?d@-hMgNe6^V+j6x$b<6@S<$+<4_1hi}Ti zncS4LsjI}fWY1>OX6feMEuLErma3QLmkw?X+1j)X-&VBk_4Y;EFPF_I+q;9dL%E~B zJh;4Nr^(LEJ3myURP{Rblsw%57T)g973R8o)DE9*xN#~;4_o$q%o z4K@u`jhx2fBXC4{U8Qn{*%*B$Ge=nny$HAYq{=vy|sI0 z_vss+H_qMky?OB#|JK!>IX&II^LlUh#rO5!7TtbwC;iULyV-Xq?ybB}ykGP{?LpZ? z-G|jbTmIbG@7#ZCz;~eY(cDM(28Dyq{*m>M4?_iynUBkc4TkHUI6gT!;y-fz>HMcd z&t%Ugo)`Y2{>!cx7B7DI)$7;J(U{Spm-3gBzioV_{p!H$8L!*M!p0uH$#^p{Ui4P` z?ZJ24cOCDe-w#jZd?0@)|7iKK^;6KN`;!@ylm7$*nDhK&GcDTy000JJOGiWi{{a60 z|De66lK=n!32;bRa{vGf6951U69E94oEQKA00(qQO+^RX2NDYkC$gxA@Bjb?GD$>1 zR9M5+m~D(5RT;;B&pC6q-DS6GDJ3F?)HeD-8>*FePo+!&+mksA|o; zNc|oW;gwhZF|=~Uir+li^C-7(y#2hv$aIq@Mn--mBG(#YkldTgn2gD<){44;fdR(G z#x~yhl{!r0gt zLqkJMOiU0(5rslQqbQP&j(PWd>V_L0o^_s?=_>os)I6iA%%6WTYu0pD{3-+$K#h?# zz{Br|nKEBdrsTgmK;^M)R$~mt7*Qo$pwDPir!G5l8B`uz8E^(#>gHzzbMK$~q5pbR zmDRuA+VYm0EX3ZCgsP+BT z7rt{+RWCunYtWfW#)U+q#iFRTm}teo>iZ8j1he}22cEm?;zie8-ufO*)YZ%d4H&Ui zhg8Li!E3;ZL31V*APoT{Qa6{GLkPgr!+$#4W?J6${Iw7Ix@bz1bC(ZKjPlaR-=+ZZ zZ2Q=4Jn_$dh9;DSbJ}=l+0EQ_@W{qEar|LZ>Pzw$0j@%PxAKI>E7ntYQaK8J+3aWsifP#=R! zYQ-mP|I1$9jEn4F*Td+!b^u4+V@h#vpMH(EWMa0Dnk00ZK!;jFl_$K<-Jj73~ z-hyQeZK9jB2{ZV(skBSP-AgyH@AZ9bUiJ+z|ISWYVJ1dhkyV#2rDN{feBs$meB#N^ z(HhO;rp4>P7n|#ESPopVVK^qi(RckeeldK2t-syDN9HY~xAVtr9?WvYJxlLELxEHs z2j19E|H>ZTjvu6577`i5;PF9lGiSXTFzRBFM%B+Jyfl1-oqzA8m58q%x{uqg{4%G` zj_{*D^w44p*)sJU8$ZgXgZFXWqHFM)vhlgQIWc+;E0#u0YE9#oU+~Gt);;dM-_R%> zy5NaSRLL{hvn6P#Rt*6ondQ^q5QNCs##JUOC&i9A?HB#B`T0btW2uiP&ZHCn5g~3Xv~4(e%fXjt>}QU?dh|1?ru(h6 zh%rRg<|?t&wxc;kdHS> zh+wTHgiymw2%%!GM$wlCop3%yf2O$JBH-aw#atJBlGG?Y`9L;^XO681Fmyxtd uj;ey0ntZg5vvM$o|M{Zaa literal 0 HcmV?d00001 From 3cb0337f3098acd5d21c1de45e87d2acfea6cdbd Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Wed, 20 May 2015 11:50:32 +0300 Subject: [PATCH 035/108] Second set of issues --- server/deployer/autodeployer.py | 19 ++++++++++++------- webapp/autoDeploy/autodeploy/api.py | 2 +- webapp/autoDeploy/static/js/functions.js | 4 ++-- 3 files changed, 15 insertions(+), 10 deletions(-) diff --git a/server/deployer/autodeployer.py b/server/deployer/autodeployer.py index db8ce8a..10baf3c 100644 --- a/server/deployer/autodeployer.py +++ b/server/deployer/autodeployer.py @@ -65,14 +65,19 @@ def deploy(config,workdir=".",raiseErrorOnStdErr=True): runEvents(config,workdir,"beforeInstall",raiseErrorOnStdErr) printNotication("Starting Deployment") - if not slient: print " Copying Files" - handleFiles(config["files"],workdir) - if not slient: print " Copying done" - - if not slient: print " Setting Permissions" - handlePermissions(config["permissions"],raiseErrorOnStdErr) - if not slient: print " Permissions Done" + if not "files" in config.keys(): + if not slient: print " No files to copy...skipping" + else: + if not slient: print " Copying Files" + handleFiles(config["files"],workdir) + if not slient: print " Copying done" + if not "permissions" in config.keys(): + if not slient: print " No permission to set...skipping" + else: + if not slient: print " Setting Permissions" + handlePermissions(config["permissions"],raiseErrorOnStdErr) + if not slient: print " Permissions Done" printNotication("Deployment Done.......") printNotication("Starting After Install Scripts") diff --git a/webapp/autoDeploy/autodeploy/api.py b/webapp/autoDeploy/autodeploy/api.py index 36d7e1a..b385e63 100644 --- a/webapp/autoDeploy/autodeploy/api.py +++ b/webapp/autoDeploy/autodeploy/api.py @@ -62,4 +62,4 @@ def deploy(request): else: print "in else" return HttpResponse(res+",,"+project.deployment_link) - else: return res \ No newline at end of file + else: return HttpResponse(res) \ No newline at end of file diff --git a/webapp/autoDeploy/static/js/functions.js b/webapp/autoDeploy/static/js/functions.js index 8d1379b..679bf7b 100644 --- a/webapp/autoDeploy/static/js/functions.js +++ b/webapp/autoDeploy/static/js/functions.js @@ -28,7 +28,7 @@ function renderResult(data,success) { if (data == "Done") html = "
    "+success+"
    " else - html = "
    " + data + "
    " + html = "
    " + data + "
    " $("#content").html(html) @@ -43,7 +43,7 @@ function deploy(data) if (data.indexOf("Done")>-1) { res = data.split(",,") - renderResult(res[0], "Deployment was successful. Visit " + res[1] + "") + renderResult(res[0], "Deployment was successful. Visit " + res[1] + "") } else renderResult(data,"Done.") From c41db4ffa8d12f2bcdb311ad0a22ff6a834685aa Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Wed, 20 May 2015 13:28:39 +0300 Subject: [PATCH 036/108] Fixed some issues --- server/deployer/autodeployer.py | 1 + webapp/autoDeploy/accounts/views.py | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/server/deployer/autodeployer.py b/server/deployer/autodeployer.py index 10baf3c..b195f80 100644 --- a/server/deployer/autodeployer.py +++ b/server/deployer/autodeployer.py @@ -78,6 +78,7 @@ def deploy(config,workdir=".",raiseErrorOnStdErr=True): if not slient: print " Setting Permissions" handlePermissions(config["permissions"],raiseErrorOnStdErr) if not slient: print " Permissions Done" + printNotication("Deployment Done.......") printNotication("Starting After Install Scripts") diff --git a/webapp/autoDeploy/accounts/views.py b/webapp/autoDeploy/accounts/views.py index 3506a2d..949c5e7 100644 --- a/webapp/autoDeploy/accounts/views.py +++ b/webapp/autoDeploy/accounts/views.py @@ -4,6 +4,7 @@ from django.shortcuts import render, render_to_response,redirect from django.contrib.auth import authenticate, login,logout from django.template import RequestContext +from autoDeploy import settings @@ -19,7 +20,7 @@ def check(request): if user.is_active: login(request, user) if "redirect" in request.POST: - return redirect(request.POST["redirect"]) + return redirect(settings.BASE_URL+request.POST["redirect"]) else: return redirect("/") # Redirect to a success page. From c5c8ffb4e5262d470f3c6dbb7ed8c5434b48c4ab Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Wed, 20 May 2015 13:45:45 +0300 Subject: [PATCH 037/108] Fixed: Issue during login --- webapp/autoDeploy/templates/account/login.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webapp/autoDeploy/templates/account/login.html b/webapp/autoDeploy/templates/account/login.html index da6deca..643f15c 100644 --- a/webapp/autoDeploy/templates/account/login.html +++ b/webapp/autoDeploy/templates/account/login.html @@ -8,7 +8,7 @@ {% endif %}

    Log In to continue

    -
    + {% csrf_token %} {% if request.GET.redirect %} From a03862bae3843c6ccbc571714cd2c17632d44cf6 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Wed, 20 May 2015 15:56:18 +0300 Subject: [PATCH 038/108] Fixed Issues --- server/scm/Git.py | 2 +- webapp/autoDeploy/autodeploy/tables.py | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/server/scm/Git.py b/server/scm/Git.py index 9716658..e25e31b 100644 --- a/server/scm/Git.py +++ b/server/scm/Git.py @@ -21,7 +21,7 @@ def get_clone_cmd(self): def get_pull_cmd(self): return "cd %s; git pull"%self.workdir def get_list_tags_cmd(self): - return "cd %s; git tag -l"%self.workdir + return self.get_pull_cmd()+";git tag -l"%self.workdir def get_switch_to_tag_cmd(self,tag): return "cd %s; git checkout tags/%s"%(self.workdir,tag) def get_history_cmd(self): diff --git a/webapp/autoDeploy/autodeploy/tables.py b/webapp/autoDeploy/autodeploy/tables.py index 718c12d..13fe133 100644 --- a/webapp/autoDeploy/autodeploy/tables.py +++ b/webapp/autoDeploy/autodeploy/tables.py @@ -6,10 +6,17 @@ class ProjectReport(TableReport): + depLink=""" + {% if not "http" in record.deployment_link%} + http://{{record.default_server.DNS}}{{ record.deployment_link }} + {% else %} + {{ record.deployment_link }} + {% endif %} + """ name=Table.Column(verbose_name="Project Name") Operations=Table.TemplateColumn("      ") repo_link=Table.TemplateColumn("{{ record.repo_link }} ",verbose_name="Source Link") - deployment_link=Table.TemplateColumn("http://{{record.default_server.DNS}}{{ record.deployment_link }} ",verbose_name="Deployment Link") + deployment_link=Table.TemplateColumn(depLink,verbose_name="Deployment Link") newVersion=Table.BooleanColumn(yesno="Yes,No",verbose_name=" Updates Avaliable") lastUpdate=Table.Column(verbose_name="Last Update") class Meta: From 5b0851cbee52666548a5b89e58d05902d3e88908 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Wed, 20 May 2015 15:59:50 +0300 Subject: [PATCH 039/108] Fixed Broken Commits --- webapp/autoDeploy/templates/deploy2.html | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webapp/autoDeploy/templates/deploy2.html b/webapp/autoDeploy/templates/deploy2.html index 678d3d4..a4a4861 100644 --- a/webapp/autoDeploy/templates/deploy2.html +++ b/webapp/autoDeploy/templates/deploy2.html @@ -17,14 +17,14 @@

    Deploy Project

    {% else %} {% if mode == "tags" %} -

    List of Tags Show Commits 

    +

    List of Tags Show Commits 

    {% if count > 0 %} {% render_table tags %} {% else %}
    There is no tags in the repo
    {% endif %} {% elif mode == "commits" %} -

    List of Commits Show Tags

    +

    List of Commits Show Tags

    {% render_table commits %}
    From cd4374928d93d3e077d1cf7c61e2e0f4b588674f Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Fri, 22 May 2015 10:42:35 +0300 Subject: [PATCH 040/108] Fixed Issue in Tags refresh --- server/scm/Git.py | 4 ++-- webapp/autoDeploy/autodeploy/views.py | 7 ++++++- webapp/autoDeploy/checkUpdates.py | 1 + 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/server/scm/Git.py b/server/scm/Git.py index e25e31b..81f2fae 100644 --- a/server/scm/Git.py +++ b/server/scm/Git.py @@ -21,11 +21,11 @@ def get_clone_cmd(self): def get_pull_cmd(self): return "cd %s; git pull"%self.workdir def get_list_tags_cmd(self): - return self.get_pull_cmd()+";git tag -l"%self.workdir + return "cd %s;git tag -l"%self.workdir def get_switch_to_tag_cmd(self,tag): return "cd %s; git checkout tags/%s"%(self.workdir,tag) def get_history_cmd(self): - return self.get_pull_cmd()+'; git log --all --pretty=format:"%H,,%h,,%an,,%ar,,%s,,%cd" | cat -' + return 'cd ' + self.workdir +'; git log --all --pretty=format:"%H,,%h,,%an,,%ar,,%s,,%cd" | cat -' def switch_to_histroy_cmd(self,commit): return 'cd %s; git reset --hard %s'%(self.workdir,commit) def commit_diff_cmd(self,commit): diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 45ab5f1..84bf8c6 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -133,7 +133,11 @@ def deploy2(request): return HttpResponseRedirect("../deploy?project="+request.session["deploy_project"]) else: server = Server.objects.get(name=request.session["deploy_server"]) - return listTags(request, server) + if request.GET.get("refresh","False")=="True": + project=Project.objects.get(name=request.session["deploy_project"]) + c=Client(str(project.repo_type),server.ip,server.port,project.sshKey.key) + c.Pull(project.repo,project.working_dir,project.sshKey.key) + return listTags(request, server) @login_required(redirect_field_name="redirect") def listTags(request, server): @@ -270,6 +274,7 @@ def listCommits(request): server = Server.objects.get(name=request.session["deploy_server"]) project = Project.objects.get(name=request.session["deploy_project"]) c = Client("git", server.ip, server.port,key=project.sshKey.key) + c.Pull(project.repo,project.working_dir,project.sshKey.key) res = c.ListCommits(project.working_dir) request.session["commits"] = res else: diff --git a/webapp/autoDeploy/checkUpdates.py b/webapp/autoDeploy/checkUpdates.py index 4a5b6ae..80e7bc5 100755 --- a/webapp/autoDeploy/checkUpdates.py +++ b/webapp/autoDeploy/checkUpdates.py @@ -12,6 +12,7 @@ updateRequired=False print "Checking %s on %s"%(project.name,project.default_server.DNS) c=Client(str(project.repo_type),project.default_server.ip,project.default_server.port,project.sshKey.key) + c.Pull(project.repo,project.working_dir,project.sshKey.key) if project.update_style=="commit": commits=c.ListCommits(project.working_dir) if project.lastCommit != commits[0]["Hash"]: From b5f78117c844f8529476a605f20d43611540fa53 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 23 May 2015 11:16:00 +0300 Subject: [PATCH 041/108] Created JIRA Communicator #27 --- autodeploy-jira/__init__.py | 1 + autodeploy-jira/jira-client.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+) create mode 100644 autodeploy-jira/__init__.py create mode 100644 autodeploy-jira/jira-client.py diff --git a/autodeploy-jira/__init__.py b/autodeploy-jira/__init__.py new file mode 100644 index 0000000..91ba68b --- /dev/null +++ b/autodeploy-jira/__init__.py @@ -0,0 +1 @@ +__author__ = 'mohamed' diff --git a/autodeploy-jira/jira-client.py b/autodeploy-jira/jira-client.py new file mode 100644 index 0000000..f37a000 --- /dev/null +++ b/autodeploy-jira/jira-client.py @@ -0,0 +1,29 @@ +__author__ = 'mohamed' + +from jira.client import JIRA + +class jiraClient(): + server="" + username="" + password="" + + def __init__(self,server,username,password): + self.server=server + self.username=username + self.password=password + + def getProjects(self): + options = {'server': self.server} + + jira = JIRA(options,basic_auth=(self.username, self.password)) # a username/password tuple + + # Get the mutable application properties for this server (requires jira-system-administrators permission) + props = jira.application_properties() + projects = jira.projects() + return projects + def getProjectKeys(self): + return [project.key for project in self.getProjects()] + +if __name__=="__main__": + c=jiraClient("http://shgp.kfshrc.edu.sa/jira",'mkalioby','wanted85') + print c.getProjectKeys() \ No newline at end of file From 6e6f5ff9e7a36e1ff1b197eef63fb3b5cf9bbf7b Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 23 May 2015 11:16:31 +0300 Subject: [PATCH 042/108] Added Plugins to the menu --- webapp/autoDeploy/templates/base.html | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 58bfbb2..5d52655 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -86,6 +86,13 @@
  • Modify SSH Keys
  • +
  • + Plugins + +
  • From f233e2c7b43d56eba7b60c272d4e57759df9d701 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Mon, 1 Jun 2015 09:40:52 +0300 Subject: [PATCH 043/108] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 6a2b9da..f99d341 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -# autoDeploy -Trying to build an automated deployment system which is similar to AWS CodeDeploy. +# AutoDeploy +Buildong an automated deployment system which is similar to AWS CodeDeploy but is hostable inside enterprise. The target is to minimize the manual prone errors of code deployment. @@ -16,9 +16,9 @@ The client should be callable from CI systems (like Jenkins) to deploy the code The following events will be handled by the system: -1. **Before Install**: This event will run after the code is downloaded, normal will be used to stop servers/decrypt files +1. **beforeInstall**: This event will run after the code is downloaded, normal will be used to stop servers/decrypt files 2. **Install**: doing the deployment operation itself -3. **After Install**: Actions required after Installing like reloading a server. +3. **afterInstall**: Actions required after Installing like reloading a server. 4. **Validation**: An optiomal step to make sure that everything is OK. Every event should have the following format: From b5eeb99546ed4037babe9b2c82fc95108ee76f0c Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Thu, 4 Jun 2015 10:31:37 +0300 Subject: [PATCH 044/108] Update Installation.md --- Installation.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Installation.md b/Installation.md index ecf323c..2898109 100644 --- a/Installation.md +++ b/Installation.md @@ -30,6 +30,10 @@ This document shows how to install autoDeploy on Ubuntu System * Edit Server init script so that it points to installation directory * Copy server init script to /etc/init.d +* Add the init script to the start defaults +```sh +sudo update-rc.d autodeploy-server start +``` * Configure your database * Edit Settings file. @@ -37,7 +41,12 @@ This document shows how to install autoDeploy on Ubuntu System ```sh python manage.py migrate ``` +* Start Django Sever +```sh +python manage.py runserver IP:PORT +``` +A Guide to show how to configure autodeploy Django webapp with Apache should be done. From d17d2572bb41afa82378c1dad687320d980e4f96 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Thu, 4 Jun 2015 10:32:12 +0300 Subject: [PATCH 045/108] Update Installation.md --- Installation.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Installation.md b/Installation.md index 2898109..c0006f1 100644 --- a/Installation.md +++ b/Installation.md @@ -2,15 +2,15 @@ This document shows how to install autoDeploy on Ubuntu System -*. Create an autodeploy user +* Create an autodeploy user ```sh # adduser --system --home /opt/autodeploy/home --shell /bin/bash autodeploy ``` -*. Add autodeploy to sudoers. +* Add autodeploy to sudoers. ```sh # adduser autodeploy sudo ``` -*. Copy the file in UnixConfig to /etc/sudoers.d/ +* Copy the file in UnixConfig to /etc/sudoers.d/ * Install the Client Library ```sh From b3b8bc7e06c0522c353e8d70b574b77108167a76 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Tue, 7 Jul 2015 18:01:17 +0300 Subject: [PATCH 046/108] Fixed issue in login --- webapp/autoDeploy/accounts/views.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webapp/autoDeploy/accounts/views.py b/webapp/autoDeploy/accounts/views.py index 949c5e7..4ce2b23 100644 --- a/webapp/autoDeploy/accounts/views.py +++ b/webapp/autoDeploy/accounts/views.py @@ -20,9 +20,9 @@ def check(request): if user.is_active: login(request, user) if "redirect" in request.POST: - return redirect(settings.BASE_URL+request.POST["redirect"]) + return redirect(request.POST["redirect"]) else: - return redirect("/") + return redirect(settings.BASE_URL) # Redirect to a success page. else: err="This user is NOT activated yet." From f97a8450823fb9374c1650c381a7440be3117b0f Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Mon, 17 Aug 2015 12:42:08 +0200 Subject: [PATCH 047/108] Added Emails to be sent to users when new version deployed --- client/autodeploy_client/Client.py | 2 +- server/autodeploy-server.py | 1 + webapp/autoDeploy/autoDeploy/settings.py | 16 ++++++- webapp/autoDeploy/autodeploy/Common.py | 38 +++++++++++++++ webapp/autoDeploy/autodeploy/api.py | 9 ++++ webapp/autoDeploy/autodeploy/forms.py | 8 +++- .../migrations/0013_auto_20150817_1250.py | 33 +++++++++++++ webapp/autoDeploy/autodeploy/models.py | 5 +- webapp/autoDeploy/autodeploy/views.py | 47 ++++++++++--------- 9 files changed, 132 insertions(+), 27 deletions(-) create mode 100644 webapp/autoDeploy/autodeploy/Common.py create mode 100644 webapp/autoDeploy/autodeploy/migrations/0013_auto_20150817_1250.py diff --git a/client/autodeploy_client/Client.py b/client/autodeploy_client/Client.py index 000c4eb..6ffd6f0 100644 --- a/client/autodeploy_client/Client.py +++ b/client/autodeploy_client/Client.py @@ -85,7 +85,7 @@ def ListCommits(self, workdir, page=0, rpp=10, owner=''): res = self._send(msg) result = [] #HEAD = True - for line in res.split("\n")[1:]: + for line in res.split("\n"): if line=="": continue info = line.split(",,") # print line diff --git a/server/autodeploy-server.py b/server/autodeploy-server.py index 17b7a3b..6c6f321 100755 --- a/server/autodeploy-server.py +++ b/server/autodeploy-server.py @@ -136,6 +136,7 @@ def HandleClient(clientsock): if cmd!="": print cmd res=Common.run(cmd) + print res Response.sendData(clientsock,res) if debug: print "Ended,",res diff --git a/webapp/autoDeploy/autoDeploy/settings.py b/webapp/autoDeploy/autoDeploy/settings.py index e96fce4..805baf0 100644 --- a/webapp/autoDeploy/autoDeploy/settings.py +++ b/webapp/autoDeploy/autoDeploy/settings.py @@ -97,7 +97,7 @@ LANGUAGE_CODE = 'en-us' -TIME_ZONE = 'UTC' +TIME_ZONE = 'Asia/Riyadh' USE_I18N = True @@ -115,4 +115,16 @@ MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' -#LOGIN_URL=BASE_URL+"admin" +SESSION_EXPIRE_AT_BROWSER_CLOSE = False +SESSION_COOKIE_AGE = 30000 # time in seconds + +LOGIN_URL=BASE_URL+"accounts/login" + +SMTP= { + 'HOST': 'smtp.gmail.com', + 'PORT': '587', + 'USERNAME': '', + 'PASSWORD': '', + 'FROM':'Auto Deploy' + + } \ No newline at end of file diff --git a/webapp/autoDeploy/autodeploy/Common.py b/webapp/autoDeploy/autodeploy/Common.py new file mode 100644 index 0000000..77e7857 --- /dev/null +++ b/webapp/autoDeploy/autodeploy/Common.py @@ -0,0 +1,38 @@ +__author__ = 'mohamed' + +def send(to,subject,body,fromUser=None,cc="",bcc="",): + + from django.conf import settings + import smtplib + from email.mime.multipart import MIMEMultipart + from email.mime.text import MIMEText + From=fromUser + if fromUser==None: + From="%s<%s>"%(settings.SMTP["FROM"],settings.SMTP["USERNAME"]) + try: + msg = MIMEMultipart('alternative') + msg['Subject'] = subject + msg['From'] = From + #msg['To'] = to one email + msg['Cc']= cc + if type(to)==type([]): + msg['To'] = ', '.join( to) #More than one email + else: + msg['To'] = to + html = body + part2 = MIMEText(html, 'html') + msg.attach(part2) + server = smtplib.SMTP(settings.SMTP["HOST"],settings.SMTP["PORT"]) + server.ehlo() + server.starttls() + server.login(settings.SMTP["USERNAME"], settings.SMTP["PASSWORD"]) + server.sendmail(From, to, msg.as_string()) + if cc!="": + server.sendmail(From, cc, msg.as_string()) + if bcc!="": + server.sendmail(From, bcc, msg.as_string()) + server.quit() + return True + + except Exception as exp: + return False diff --git a/webapp/autoDeploy/autodeploy/api.py b/webapp/autoDeploy/autodeploy/api.py index b385e63..78969f4 100644 --- a/webapp/autoDeploy/autodeploy/api.py +++ b/webapp/autoDeploy/autodeploy/api.py @@ -28,6 +28,7 @@ def clone(request): @csrf_protect def deploy(request): + import Common server = Server.objects.get(name=request.session["deploy_server"]) project = Project.objects.get(name=request.session["deploy_project"]) D= Deployment_Server() @@ -58,8 +59,16 @@ def deploy(request): print "in if" link="http://"+server.DNS+project.deployment_link print link + if project.emailUsers!="" or project.emailUsers!=" ": + for user in project.emailUsers.split(","): + Common.send(user,"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s"%(project.name,link),fromUser=None,cc="",bcc="",) + return HttpResponse(res+",,"+link) else: print "in else" + if project.emailUsers!="" or project.emailUsers!=" ": + for user in project.emailUsers.split(","): + Common.send(user,"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s"%(project.name,project.deployment_link),fromUser=None,cc="",bcc="",) + return HttpResponse(res+",,"+project.deployment_link) else: return HttpResponse(res) \ No newline at end of file diff --git a/webapp/autoDeploy/autodeploy/forms.py b/webapp/autoDeploy/autodeploy/forms.py index 8cb8bc2..e6dcf9f 100644 --- a/webapp/autoDeploy/autodeploy/forms.py +++ b/webapp/autoDeploy/autodeploy/forms.py @@ -26,6 +26,7 @@ class ProjectsForm(forms.ModelForm): repo_link= forms.CharField(label='Repo Link',widget=forms.TextInput(attrs={'class':'form-control','size':30})) repo= forms.CharField(label='Repo',widget=forms.TextInput(attrs={'class':'form-control','size':30})) deployment_link= forms.CharField(label='Deployment Link',widget=forms.TextInput(attrs={'class':'form-control','size':30})) + emailUsers=forms.CharField(label='Users emails',help_text="comma seprated list of emails of users to notify when new version deployed",widget=forms.TextInput(attrs={'class':'form-control','size':30})) def __init__(self, *args, **kwargs): super(ProjectsForm, self).__init__(*args, **kwargs) @@ -43,12 +44,15 @@ def save(self,files,name): P.sshKey=self.cleaned_data["sshKey"] P.default_server=self.cleaned_data["default_server"] P.update_style=self.cleaned_data["update_style"] + P.emailUsers=self.clened_data["emailUsers"] print "Files is ",files - P.configFile = saveFile(files.get('cfile',''),name) + f=files.get('cfile','') + if f!="": + P.configFile = saveFile(files.get('cfile',''),name) P.save() class Meta: model= models.Project - fields=("name","repo","repo_link","working_dir","update_style","default_server","repo_type","sshKey","deployment_link","cfile") + fields=("name","repo","repo_link","working_dir","update_style","default_server","repo_type","sshKey","deployment_link","cfile","emailUsers") class ServerForm(forms.ModelForm): ip=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','size':30}),label="Hostname/IP") diff --git a/webapp/autoDeploy/autodeploy/migrations/0013_auto_20150817_1250.py b/webapp/autoDeploy/autodeploy/migrations/0013_auto_20150817_1250.py new file mode 100644 index 0000000..9841669 --- /dev/null +++ b/webapp/autoDeploy/autodeploy/migrations/0013_auto_20150817_1250.py @@ -0,0 +1,33 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime + + +class Migration(migrations.Migration): + + dependencies = [ + ('autodeploy', '0012_auto_20150519_1943'), + ] + + operations = [ + migrations.CreateModel( + name='Plugins', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ('name', models.CharField(max_length=50)), + ('settings', models.TextField()), + ], + ), + migrations.AddField( + model_name='project', + name='emailUsers', + field=models.TextField(default=b'', blank=True), + ), + migrations.AlterField( + model_name='project', + name='lastUpdate', + field=models.DateTimeField(default=datetime.datetime(2015, 8, 17, 12, 50, 51, 949082), blank=True), + ), + ] diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index 514ed62..7ffd1a8 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -40,6 +40,7 @@ class Project(models.Model): repo_link=models.URLField(blank=True) deployment_link=models.CharField(max_length=200,blank=True) newVersion=models.BooleanField(default=False) + emailUsers=models.TextField(default="",blank=True) def __unicode__(self): return self.name @@ -54,6 +55,8 @@ class Deployment_Server(models.Model): project = models.ForeignKey(Project) server = models.ForeignKey(Server) - +class Plugins(models.Model): + name=models.CharField(max_length=50) + settings=models.TextField() diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 84bf8c6..71aae29 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -124,6 +124,7 @@ def deploy(request): @login_required(redirect_field_name="redirect") def deploy2(request): server = None + project=Project.objects.get(name=request.session["deploy_project"]) if request.method == "POST": form=CloneForm(request.POST) if form.is_valid(): @@ -134,10 +135,12 @@ def deploy2(request): else: server = Server.objects.get(name=request.session["deploy_server"]) if request.GET.get("refresh","False")=="True": - project=Project.objects.get(name=request.session["deploy_project"]) c=Client(str(project.repo_type),server.ip,server.port,project.sshKey.key) c.Pull(project.repo,project.working_dir,project.sshKey.key) + if project.update_style=="tag": return listTags(request, server) + else: + return listCommits(request) @login_required(redirect_field_name="redirect") def listTags(request, server): @@ -264,26 +267,28 @@ def checkServersStatus(request): @login_required(redirect_field_name="redirect") def listCommits(request): - if request.method == "GET": - res = None - if request.GET.get("refresh","False")=="True": - if "commits" in request.session: - del request.session["commits"] - return redirect("./listCommits") - if not "commits" in request.session: - server = Server.objects.get(name=request.session["deploy_server"]) - project = Project.objects.get(name=request.session["deploy_project"]) - c = Client("git", server.ip, server.port,key=project.sshKey.key) - c.Pull(project.repo,project.working_dir,project.sshKey.key) - res = c.ListCommits(project.working_dir) - request.session["commits"] = res - else: - res = request.session["commits"] - table = CommitTable(res) - table_to_report = RequestConfig(request, paginate={"per_page": 15}).configure(table) - if table_to_report: - return create_report_http_response(table_to_report, request) - return render_to_response("deploy2.html", {"mode":"commits","commits": table}, context_instance=RequestContext(request)) + #if request.method == "GET": + res = None + print request.GET.get("refresh","False") + if request.GET.get("refresh","False")=="True": + if "commits" in request.session: + del request.session["commits"] + return redirect("./listCommits") + if not "commits" in request.session: + server = Server.objects.get(name=request.session["deploy_server"]) + project = Project.objects.get(name=request.session["deploy_project"]) + c = Client("git", server.ip, server.port,key=project.sshKey.key) + c.Pull(project.repo,project.working_dir,project.sshKey.key) + res = c.ListCommits(project.working_dir) + print res + request.session["commits"] = res + else: + res = request.session["commits"] + table = CommitTable(res) + table_to_report = RequestConfig(request, paginate={"per_page": 15}).configure(table) + if table_to_report: + return create_report_http_response(table_to_report, request) + return render_to_response("deploy2.html", {"mode":"commits","commits": table}, context_instance=RequestContext(request)) @login_required(redirect_field_name="redirect") From e1ec832045da7fe7553e9d24f9810c0b276cbdce Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Mon, 17 Aug 2015 12:54:25 +0200 Subject: [PATCH 048/108] Fixed issue when add email users --- requirments.txt | 5 +++++ webapp/autoDeploy/autodeploy/views.py | 1 + 2 files changed, 6 insertions(+) create mode 100644 requirments.txt diff --git a/requirments.txt b/requirments.txt new file mode 100644 index 0000000..0317f76 --- /dev/null +++ b/requirments.txt @@ -0,0 +1,5 @@ +pycrypto +django +django-tables2 +django-tables2-reports +jira diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 71aae29..f11977c 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -42,6 +42,7 @@ def add_project(request): project.working_dir=request.POST["working_dir"] project.default_server=Server.objects.get(name=request.POST["default_server"]) project.update_style=request.POST["update_style"] + project.emailUsers=request.POST["emailUsers"] if request.FILES.get("cfile","")!="": project.configFile=saveFile(request.FILES["cfile"],project.name) project.save() From 804d6141445a11eb8ce591717abbebb57da6716b Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Tue, 18 Aug 2015 15:42:30 +0200 Subject: [PATCH 049/108] Make send a single mail rather than different mails --- webapp/autoDeploy/autodeploy/api.py | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/webapp/autoDeploy/autodeploy/api.py b/webapp/autoDeploy/autodeploy/api.py index 78969f4..ee395da 100644 --- a/webapp/autoDeploy/autodeploy/api.py +++ b/webapp/autoDeploy/autodeploy/api.py @@ -60,15 +60,16 @@ def deploy(request): link="http://"+server.DNS+project.deployment_link print link if project.emailUsers!="" or project.emailUsers!=" ": - for user in project.emailUsers.split(","): - Common.send(user,"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s"%(project.name,link),fromUser=None,cc="",bcc="",) +# for user in project.emailUsers.split(","): + Common.send(project.emailUsers.replace(",",";"),"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s"%(project.name,link),fromUser=None,cc="",bcc="",) return HttpResponse(res+",,"+link) else: print "in else" if project.emailUsers!="" or project.emailUsers!=" ": - for user in project.emailUsers.split(","): - Common.send(user,"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s"%(project.name,project.deployment_link),fromUser=None,cc="",bcc="",) + Common.send(project.emailUsers.replace(",",";"),"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s"%(project.name,link),fromUser=None,cc="",bcc="",) +# for user in project.emailUsers.split(","): + # Common.send(user,"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s"%(project.name,project.deployment_link),fromUser=None,cc="",bcc="",) return HttpResponse(res+",,"+project.deployment_link) - else: return HttpResponse(res) \ No newline at end of file + else: return HttpResponse(res) From e7bce505467f0d47db97cb942483972315b30678 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 22 Aug 2015 13:55:57 +0200 Subject: [PATCH 050/108] Fixed: Sending Emails --- webapp/autoDeploy/autodeploy/Common.py | 3 ++- webapp/autoDeploy/autodeploy/api.py | 8 +++----- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/webapp/autoDeploy/autodeploy/Common.py b/webapp/autoDeploy/autodeploy/Common.py index 77e7857..8ce1333 100644 --- a/webapp/autoDeploy/autodeploy/Common.py +++ b/webapp/autoDeploy/autodeploy/Common.py @@ -26,7 +26,8 @@ def send(to,subject,body,fromUser=None,cc="",bcc="",): server.ehlo() server.starttls() server.login(settings.SMTP["USERNAME"], settings.SMTP["PASSWORD"]) - server.sendmail(From, to, msg.as_string()) + for t in to.split(";"): + server.sendmail(From, t, msg.as_string()) if cc!="": server.sendmail(From, cc, msg.as_string()) if bcc!="": diff --git a/webapp/autoDeploy/autodeploy/api.py b/webapp/autoDeploy/autodeploy/api.py index ee395da..ee6416e 100644 --- a/webapp/autoDeploy/autodeploy/api.py +++ b/webapp/autoDeploy/autodeploy/api.py @@ -66,10 +66,8 @@ def deploy(request): return HttpResponse(res+",,"+link) else: print "in else" + link=project.deployment_link if project.emailUsers!="" or project.emailUsers!=" ": - Common.send(project.emailUsers.replace(",",";"),"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s"%(project.name,link),fromUser=None,cc="",bcc="",) -# for user in project.emailUsers.split(","): - # Common.send(user,"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s"%(project.name,project.deployment_link),fromUser=None,cc="",bcc="",) - - return HttpResponse(res+",,"+project.deployment_link) + Common.send(project.emailUsers.replace(",",";"),"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s"%(project.name,link),fromUser=None,cc="",bcc="",) + return HttpResponse(res+",,"+link) else: return HttpResponse(res) From 94f8b9b33114ebe459bae6533d2d862aca8d21d5 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 22 Aug 2015 14:19:39 +0200 Subject: [PATCH 051/108] Fixed issue in history in case of tags --- webapp/autoDeploy/autodeploy/views.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index f11977c..f8f76c7 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -312,8 +312,9 @@ def getProjectDepHistory(request): commits=c.getCommitsDiff(deployment.project.working_dir,deployment.update_version) print commits deployment.has_new_version = len(commits) - res.append(deployment) print deployment.server,deployment.has_new_version + res.append(deployment) + table=DeploymentHistory(res) RequestConfigReport(request, paginate={"per_page": 15}).configure(table) From ed09bf40729fe43f3fa8ab4bc6b8d831a8f943f2 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Thu, 10 Sep 2015 12:53:12 +0200 Subject: [PATCH 052/108] Fixed Issue with multiple checks that may cause too many connections --- webapp/autoDeploy/checkUpdates.py | 26 +++++++++++++++++++++++++ webapp/autoDeploy/templates/deploy.html | 2 +- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/webapp/autoDeploy/checkUpdates.py b/webapp/autoDeploy/checkUpdates.py index 80e7bc5..2326359 100755 --- a/webapp/autoDeploy/checkUpdates.py +++ b/webapp/autoDeploy/checkUpdates.py @@ -5,9 +5,35 @@ os.environ.setdefault("DJANGO_SETTINGS_MODULE", "autoDeploy.settings") django.setup() +def savePID(): + f=open('/var/run/autodeploy-check', "w") + f.write(str(os.getpid())) + f.close() + +def getPreviousPID(): + if not os.path.exists("/var/run/autodeploy-check"): return 0 + f=open('/var/run/autodeploy-check', "r") + return int(f.read().strip()) + +def check_pid(pid): + """ Check For the existence of a unix pid. """ + try: + os.kill(pid, 0) + except OSError: + return False + else: + return True + from autodeploy.models import * from autodeploy_client import Client +pid=getPreviousPID() +if pid!=0: + if check_pid(pid): + print "Another check is running, exiting...." + exit(-13) +savePID() + for project in Project.objects.all(): updateRequired=False print "Checking %s on %s"%(project.name,project.default_server.DNS) diff --git a/webapp/autoDeploy/templates/deploy.html b/webapp/autoDeploy/templates/deploy.html index ff81ba1..38ebe39 100644 --- a/webapp/autoDeploy/templates/deploy.html +++ b/webapp/autoDeploy/templates/deploy.html @@ -2,7 +2,7 @@ {% block content %}

    -

    Clone Project

    +

    Deploy Project

    {% csrf_token %} From c47bc0b5c4575b6b8eda0dd2fdbb81695b328562 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 14 May 2016 11:14:37 +0200 Subject: [PATCH 053/108] Fixed: Modify SSH Key, Set Default Server --- webapp/autoDeploy/autodeploy/forms.py | 3 ++- webapp/autoDeploy/autodeploy/views.py | 22 +++++++++++++-------- webapp/autoDeploy/templates/add_sshkey.html | 5 +++++ 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/webapp/autoDeploy/autodeploy/forms.py b/webapp/autoDeploy/autodeploy/forms.py index e6dcf9f..45fefca 100644 --- a/webapp/autoDeploy/autodeploy/forms.py +++ b/webapp/autoDeploy/autodeploy/forms.py @@ -44,7 +44,8 @@ def save(self,files,name): P.sshKey=self.cleaned_data["sshKey"] P.default_server=self.cleaned_data["default_server"] P.update_style=self.cleaned_data["update_style"] - P.emailUsers=self.clened_data["emailUsers"] + P.emailUsers=self.cleaned_data["emailUsers"] + print "Files is ",files f=files.get('cfile','') if f!="": diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index f8f76c7..446e253 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -89,13 +89,18 @@ def add_ssh_key(request): return render_to_response("add_sshkey.html", {"form": SSHKeyForm()}, context_instance=RequestContext(request)) else: form = SSHKeyForm(request.POST) - if form.is_valid(): - form.save() - return render_to_response("add_sshkey.html", {"form": form, "done": True}, - context_instance=RequestContext(request)) + if request.POST["edit"] == "True": + key=SSHKey.objects.get(name=request.POST["name"]) + key.key=request.POST["key"] + key.save() else: - return render_to_response("add_sshkey.html", {"form": form, "error": True}, + if form.is_valid(): + form.save() + else: + return render_to_response("add_sshkey.html", {"form": form, "error": True}, context_instance=RequestContext(request)) + return render_to_response("add_sshkey.html", {"form": form, "done": True}, + context_instance=RequestContext(request)) @csrf_protect @@ -103,7 +108,7 @@ def add_ssh_key(request): def clone(request): if request.method == "GET": project = Project.objects.get(name=request.GET["project"]) - return render_to_response("clone.html", {"form": CloneForm, "project_workdir": project.working_dir}, + return render_to_response("clone.html", {"form": CloneForm(initial={"server":project.default_server}), "project_workdir": project.working_dir}, context_instance=RequestContext(request)) else: project = Project.objects.get(name=request.POST["project"]) @@ -119,8 +124,9 @@ def clone(request): @csrf_protect def deploy(request): if request.method == "GET": + project = Project.objects.get(name=request.GET["project"]) request.session["deploy_project"] = request.GET["project"] - return render_to_response("deploy.html", {"form": CloneForm}, context_instance=RequestContext(request)) + return render_to_response("deploy.html", {"form": CloneForm(initial={"server":project.default_server})}, context_instance=RequestContext(request)) @login_required(redirect_field_name="redirect") def deploy2(request): @@ -174,7 +180,7 @@ def edit_ssh_key(request, sshKey): if request.method == "GET": key = SSHKey.objects.get(name=sshKey) form = SSHKeyForm(instance=key) - return render_to_response("add_sshkey.html", {"form": form}, context_instance=RequestContext(request)) + return render_to_response("add_sshkey.html", {"form": form,"edit":True}, context_instance=RequestContext(request)) @login_required(redirect_field_name="redirect") def edit_server(request, server): diff --git a/webapp/autoDeploy/templates/add_sshkey.html b/webapp/autoDeploy/templates/add_sshkey.html index e07b78d..ca14280 100644 --- a/webapp/autoDeploy/templates/add_sshkey.html +++ b/webapp/autoDeploy/templates/add_sshkey.html @@ -17,6 +17,11 @@
    {{ form.as_table }} + {% if edit %} + + {% else %} + + {% endif %}
    From eba023bcfb08e3661c1e7651fa4faaeeadd30a87 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 14 May 2016 12:23:28 +0200 Subject: [PATCH 054/108] Fixes #34, Fixes #35 --- client/autodeploy_client/Client.py | 11 +++++-- client/autodeploy_client/ClientJob.py | 14 +++++++++ exampleConfig/autodeploy.yaml | 2 +- server/Request.py | 28 ++++++++++++++++-- server/autodeploy-server.py | 23 +++++++++++++-- server/scm/BaseSCM.py | 2 +- server/scm/Git.py | 15 ++++++++-- .../migrations/0014_auto_20160514_1317.py | 25 ++++++++++++++++ webapp/autoDeploy/autodeploy/models.py | 2 +- webapp/autoDeploy/autodeploy/views.py | 29 ++++++++++++++----- .../media/AutoDeploy/autodeploy.yaml | 18 ++++++++++++ webapp/autoDeploy/templates/base.html | 7 +++-- webapp/autoDeploy/templates/deploy2.html | 18 +++++++++++- 13 files changed, 173 insertions(+), 21 deletions(-) create mode 100644 webapp/autoDeploy/autodeploy/migrations/0014_auto_20160514_1317.py create mode 100644 webapp/autoDeploy/media/AutoDeploy/autodeploy.yaml diff --git a/client/autodeploy_client/Client.py b/client/autodeploy_client/Client.py index 6ffd6f0..10646ba 100644 --- a/client/autodeploy_client/Client.py +++ b/client/autodeploy_client/Client.py @@ -59,6 +59,13 @@ def ListTags(self, workdir, owner=''): return newlist else: return [] + def ListBranchs(self,workdir,owner=''): + global msg + if owner == '': + owner = Config.Owner + msg = Job.createGetBranchs(workdir=workdir, scm=self.scm, owner=owner) + result = self._send(msg) + return result.split("\n") def SwitchTag(self, workdir, tag, owner=''): global msg if owner == '': @@ -78,10 +85,10 @@ def Deploy(self, workdir, configFile, owner=''): def CheckUp(self): return Connect.connect(self.server, self.port, 5) - def ListCommits(self, workdir, page=0, rpp=10, owner=''): + def ListCommits(self, workdir, page=0, rpp=10, owner='',options=None): if owner == '': owner = Config.Owner - msg = Job.createListCommitsMessage(workdir=workdir, scm=self.scm, owner=owner,key=self.sshkey) + msg = Job.createListCommitsMessage(workdir=workdir, scm=self.scm, owner=owner,key=self.sshkey,options=options) res = self._send(msg) result = [] #HEAD = True diff --git a/client/autodeploy_client/ClientJob.py b/client/autodeploy_client/ClientJob.py index 6d3ae14..2d410b6 100644 --- a/client/autodeploy_client/ClientJob.py +++ b/client/autodeploy_client/ClientJob.py @@ -13,6 +13,20 @@ def importKey(): return key +def createGetBranchs(workdir, scm, owner,options=None): + sec = base64.encodestring(importKey().encrypt(owner + scm + "LIST-BRNACHS", "")[0]) + f = '\n' % (owner, "LIST-BRNACHS", sec, scm) + f += '%s' % workdir + + if options: + f += '' + for option in options.keys(): + f += "" % (option, options[option]) + + f += "" + f += '' + return f + # Provide id, owner and command as string # inputsFiles as List of file path diff --git a/exampleConfig/autodeploy.yaml b/exampleConfig/autodeploy.yaml index c40b39e..f0ee7f2 100644 --- a/exampleConfig/autodeploy.yaml +++ b/exampleConfig/autodeploy.yaml @@ -11,7 +11,7 @@ permissions: events: beforeInstall: - - location: "/bin/rm -r /var/www/autodeploy" + - location: "/bin/rm -rf /var/www/autodeploy" afterInstall: - location: "/var/www/autodeploy/manage.py runserver 0.0.0.0:9002 &" interpreter: python diff --git a/server/Request.py b/server/Request.py index 3c3ae18..597e820 100755 --- a/server/Request.py +++ b/server/Request.py @@ -67,6 +67,26 @@ def parseListTagsJob(message): return params +def parseListBranchsJob(message): + params = {} + optionsDict = {} + doc = xml.dom.minidom.parseString(message) + Job = doc.getElementsByTagName('job')[0] + scm=Job.getAttribute("scm") + workdir= getValue(Job, 'workdir') + + requestType = Job.getAttribute('type') + owner = Job.getAttribute('owner') + """options = (Job.getElementsByTagName('option')) + for option in options: + name = option.getAttribute("name") + optionsDict[name] = option.firstChild.nodeValue + """ + print 'Recieved New Job from ' + owner + '.....' + params = {"workdir": workdir,"owner": owner, "requestType": requestType,"scm":scm,"options": optionsDict} + return params + + def parseSwitchTagJob(message): params = {} optionsDict = {} @@ -122,8 +142,12 @@ def parseGetCommitsJob(message): requestType = Job.getAttribute('type') key= getValue(Job, 'sshkey') owner = Job.getAttribute('owner') - params = {"workdir": workdir,"owner": owner, "requestType": requestType,"key":key, - "scm":scm,"options": optionsDict} + options = (Job.getElementsByTagName('option')) + for option in options: + name = option.getAttribute("name") + optionsDict[name] = option.firstChild.nodeValue + params = {"workdir": workdir, "owner": owner, "requestType": requestType, "key": key, + "scm": scm, "options": optionsDict} return params diff --git a/server/autodeploy-server.py b/server/autodeploy-server.py index 6c6f321..b90b004 100755 --- a/server/autodeploy-server.py +++ b/server/autodeploy-server.py @@ -102,13 +102,32 @@ def HandleClient(clientsock): pass Response.sendData(clientsock,"\n".join(result)) return - + elif req["requestType"] == "LIST-BRNACHS": + job = Request.parseListBranchsJob(msg) + if job["scm"] == "git": + gclient = git.GIT(workdir=job["workdir"]) + cmd = gclient.get_list_branches() + result = [] + res = Common.run(cmd) + print res + if "ERR:" in res: + Response.sendData(clientsock, res) + else: + for line in res.split("\n"): + try: + if line!="": + result.append(line.replace("*","").strip()) + except: + pass + print result + Response.sendData(clientsock, "\n".join(result)) + return elif req["requestType"]=="LIST-COMMITS": job = Request.parseGetCommitsJob(msg) if job["scm"]=="git": gclient=git.GIT(workdir=job["workdir"]) gclient.setKey(job["key"]) - cmd=gclient.get_history_cmd() + cmd=gclient.get_history_cmd(job["options"]) elif req["requestType"]=="SWITCH-TAG": job = Request.parseSwitchTagJob(msg) if job["scm"]=="git": diff --git a/server/scm/BaseSCM.py b/server/scm/BaseSCM.py index 4b40920..07d1ed4 100644 --- a/server/scm/BaseSCM.py +++ b/server/scm/BaseSCM.py @@ -10,7 +10,7 @@ def get_list_tags_cmd(self): pass def get_switch_to_tag_cmd(self): pass - def get_history_cmd(self,page=0,rpp=10): + def get_history_cmd(self,page=0,rpp=10,options={}): pass def switch_to_histroy_cmd(self,commit): pass diff --git a/server/scm/Git.py b/server/scm/Git.py index 81f2fae..a815716 100644 --- a/server/scm/Git.py +++ b/server/scm/Git.py @@ -22,10 +22,21 @@ def get_pull_cmd(self): return "cd %s; git pull"%self.workdir def get_list_tags_cmd(self): return "cd %s;git tag -l"%self.workdir + + def get_list_branches(self): + return "cd %s;git branch -a" % self.workdir + def get_switch_to_tag_cmd(self,tag): return "cd %s; git checkout tags/%s"%(self.workdir,tag) - def get_history_cmd(self): - return 'cd ' + self.workdir +'; git log --all --pretty=format:"%H,,%h,,%an,,%ar,,%s,,%cd" | cat -' + def get_history_cmd(self,options={}): + branch=options.get("branch","") + cmd = 'cd ' + self.workdir +'; git log ' + if branch!="": + cmd += branch + else: + cmd+= ' --all ' + cmd += ' --pretty=format:"%H,,%h,,%an,,%ar,,%s,,%cd" | cat -' + return cmd def switch_to_histroy_cmd(self,commit): return 'cd %s; git reset --hard %s'%(self.workdir,commit) def commit_diff_cmd(self,commit): diff --git a/webapp/autoDeploy/autodeploy/migrations/0014_auto_20160514_1317.py b/webapp/autoDeploy/autodeploy/migrations/0014_auto_20160514_1317.py new file mode 100644 index 0000000..17f275e --- /dev/null +++ b/webapp/autoDeploy/autodeploy/migrations/0014_auto_20160514_1317.py @@ -0,0 +1,25 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime + + +class Migration(migrations.Migration): + + dependencies = [ + ('autodeploy', '0013_auto_20150817_1250'), + ] + + operations = [ + migrations.AlterField( + model_name='project', + name='lastCommit', + field=models.CharField(max_length=50, blank=True), + ), + migrations.AlterField( + model_name='project', + name='lastUpdate', + field=models.DateTimeField(default=datetime.datetime(2016, 5, 14, 13, 17, 34, 809478), blank=True), + ), + ] diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index 7ffd1a8..242ea3d 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -30,7 +30,7 @@ class Project(models.Model): repo = models.CharField(max_length=255, blank=True) default_server=models.ForeignKey(Server,blank=True) update_style=models.CharField(max_length=10,blank=True) - lastCommit = models.CharField(max_length=32,blank=True) + lastCommit = models.CharField(max_length=50,blank=True) lastTag=models.CharField(max_length=255,blank=True) lastCommitDate = models.DateTimeField(blank=True,default="1970-01-01") working_dir=models.FileField(blank=True) diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 446e253..2484ccb 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -147,7 +147,8 @@ def deploy2(request): if project.update_style=="tag": return listTags(request, server) else: - return listCommits(request) + filter=request.GET.get("filter",None) + return listCommits(request,filter) @login_required(redirect_field_name="redirect") def listTags(request, server): @@ -273,29 +274,43 @@ def checkServersStatus(request): return render_to_response("base.html", {"title":"Servers Health","function":"checkServers","dataType":"JSON","data":"","ajax": True}, context_instance=RequestContext(request)) @login_required(redirect_field_name="redirect") -def listCommits(request): +def listCommits(request,filter=None): #if request.method == "GET": res = None + branches=[] + c=None + server=None + project=None print request.GET.get("refresh","False") if request.GET.get("refresh","False")=="True": if "commits" in request.session: - del request.session["commits"] + request.session.pop("commits","") + request.session.pop("branchs","") return redirect("./listCommits") - if not "commits" in request.session: + if filter or not "commits" in request.session: server = Server.objects.get(name=request.session["deploy_server"]) project = Project.objects.get(name=request.session["deploy_project"]) c = Client("git", server.ip, server.port,key=project.sshKey.key) c.Pull(project.repo,project.working_dir,project.sshKey.key) - res = c.ListCommits(project.working_dir) - print res + res = c.ListCommits(project.working_dir,options={"branch":filter}) request.session["commits"] = res else: res = request.session["commits"] + + if not "branchs" in request.session: + if not c: + server = Server.objects.get(name=request.session["deploy_server"]) + project = Project.objects.get(name=request.session["deploy_project"]) + c = Client("git", server.ip, server.port, key=project.sshKey.key) + branches=c.ListBranchs(project.working_dir) + else: + branches=request.session["branchs"] + request.session["branchs"]=branches table = CommitTable(res) table_to_report = RequestConfig(request, paginate={"per_page": 15}).configure(table) if table_to_report: return create_report_http_response(table_to_report, request) - return render_to_response("deploy2.html", {"mode":"commits","commits": table}, context_instance=RequestContext(request)) + return render_to_response("deploy2.html", {"mode":"commits","commits": table,"branchs":branches,"current_branch":filter}, context_instance=RequestContext(request)) @login_required(redirect_field_name="redirect") diff --git a/webapp/autoDeploy/media/AutoDeploy/autodeploy.yaml b/webapp/autoDeploy/media/AutoDeploy/autodeploy.yaml new file mode 100644 index 0000000..f0ee7f2 --- /dev/null +++ b/webapp/autoDeploy/media/AutoDeploy/autodeploy.yaml @@ -0,0 +1,18 @@ +files: + - source: /webapp/autoDeploy/* + destination: /var/www/autodeploy/ + +permissions: + - object: /var/www/autodeploy/ + owner: mohamed + group: users + mode: 755 + type: directory + +events: + beforeInstall: + - location: "/bin/rm -rf /var/www/autodeploy" + afterInstall: + - location: "/var/www/autodeploy/manage.py runserver 0.0.0.0:9002 &" + interpreter: python + wait: False diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 5d52655..6935a2a 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -22,8 +22,11 @@ $.ajax({url:"{{ BASE_URL }}api/{{ function }}","method":"GET","dataType":"{{ dataType }}", success:function(data) { {{ function }}(data) - }{% if data != "" %},data:{{ data|safe }} {% endif %} - + },error:function (data) { + renderResult(data.responseText,"Error") + } + {% if data != "" %},data:{{ data|safe }} {% endif %} + }) {% endif %} diff --git a/webapp/autoDeploy/templates/deploy2.html b/webapp/autoDeploy/templates/deploy2.html index a4a4861..120f423 100644 --- a/webapp/autoDeploy/templates/deploy2.html +++ b/webapp/autoDeploy/templates/deploy2.html @@ -1,6 +1,13 @@ {% extends "base.html"%} {% load render_table from django_tables2 %} - +{% block head %} + +{% endblock %} {% block content %}
    @@ -25,6 +32,15 @@

    List of Tags Show Commits List of Commits Show Tags

    + {% if branchs|length > 1 %} + Filter By Branch: + {% endif %}
    {% render_table commits %}
    From d86ffef22509fe81adaadc02b4b92fbf07498820 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 14 May 2016 13:51:11 +0200 Subject: [PATCH 055/108] Sending Changes to the users by email --- client/autodeploy_client/Client.py | 11 +++++++ client/autodeploy_client/ClientJob.py | 13 +++++++++ server/Config.cfg | 2 +- server/Request.py | 22 +++++++++++++- server/autodeploy-server.py | 20 +++++++++++++ server/scm/Git.py | 3 ++ webapp/autoDeploy/autodeploy/api.py | 29 +++++++++++++++++-- webapp/autoDeploy/autodeploy/models.py | 3 ++ .../media/AutoDeploy/autodeploy.yaml | 18 ------------ 9 files changed, 98 insertions(+), 23 deletions(-) delete mode 100644 webapp/autoDeploy/media/AutoDeploy/autodeploy.yaml diff --git a/client/autodeploy_client/Client.py b/client/autodeploy_client/Client.py index 10646ba..3bed9a1 100644 --- a/client/autodeploy_client/Client.py +++ b/client/autodeploy_client/Client.py @@ -125,4 +125,15 @@ def getCommitsDiff(self,workdir,commit,owner=''): for item in res.split("\n"): if item=="" or item=="Done" : continue result.append(item) + return result + + def getChangeLog(self, workdir, since,to, owner=''): + if owner == '': + owner = Config.Owner + msg = Job.createGetChangeLog(owner, workdir, self.scm,options={"since":since,"to":to}) + res = self._send(msg) + result = [] + for item in res.split("\n"): + if item == "" or item == "Done": continue + result.append(item) return result \ No newline at end of file diff --git a/client/autodeploy_client/ClientJob.py b/client/autodeploy_client/ClientJob.py index 2d410b6..fa6d7ac 100644 --- a/client/autodeploy_client/ClientJob.py +++ b/client/autodeploy_client/ClientJob.py @@ -150,6 +150,19 @@ def creategetCommitsDiffMessage(owner, workdir, commit, scm,options=None): f += '%s'%workdir f += '%s'%commit + if options: + f += '' + for option in options.keys(): + f += "" % (option, options[option]) + + f += "" + f += '' + return f + +def createGetChangeLog(owner,workdir,scm,options=None): + sec = base64.encodestring(importKey().encrypt(owner + scm + "LIST-CHANGES", "")[0]) + f = '\n' % (owner, "LIST-CHANGES", sec, scm) + f += '%s' % workdir if options: f += '' for option in options.keys(): diff --git a/server/Config.cfg b/server/Config.cfg index c836575..34fc44c 100755 --- a/server/Config.cfg +++ b/server/Config.cfg @@ -1,4 +1,4 @@ [Server] port: 4567 -publicKey: /home/mohamed/autoDeploy/autoDeploy/server/client.pub +publicKey: /home/mohamed/AutoDeploy/server/client.pub diff --git a/server/Request.py b/server/Request.py index 597e820..a115d9c 100755 --- a/server/Request.py +++ b/server/Request.py @@ -173,4 +173,24 @@ def parseSwitchCommitJob(message): def parseGetCommitDiff(message): - return parseSwitchCommitJob(message) \ No newline at end of file + return parseSwitchCommitJob(message) + +def parseGetChangeLog(message): + params = {} + optionsDict = {} + doc = xml.dom.minidom.parseString(message) + Job = doc.getElementsByTagName('job')[0] + scm = Job.getAttribute("scm") + workdir = getValue(Job, 'workdir') + + requestType = Job.getAttribute('type') + owner = Job.getAttribute('owner') + options = (Job.getElementsByTagName('option')) + for option in options: + name = option.getAttribute("name") + optionsDict[name] = option.firstChild.nodeValue + + print 'Recieved New Job from ' + owner + '.....' + params = {"workdir": workdir, "owner": owner, "requestType": requestType, + "scm": scm, "options": optionsDict} + return params \ No newline at end of file diff --git a/server/autodeploy-server.py b/server/autodeploy-server.py index b90b004..9e99c29 100755 --- a/server/autodeploy-server.py +++ b/server/autodeploy-server.py @@ -143,6 +143,26 @@ def HandleClient(clientsock): if job["scm"]=="git": gclient=git.GIT(workdir=job["workdir"]) cmd=gclient.commit_diff_cmd(commit=job["commit"]) + + elif req["requestType"]=="LIST-CHANGES": + job = Request.parseGetChangeLog(msg) + if job["scm"] == "git": + gclient = git.GIT(workdir=job["workdir"]) + cmd = gclient.get_changelog(since=job["options"]["since"], to=job["options"]["to"]) + result = [] + res = Common.run(cmd) + print res + if "ERR:" in res: + Response.sendData(clientsock, res) + else: + for line in res.split("\n"): + try: + if line != "": + result.append(line.replace("*", "").strip()) + except: + pass + print result + Response.sendData(clientsock, "\n".join(result)) elif req["requestType"]=="DEPLOY": print msg job = Request.parseDeployJob(msg) diff --git a/server/scm/Git.py b/server/scm/Git.py index a815716..4498610 100644 --- a/server/scm/Git.py +++ b/server/scm/Git.py @@ -42,3 +42,6 @@ def switch_to_histroy_cmd(self,commit): def commit_diff_cmd(self,commit): Common.run(self.get_pull_cmd()) return 'git rev-list %s..HEAD'%(commit) + def get_changelog(self,since,to): + return "cd %s;git shortlog %s..%s"%(self.workdir,since,to) + diff --git a/webapp/autoDeploy/autodeploy/api.py b/webapp/autoDeploy/autodeploy/api.py index ee6416e..cac9641 100644 --- a/webapp/autoDeploy/autodeploy/api.py +++ b/webapp/autoDeploy/autodeploy/api.py @@ -31,6 +31,7 @@ def deploy(request): import Common server = Server.objects.get(name=request.session["deploy_server"]) project = Project.objects.get(name=request.session["deploy_project"]) + last_Deployment=Deployment_Server.objects.filter(server=server,project=project).latest() D= Deployment_Server() c = Client(str(project.repo_type), server.ip, server.port) D.project = project @@ -60,14 +61,36 @@ def deploy(request): link="http://"+server.DNS+project.deployment_link print link if project.emailUsers!="" or project.emailUsers!=" ": -# for user in project.emailUsers.split(","): - Common.send(project.emailUsers.replace(",",";"),"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s"%(project.name,link),fromUser=None,cc="",bcc="",) + changes=c.getChangeLog(project.working_dir,since=last_Deployment.update_version,to=request.GET["commit"]) + changes_text="

    Changes

      " + found=False + for change in changes: + if change.endswith(":"): continue + changes_text+="
    • %s
    • "%change + found=True + if found: + changes_text+="
    " + else: + changes_text="" + Common.send(project.emailUsers.replace(",",";"),"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s
    %s"%(project.name,link,changes_text),fromUser=None,cc="",bcc="",) return HttpResponse(res+",,"+link) else: print "in else" link=project.deployment_link if project.emailUsers!="" or project.emailUsers!=" ": - Common.send(project.emailUsers.replace(",",";"),"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s"%(project.name,link),fromUser=None,cc="",bcc="",) + changes=c.getChangeLog(project.working_dir,since=last_Deployment.update_version,to=request.GET["commit"]) + changes_text="

    Changes

      " + found=False + for change in changes: + if change.endswith(":"): continue + changes_text+="
    • %s
    • "%change + found=True + if found: + changes_text += "
    " + else: + changes_text = "" + + Common.send(project.emailUsers.replace(",",";"),"New version of %s deployed"%project.name,"Dear User,
    This is an automated notification that a new version of %s has been deployed at: %s.
    %s"%(project.name,link,changes_text),fromUser=None,cc="",bcc="",) return HttpResponse(res+",,"+link) else: return HttpResponse(res) diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index 242ea3d..15d32a9 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -55,6 +55,9 @@ class Deployment_Server(models.Model): project = models.ForeignKey(Project) server = models.ForeignKey(Server) + class Meta: + get_latest_by="id" + class Plugins(models.Model): name=models.CharField(max_length=50) settings=models.TextField() diff --git a/webapp/autoDeploy/media/AutoDeploy/autodeploy.yaml b/webapp/autoDeploy/media/AutoDeploy/autodeploy.yaml deleted file mode 100644 index f0ee7f2..0000000 --- a/webapp/autoDeploy/media/AutoDeploy/autodeploy.yaml +++ /dev/null @@ -1,18 +0,0 @@ -files: - - source: /webapp/autoDeploy/* - destination: /var/www/autodeploy/ - -permissions: - - object: /var/www/autodeploy/ - owner: mohamed - group: users - mode: 755 - type: directory - -events: - beforeInstall: - - location: "/bin/rm -rf /var/www/autodeploy" - afterInstall: - - location: "/var/www/autodeploy/manage.py runserver 0.0.0.0:9002 &" - interpreter: python - wait: False From 8000d671bba22e5a59ffc33420918d4e1e82d875 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 14 May 2016 15:07:19 +0300 Subject: [PATCH 056/108] Update Installation.md --- Installation.md | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/Installation.md b/Installation.md index c0006f1..f058633 100644 --- a/Installation.md +++ b/Installation.md @@ -2,6 +2,8 @@ This document shows how to install autoDeploy on Ubuntu System +# Install Server + * Create an autodeploy user ```sh # adduser --system --home /opt/autodeploy/home --shell /bin/bash autodeploy @@ -10,21 +12,17 @@ This document shows how to install autoDeploy on Ubuntu System ```sh # adduser autodeploy sudo ``` +* Download The latest release from [github](https://github.com/mkalioby/AutoDeploy/releases) +* Expand the downloaded archive to '/opt/autodeploy/home' * Copy the file in UnixConfig to /etc/sudoers.d/ * Install the Client Library ```sh # python setup.py install ``` - -* Install pyCrypto -```sh -# pip install python-pycrypto -``` - -* Install yaml +* Install pyCrypto and pyYAML ```sh -# pip install pyyaml +# pip install python-pycrypto pyyaml ``` * Edit Server init script so that it points to installation directory @@ -35,18 +33,27 @@ This document shows how to install autoDeploy on Ubuntu System sudo update-rc.d autodeploy-server start ``` +# Install Web Application + +* Install required Packages +```sh +sudo pip install django==1.8 django-tables2==1.0.4 django-tables2-reports +``` + * Configure your database - * Edit Settings file. - * Create empty database in your DBMS. + * Create empty database in your DBMS. + * Edit Settings file in `webapp/autoDeploy/settings.py`. + +* Create Database by ```sh python manage.py migrate ``` -* Start Django Sever +1. Start Django Sever ```sh python manage.py runserver IP:PORT ``` -A Guide to show how to configure autodeploy Django webapp with Apache should be done. +TBD: A Guide to show how to configure autodeploy Django webapp with Apache should be done. From a9ddf91b99d78e98ff67920cdd1a97f2310ec1fd Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 14 May 2016 15:08:21 +0300 Subject: [PATCH 057/108] Update Installation.md --- Installation.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Installation.md b/Installation.md index f058633..d38c442 100644 --- a/Installation.md +++ b/Installation.md @@ -30,14 +30,14 @@ This document shows how to install autoDeploy on Ubuntu System * Copy server init script to /etc/init.d * Add the init script to the start defaults ```sh -sudo update-rc.d autodeploy-server start +# update-rc.d autodeploy-server start ``` # Install Web Application * Install required Packages ```sh -sudo pip install django==1.8 django-tables2==1.0.4 django-tables2-reports +# pip install django==1.8 django-tables2==1.0.4 django-tables2-reports ``` * Configure your database @@ -46,7 +46,7 @@ sudo pip install django==1.8 django-tables2==1.0.4 django-tables2-reports * Create Database by ```sh -python manage.py migrate +$ python manage.py migrate ``` 1. Start Django Sever ```sh From 025cb123aeff014a244d484b75c804bbde619c14 Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 2 Jul 2016 15:44:08 +0300 Subject: [PATCH 058/108] Add Stackshare --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index f99d341..7ede1ec 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ # AutoDeploy Buildong an automated deployment system which is similar to AWS CodeDeploy but is hostable inside enterprise. +[![StackShare](http://img.shields.io/badge/tech-stack-0690fa.svg?style=flat)](http://stackshare.io/mkalioby/autodeploy) The target is to minimize the manual prone errors of code deployment. From 1a158b0912f7ca5edb5eef207735913b212a0fff Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Sat, 2 Jul 2016 15:44:50 +0300 Subject: [PATCH 059/108] Update README.md --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7ede1ec..1d6170a 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,9 @@ # AutoDeploy -Buildong an automated deployment system which is similar to AWS CodeDeploy but is hostable inside enterprise. + [![StackShare](http://img.shields.io/badge/tech-stack-0690fa.svg?style=flat)](http://stackshare.io/mkalioby/autodeploy) +Buildong an automated deployment system which is similar to AWS CodeDeploy but is hostable inside enterprise. + The target is to minimize the manual prone errors of code deployment. The project will have the following componemts: From d4ecf8091f665453d055f75ad31cf829f4f764ef Mon Sep 17 00:00:00 2001 From: Mohamed El-Kalioby Date: Tue, 11 Oct 2016 22:19:56 +0200 Subject: [PATCH 060/108] Fixing issue where server can't detect EOM --- server/autodeploy-server.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/server/autodeploy-server.py b/server/autodeploy-server.py index b90b004..9c0891e 100755 --- a/server/autodeploy-server.py +++ b/server/autodeploy-server.py @@ -49,7 +49,10 @@ def HandleClient(clientsock): cmd="" while 1: buf = clientsock.recv(2048) - chunks.append(str(buf)) + if len(buf)<6: + chunks[-1]+=buf + else: + chunks.append(str(buf)) if (EOM in chunks[-1]): msg = "".join(chunks)[:-5] if debug: print msg From d395df73a47e3a1b85fcc01fdf54752dced61348 Mon Sep 17 00:00:00 2001 From: Mohamed ElKalioby Date: Sun, 17 Sep 2017 12:38:17 +0300 Subject: [PATCH 061/108] Added deployed Column --- .gitignore | 2 +- webapp/autoDeploy/autodeploy/models.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index ba74660..5bed1c6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,7 @@ # Byte-compiled / optimized / DLL files __pycache__/ *.py[cod] - +.idea* # C extensions *.so diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index 15d32a9..70f53ee 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -54,7 +54,7 @@ class Deployment_Server(models.Model): has_new_version = models.IntegerField(verbose_name="Updates Behind") project = models.ForeignKey(Project) server = models.ForeignKey(Server) - + deployed=models.BooleanField(default=True) class Meta: get_latest_by="id" From ca63b935c69ac6097bbf7b94bab60ab9de3602f0 Mon Sep 17 00:00:00 2001 From: Mohamed ElKalioby Date: Mon, 18 Sep 2017 15:53:21 +0300 Subject: [PATCH 062/108] Moved to Django Emailer --- webapp/autoDeploy/autoDeploy/settings.py | 14 +++---- webapp/autoDeploy/autodeploy/Common.py | 48 +++++++----------------- 2 files changed, 19 insertions(+), 43 deletions(-) diff --git a/webapp/autoDeploy/autoDeploy/settings.py b/webapp/autoDeploy/autoDeploy/settings.py index 805baf0..75844ff 100644 --- a/webapp/autoDeploy/autoDeploy/settings.py +++ b/webapp/autoDeploy/autoDeploy/settings.py @@ -120,11 +120,9 @@ LOGIN_URL=BASE_URL+"accounts/login" -SMTP= { - 'HOST': 'smtp.gmail.com', - 'PORT': '587', - 'USERNAME': '', - 'PASSWORD': '', - 'FROM':'Auto Deploy' - - } \ No newline at end of file +EMAIL_HOST= 'smtp.gmail.com' +EMAIL_PORT= 587 +EMAIL_HOST_USER= '' +EMAIL_HOST_PASSWORD='' +EMAIL_USE_TLS=True +EMAIL_FROM="AutoDeploy" diff --git a/webapp/autoDeploy/autodeploy/Common.py b/webapp/autoDeploy/autodeploy/Common.py index 8ce1333..2cdb82b 100644 --- a/webapp/autoDeploy/autodeploy/Common.py +++ b/webapp/autoDeploy/autodeploy/Common.py @@ -1,39 +1,17 @@ __author__ = 'mohamed' def send(to,subject,body,fromUser=None,cc="",bcc="",): - from django.conf import settings - import smtplib - from email.mime.multipart import MIMEMultipart - from email.mime.text import MIMEText - From=fromUser - if fromUser==None: - From="%s<%s>"%(settings.SMTP["FROM"],settings.SMTP["USERNAME"]) - try: - msg = MIMEMultipart('alternative') - msg['Subject'] = subject - msg['From'] = From - #msg['To'] = to one email - msg['Cc']= cc - if type(to)==type([]): - msg['To'] = ', '.join( to) #More than one email - else: - msg['To'] = to - html = body - part2 = MIMEText(html, 'html') - msg.attach(part2) - server = smtplib.SMTP(settings.SMTP["HOST"],settings.SMTP["PORT"]) - server.ehlo() - server.starttls() - server.login(settings.SMTP["USERNAME"], settings.SMTP["PASSWORD"]) - for t in to.split(";"): - server.sendmail(From, t, msg.as_string()) - if cc!="": - server.sendmail(From, cc, msg.as_string()) - if bcc!="": - server.sendmail(From, bcc, msg.as_string()) - server.quit() - return True - - except Exception as exp: - return False + from django.core.mail import EmailMessage + From = "%s<%s>" % (fromUser, settings.EMAIL_HOST_USER) + if fromUser == None: + From = "%s<%s>" % (settings.EMAIL_FROM, settings.EMAIL_HOST_USER) + if type(to) != type([]): + to = [to] + email = EmailMessage( + subject, + body, + From, + to, cc=cc, bcc=bcc) + email.content_subtype = "html" + return email.send(True) From e972b65561c831bf62bd842dd3e4982eadbf135a Mon Sep 17 00:00:00 2001 From: Mohamed ElKalioby Date: Wed, 22 Nov 2017 10:38:59 +0300 Subject: [PATCH 063/108] Handle an error when this is the first deployment --- webapp/autoDeploy/autodeploy/api.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/webapp/autoDeploy/autodeploy/api.py b/webapp/autoDeploy/autodeploy/api.py index cac9641..55dc637 100644 --- a/webapp/autoDeploy/autodeploy/api.py +++ b/webapp/autoDeploy/autodeploy/api.py @@ -31,7 +31,11 @@ def deploy(request): import Common server = Server.objects.get(name=request.session["deploy_server"]) project = Project.objects.get(name=request.session["deploy_project"]) - last_Deployment=Deployment_Server.objects.filter(server=server,project=project).latest() + last_Deployment=None + try: + last_Deployment=Deployment_Server.objects.filter(server=server,project=project).latest() + except: + pass D= Deployment_Server() c = Client(str(project.repo_type), server.ip, server.port) D.project = project @@ -60,7 +64,7 @@ def deploy(request): print "in if" link="http://"+server.DNS+project.deployment_link print link - if project.emailUsers!="" or project.emailUsers!=" ": + if project.emailUsers!="" or project.emailUsers!=" " and last_Deployment!=None: changes=c.getChangeLog(project.working_dir,since=last_Deployment.update_version,to=request.GET["commit"]) changes_text="

    Changes

      " found=False From 82c86a7b0e18ed1e482b6142cb72cf860b62d15f Mon Sep 17 00:00:00 2001 From: Mohamed ElKalioby Date: Thu, 23 Nov 2017 10:22:54 +0300 Subject: [PATCH 064/108] List number of commits to return by a config --- server/Config.cfg | 4 +++- server/autodeploy-server.py | 8 ++++---- server/config.py | 4 ++++ server/scm/Git.py | 9 ++++----- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/server/Config.cfg b/server/Config.cfg index 34fc44c..e8e19dc 100755 --- a/server/Config.cfg +++ b/server/Config.cfg @@ -1,4 +1,6 @@ [Server] port: 4567 -publicKey: /home/mohamed/AutoDeploy/server/client.pub +publicKey: /home/shgpuser/dev/AutoDeploy/server/client.pub +[MISC] +log_limit: 30 \ No newline at end of file diff --git a/server/autodeploy-server.py b/server/autodeploy-server.py index e4a1483..e2420a3 100755 --- a/server/autodeploy-server.py +++ b/server/autodeploy-server.py @@ -42,6 +42,7 @@ def validReq(req): def HandleClient(clientsock): + import config name = threading.currentThread().getName() print name, ' Started.............' global EOM @@ -112,7 +113,6 @@ def HandleClient(clientsock): cmd = gclient.get_list_branches() result = [] res = Common.run(cmd) - print res if "ERR:" in res: Response.sendData(clientsock, res) else: @@ -122,7 +122,7 @@ def HandleClient(clientsock): result.append(line.replace("*","").strip()) except: pass - print result + #print result Response.sendData(clientsock, "\n".join(result)) return elif req["requestType"]=="LIST-COMMITS": @@ -130,7 +130,7 @@ def HandleClient(clientsock): if job["scm"]=="git": gclient=git.GIT(workdir=job["workdir"]) gclient.setKey(job["key"]) - cmd=gclient.get_history_cmd(job["options"]) + cmd=gclient.get_history_cmd(job["options"],limit=config.log_limit) elif req["requestType"]=="SWITCH-TAG": job = Request.parseSwitchTagJob(msg) if job["scm"]=="git": @@ -178,7 +178,7 @@ def HandleClient(clientsock): if cmd!="": print cmd res=Common.run(cmd) - print res + Response.sendData(clientsock,res) if debug: print "Ended,",res diff --git a/server/config.py b/server/config.py index 33da8ff..88c78ac 100755 --- a/server/config.py +++ b/server/config.py @@ -11,3 +11,7 @@ publicKey=config.get('Server', 'publicKey') port=config.get('Server', 'port') +try: + log_limit=config.get('MISC', 'log_limit') +except: + log_limit=100 diff --git a/server/scm/Git.py b/server/scm/Git.py index 4498610..b31028f 100644 --- a/server/scm/Git.py +++ b/server/scm/Git.py @@ -28,13 +28,12 @@ def get_list_branches(self): def get_switch_to_tag_cmd(self,tag): return "cd %s; git checkout tags/%s"%(self.workdir,tag) - def get_history_cmd(self,options={}): + def get_history_cmd(self,options={},limit=0): branch=options.get("branch","") cmd = 'cd ' + self.workdir +'; git log ' - if branch!="": - cmd += branch - else: - cmd+= ' --all ' + if limit!=0: cmd+= "-n %s "%limit + if branch!="": cmd += branch + else: cmd+= ' --all ' cmd += ' --pretty=format:"%H,,%h,,%an,,%ar,,%s,,%cd" | cat -' return cmd def switch_to_histroy_cmd(self,commit): From 6d74df1b6d52fe0a1d3c3d3c5464ca5698fd0bf4 Mon Sep 17 00:00:00 2001 From: Mohamed ElKalioby Date: Thu, 23 Nov 2017 10:27:55 +0300 Subject: [PATCH 065/108] Full Bootstrap support, added Default Branch --- webapp/autoDeploy/autodeploy/forms.py | 14 ++++--- .../migrations/0015_auto_20171123_0937.py | 39 +++++++++++++++++++ webapp/autoDeploy/autodeploy/models.py | 3 +- webapp/autoDeploy/autodeploy/views.py | 5 ++- webapp/autoDeploy/templates/deploy2.html | 14 ++++++- 5 files changed, 66 insertions(+), 9 deletions(-) create mode 100644 webapp/autoDeploy/autodeploy/migrations/0015_auto_20171123_0937.py diff --git a/webapp/autoDeploy/autodeploy/forms.py b/webapp/autoDeploy/autodeploy/forms.py index 45fefca..c9144d9 100644 --- a/webapp/autoDeploy/autodeploy/forms.py +++ b/webapp/autoDeploy/autodeploy/forms.py @@ -19,14 +19,17 @@ def saveFile(file,project_name): class ProjectsForm(forms.ModelForm): working_dir=forms.CharField(label="Working Directory",widget=forms.TextInput(attrs={'class':'form-control','size':30})) - repo_type=forms.ChoiceField(choices=repo_type,label="Repo Type") - update_style=forms.ChoiceField(choices=update_style,label="Update Style") + repo_type=forms.ChoiceField(choices=repo_type,label="Repo Type",widget=forms.Select(attrs={"class":"form-control"})) + update_style=forms.ChoiceField(choices=update_style,label="Update Style",widget=forms.Select(attrs={"class":"form-control"})) cfile=forms.FileField(label="Config File") name = forms.CharField(label='Project Name',widget=forms.TextInput(attrs={'class':'form-control','size':30})) repo_link= forms.CharField(label='Repo Link',widget=forms.TextInput(attrs={'class':'form-control','size':30})) repo= forms.CharField(label='Repo',widget=forms.TextInput(attrs={'class':'form-control','size':30})) deployment_link= forms.CharField(label='Deployment Link',widget=forms.TextInput(attrs={'class':'form-control','size':30})) - emailUsers=forms.CharField(label='Users emails',help_text="comma seprated list of emails of users to notify when new version deployed",widget=forms.TextInput(attrs={'class':'form-control','size':30})) + emailUsers=forms.CharField(required=False,label='Users emails',help_text="comma seprated list of emails of users to notify when new version deployed",widget=forms.TextInput(attrs={'class':'form-control','size':30})) + default_server=forms.ModelChoiceField(queryset=models.Server.objects.all(),empty_label="Select",widget=forms.Select(attrs={"class":"form-control"}),label="Default Server") + sshKey = forms.ModelChoiceField(queryset=models.SSHKey.objects.all(), empty_label="Select",label="SSH Key",widget=forms.Select(attrs={"class": "form-control"})) + default_branch = forms.CharField(label='Default Branch', widget=forms.TextInput(attrs={'class': 'form-control', 'size': 30})) def __init__(self, *args, **kwargs): super(ProjectsForm, self).__init__(*args, **kwargs) @@ -45,6 +48,7 @@ def save(self,files,name): P.default_server=self.cleaned_data["default_server"] P.update_style=self.cleaned_data["update_style"] P.emailUsers=self.cleaned_data["emailUsers"] + P.default_branch=self.cleaned_data["default_branch"] print "Files is ",files f=files.get('cfile','') @@ -53,7 +57,7 @@ def save(self,files,name): P.save() class Meta: model= models.Project - fields=("name","repo","repo_link","working_dir","update_style","default_server","repo_type","sshKey","deployment_link","cfile","emailUsers") + fields=("name","repo","repo_link","working_dir","update_style","default_branch","default_server","repo_type","sshKey","deployment_link","cfile","emailUsers") class ServerForm(forms.ModelForm): ip=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','size':30}),label="Hostname/IP") @@ -81,6 +85,6 @@ class Meta: fields=('name','key') class CloneForm(forms.Form): - server=forms.ModelChoiceField(queryset=models.Server.objects.all(),label="Server",required=True) + server=forms.ModelChoiceField(queryset=models.Server.objects.all(),label="Server",required=True,widget=forms.Select(attrs={"class":"form-control"})) diff --git a/webapp/autoDeploy/autodeploy/migrations/0015_auto_20171123_0937.py b/webapp/autoDeploy/autodeploy/migrations/0015_auto_20171123_0937.py new file mode 100644 index 0000000..93be6ba --- /dev/null +++ b/webapp/autoDeploy/autodeploy/migrations/0015_auto_20171123_0937.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime + + +class Migration(migrations.Migration): + + dependencies = [ + ('autodeploy', '0014_auto_20160514_1317'), + ] + + operations = [ + migrations.AlterModelOptions( + name='deployment_server', + options={'get_latest_by': 'id'}, + ), + # migrations.AddField( + # model_name='deployment_server', + # name='deployed', + # field=models.BooleanField(default=True), + # ), + # # migrations.AddField( + # model_name='project', + # name='autoDeploy', + # field=models.BooleanField(default=False), + # ), + migrations.AddField( + model_name='project', + name='default_branch', + field=models.CharField(max_length=255, null=True), + ), + migrations.AlterField( + model_name='project', + name='lastUpdate', + field=models.DateTimeField(default=datetime.datetime(2017, 11, 23, 9, 37, 18, 29660), blank=True), + ), + ] diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index 70f53ee..845ecaa 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -41,7 +41,8 @@ class Project(models.Model): deployment_link=models.CharField(max_length=200,blank=True) newVersion=models.BooleanField(default=False) emailUsers=models.TextField(default="",blank=True) - + autoDeploy = models.BooleanField(default=False) + default_branch=models.CharField(max_length=255,null=True) def __unicode__(self): return self.name diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 2484ccb..8932517 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -43,6 +43,7 @@ def add_project(request): project.default_server=Server.objects.get(name=request.POST["default_server"]) project.update_style=request.POST["update_style"] project.emailUsers=request.POST["emailUsers"] + project.default_branch=request.POST["default_branch"] if request.FILES.get("cfile","")!="": project.configFile=saveFile(request.FILES["cfile"],project.name) project.save() @@ -281,6 +282,8 @@ def listCommits(request,filter=None): c=None server=None project=None + project = Project.objects.get(name=request.session["deploy_project"]) + if filter==None: filter=project.default_branch if project.default_branch not in ("",None) else None print request.GET.get("refresh","False") if request.GET.get("refresh","False")=="True": if "commits" in request.session: @@ -289,7 +292,7 @@ def listCommits(request,filter=None): return redirect("./listCommits") if filter or not "commits" in request.session: server = Server.objects.get(name=request.session["deploy_server"]) - project = Project.objects.get(name=request.session["deploy_project"]) + c = Client("git", server.ip, server.port,key=project.sshKey.key) c.Pull(project.repo,project.working_dir,project.sshKey.key) res = c.ListCommits(project.working_dir,options={"branch":filter}) diff --git a/webapp/autoDeploy/templates/deploy2.html b/webapp/autoDeploy/templates/deploy2.html index 120f423..e60c244 100644 --- a/webapp/autoDeploy/templates/deploy2.html +++ b/webapp/autoDeploy/templates/deploy2.html @@ -33,13 +33,23 @@

      List of Tags Show Commits List of Commits Show Tags

      {% if branchs|length > 1 %} - Filter By Branch: {% for branch in branchs %} {% endfor %} - + +
    +
    + +
    +
    {% endif %}
    {% render_table commits %} From c86fec39b68f400b30fb9763cb0bcb726eb18d46 Mon Sep 17 00:00:00 2001 From: Mahmood Nasr Date: Sun, 12 Aug 2018 10:02:50 +0200 Subject: [PATCH 066/108] permissions added --- .../migrations/0016_auto_20180807_1651.py | 48 ++++++++++++++ .../migrations/0017_auto_20180812_1025.py | 20 ++++++ webapp/autoDeploy/autodeploy/models.py | 4 ++ webapp/autoDeploy/autodeploy/tables.py | 7 +- webapp/autoDeploy/autodeploy/views.py | 6 +- webapp/autoDeploy/templates/base.html | 66 ++++++++++++------- 6 files changed, 125 insertions(+), 26 deletions(-) create mode 100644 webapp/autoDeploy/autodeploy/migrations/0016_auto_20180807_1651.py create mode 100644 webapp/autoDeploy/autodeploy/migrations/0017_auto_20180812_1025.py diff --git a/webapp/autoDeploy/autodeploy/migrations/0016_auto_20180807_1651.py b/webapp/autoDeploy/autodeploy/migrations/0016_auto_20180807_1651.py new file mode 100644 index 0000000..f6ffb6f --- /dev/null +++ b/webapp/autoDeploy/autodeploy/migrations/0016_auto_20180807_1651.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations +import datetime +from django.conf import settings + + +class Migration(migrations.Migration): + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ('autodeploy', '0015_auto_20171123_0937'), + ] + + operations = [ + migrations.CreateModel( + name='User_Project', + fields=[ + ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), + ], + ), + migrations.AddField( + model_name='deployment_server', + name='deployed', + field=models.BooleanField(default=True), + ), + migrations.AddField( + model_name='project', + name='autoDeploy', + field=models.BooleanField(default=False), + ), + migrations.AlterField( + model_name='project', + name='lastUpdate', + field=models.DateTimeField(default=datetime.datetime(2018, 8, 7, 16, 51, 46, 165178), blank=True), + ), + migrations.AddField( + model_name='user_project', + name='project', + field=models.ForeignKey(to='autodeploy.Project'), + ), + migrations.AddField( + model_name='user_project', + name='user', + field=models.ForeignKey(to=settings.AUTH_USER_MODEL), + ), + ] diff --git a/webapp/autoDeploy/autodeploy/migrations/0017_auto_20180812_1025.py b/webapp/autoDeploy/autodeploy/migrations/0017_auto_20180812_1025.py new file mode 100644 index 0000000..9acba58 --- /dev/null +++ b/webapp/autoDeploy/autodeploy/migrations/0017_auto_20180812_1025.py @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals + +from django.db import models, migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('autodeploy', '0016_auto_20180807_1651'), + ] + + operations = [ + migrations.RunSQL( + """insert into auth_permission (name, content_type_id, codename) values ("Can deploy project",10,"deploy_project");"""), + migrations.RunSQL( + """insert into auth_permission (name, content_type_id, codename) values ("Can clone project",10,"clone_project");"""), + migrations.RunSQL( + """insert into auth_permission (name, content_type_id, codename) values ("Can check server",9,"check_server");"""), + ] diff --git a/webapp/autoDeploy/autodeploy/models.py b/webapp/autoDeploy/autodeploy/models.py index 845ecaa..6aaa90e 100644 --- a/webapp/autoDeploy/autodeploy/models.py +++ b/webapp/autoDeploy/autodeploy/models.py @@ -1,5 +1,6 @@ from django.db import models from datetime import datetime +from django.contrib.auth.models import User class SSHKey(models.Model): name=models.CharField(max_length=50,primary_key=True) key=models.TextField() @@ -64,3 +65,6 @@ class Plugins(models.Model): settings=models.TextField() +class User_Project(models.Model): + user=models.ForeignKey(User) + project=models.ForeignKey(Project) diff --git a/webapp/autoDeploy/autodeploy/tables.py b/webapp/autoDeploy/autodeploy/tables.py index 13fe133..8aef75f 100644 --- a/webapp/autoDeploy/autodeploy/tables.py +++ b/webapp/autoDeploy/autodeploy/tables.py @@ -14,7 +14,12 @@ class ProjectReport(TableReport): {% endif %} """ name=Table.Column(verbose_name="Project Name") - Operations=Table.TemplateColumn("      ") + Operations=Table.TemplateColumn(""" + {% if perms.autodeploy.clone_project %}  {%endif%} + {% if perms.autodeploy.deploy_project %} {% endif %} + + {% if perms.autodeploy.change_project %}   {%endif%} + {% if perms.autodeploy.delete_project %}{%endif%}""") repo_link=Table.TemplateColumn("{{ record.repo_link }} ",verbose_name="Source Link") deployment_link=Table.TemplateColumn(depLink,verbose_name="Deployment Link") newVersion=Table.BooleanColumn(yesno="Yes,No",verbose_name=" Updates Avaliable") diff --git a/webapp/autoDeploy/autodeploy/views.py b/webapp/autoDeploy/autodeploy/views.py index 8932517..70e9560 100644 --- a/webapp/autoDeploy/autodeploy/views.py +++ b/webapp/autoDeploy/autodeploy/views.py @@ -16,7 +16,11 @@ @login_required(redirect_field_name="redirect") def projects(request): name = "Projects" - xlstable = ProjectReport(Project.objects.all()) + if request.user.is_superuser: + xlstable = ProjectReport(Project.objects.all()) + else: + projects = User_Project.objects.filter(user_id=request.user.id).values_list('project',flat=True) + xlstable = ProjectReport(Project.objects.filter(name__in=list(projects))) table_to_report = RequestConfigReport(request, paginate={"per_page": 15}).configure(xlstable) if table_to_report: return create_report_http_response(table_to_report, request) diff --git a/webapp/autoDeploy/templates/base.html b/webapp/autoDeploy/templates/base.html index 6935a2a..ed23b17 100644 --- a/webapp/autoDeploy/templates/base.html +++ b/webapp/autoDeploy/templates/base.html @@ -66,36 +66,54 @@
  • Projects
  • -
  • - Servers - -
  • - SSH Keys - -
  • -
  • - Plugins - -
  • + {% if not perms.autodeploy.add_server and not perms.autodeploy.change_server and not perms.autodeploy.delete_server and not perms.autodeploy.check_server%} + {% else %} +
  • + Servers + +
  • + {% endif %} + {% if perms.autodeploy.add_sshkey and perms.autodeploy.change_sshkey and perms.autodeploy.delete_sshkey %} + +
  • + SSH Keys + +
  • + {% endif %} + {% if perms.autodeploy.add_plugins and perms.autodeploy.change_plugins and perms.autodeploy.delete_plugins %} +
  • + Plugins + +
  • + {% endif %}
    From ddb83b275e1b921afc508e8c4868c07b6bddd5ba Mon Sep 17 00:00:00 2001 From: Mohamed ElKalioby Date: Tue, 9 Oct 2018 17:36:43 +0300 Subject: [PATCH 067/108] Adding Admin Static content, add all models to admin --- webapp/autoDeploy/autodeploy/admin.py | 7 + webapp/autoDeploy/static/admin/css/base.css | 850 ++ .../static/admin/css/changelists.css | 293 + .../autoDeploy/static/admin/css/dashboard.css | 30 + webapp/autoDeploy/static/admin/css/forms.css | 395 + webapp/autoDeploy/static/admin/css/ie.css | 63 + webapp/autoDeploy/static/admin/css/login.css | 60 + webapp/autoDeploy/static/admin/css/rtl.css | 250 + .../autoDeploy/static/admin/css/widgets.css | 591 + .../static/admin/img/changelist-bg.gif | Bin 0 -> 50 bytes .../static/admin/img/changelist-bg_rtl.gif | Bin 0 -> 75 bytes .../static/admin/img/default-bg-reverse.gif | Bin 0 -> 835 bytes .../static/admin/img/default-bg.gif | Bin 0 -> 836 bytes .../static/admin/img/deleted-overlay.gif | Bin 0 -> 45 bytes .../static/admin/img/gis/move_vertex_off.png | Bin 0 -> 711 bytes .../static/admin/img/gis/move_vertex_on.png | Bin 0 -> 506 bytes .../autoDeploy/static/admin/img/icon-no.gif | Bin 0 -> 176 bytes .../static/admin/img/icon-unknown.gif | Bin 0 -> 130 bytes .../autoDeploy/static/admin/img/icon-yes.gif | Bin 0 -> 299 bytes .../static/admin/img/icon_addlink.gif | Bin 0 -> 119 bytes .../static/admin/img/icon_alert.gif | Bin 0 -> 145 bytes .../static/admin/img/icon_calendar.gif | Bin 0 -> 192 bytes .../static/admin/img/icon_changelink.gif | Bin 0 -> 119 bytes .../static/admin/img/icon_clock.gif | Bin 0 -> 390 bytes .../static/admin/img/icon_deletelink.gif | Bin 0 -> 181 bytes .../static/admin/img/icon_error.gif | Bin 0 -> 319 bytes .../static/admin/img/icon_searchbox.png | Bin 0 -> 368 bytes .../static/admin/img/icon_success.gif | Bin 0 -> 341 bytes .../static/admin/img/inline-delete-8bit.png | Bin 0 -> 395 bytes .../static/admin/img/inline-delete.png | Bin 0 -> 707 bytes .../static/admin/img/inline-restore-8bit.png | Bin 0 -> 363 bytes .../static/admin/img/inline-restore.png | Bin 0 -> 557 bytes .../static/admin/img/inline-splitter-bg.gif | Bin 0 -> 94 bytes .../static/admin/img/nav-bg-grabber.gif | Bin 0 -> 116 bytes .../static/admin/img/nav-bg-reverse.gif | Bin 0 -> 178 bytes .../static/admin/img/nav-bg-selected.gif | Bin 0 -> 265 bytes webapp/autoDeploy/static/admin/img/nav-bg.gif | Bin 0 -> 265 bytes .../static/admin/img/selector-icons.gif | Bin 0 -> 2771 bytes .../static/admin/img/selector-search.gif | Bin 0 -> 552 bytes .../static/admin/img/sorting-icons.gif | Bin 0 -> 369 bytes .../static/admin/img/tooltag-add.png | Bin 0 -> 119 bytes .../static/admin/img/tooltag-arrowright.png | Bin 0 -> 200 bytes .../static/admin/js/LICENSE-JQUERY.txt | 20 + .../autoDeploy/static/admin/js/SelectBox.js | 114 + .../static/admin/js/SelectFilter2.js | 166 + webapp/autoDeploy/static/admin/js/actions.js | 144 + .../autoDeploy/static/admin/js/actions.min.js | 6 + .../admin/js/admin/DateTimeShortcuts.js | 357 + .../admin/js/admin/RelatedObjectLookups.js | 130 + webapp/autoDeploy/static/admin/js/calendar.js | 169 + webapp/autoDeploy/static/admin/js/collapse.js | 24 + .../static/admin/js/collapse.min.js | 2 + webapp/autoDeploy/static/admin/js/core.js | 246 + webapp/autoDeploy/static/admin/js/inlines.js | 272 + .../autoDeploy/static/admin/js/inlines.min.js | 9 + .../autoDeploy/static/admin/js/jquery.init.js | 7 + webapp/autoDeploy/static/admin/js/jquery.js | 10346 ++++++++++++++++ .../autoDeploy/static/admin/js/jquery.min.js | 4 + .../autoDeploy/static/admin/js/prepopulate.js | 39 + .../static/admin/js/prepopulate.min.js | 1 + .../static/admin/js/related-widget-wrapper.js | 23 + .../autoDeploy/static/admin/js/timeparse.js | 94 + webapp/autoDeploy/static/admin/js/urlify.js | 147 + 63 files changed, 14859 insertions(+) create mode 100644 webapp/autoDeploy/static/admin/css/base.css create mode 100644 webapp/autoDeploy/static/admin/css/changelists.css create mode 100644 webapp/autoDeploy/static/admin/css/dashboard.css create mode 100644 webapp/autoDeploy/static/admin/css/forms.css create mode 100644 webapp/autoDeploy/static/admin/css/ie.css create mode 100644 webapp/autoDeploy/static/admin/css/login.css create mode 100644 webapp/autoDeploy/static/admin/css/rtl.css create mode 100644 webapp/autoDeploy/static/admin/css/widgets.css create mode 100644 webapp/autoDeploy/static/admin/img/changelist-bg.gif create mode 100644 webapp/autoDeploy/static/admin/img/changelist-bg_rtl.gif create mode 100644 webapp/autoDeploy/static/admin/img/default-bg-reverse.gif create mode 100644 webapp/autoDeploy/static/admin/img/default-bg.gif create mode 100644 webapp/autoDeploy/static/admin/img/deleted-overlay.gif create mode 100644 webapp/autoDeploy/static/admin/img/gis/move_vertex_off.png create mode 100644 webapp/autoDeploy/static/admin/img/gis/move_vertex_on.png create mode 100644 webapp/autoDeploy/static/admin/img/icon-no.gif create mode 100644 webapp/autoDeploy/static/admin/img/icon-unknown.gif create mode 100644 webapp/autoDeploy/static/admin/img/icon-yes.gif create mode 100644 webapp/autoDeploy/static/admin/img/icon_addlink.gif create mode 100644 webapp/autoDeploy/static/admin/img/icon_alert.gif create mode 100644 webapp/autoDeploy/static/admin/img/icon_calendar.gif create mode 100644 webapp/autoDeploy/static/admin/img/icon_changelink.gif create mode 100644 webapp/autoDeploy/static/admin/img/icon_clock.gif create mode 100644 webapp/autoDeploy/static/admin/img/icon_deletelink.gif create mode 100644 webapp/autoDeploy/static/admin/img/icon_error.gif create mode 100644 webapp/autoDeploy/static/admin/img/icon_searchbox.png create mode 100644 webapp/autoDeploy/static/admin/img/icon_success.gif create mode 100644 webapp/autoDeploy/static/admin/img/inline-delete-8bit.png create mode 100644 webapp/autoDeploy/static/admin/img/inline-delete.png create mode 100644 webapp/autoDeploy/static/admin/img/inline-restore-8bit.png create mode 100644 webapp/autoDeploy/static/admin/img/inline-restore.png create mode 100644 webapp/autoDeploy/static/admin/img/inline-splitter-bg.gif create mode 100644 webapp/autoDeploy/static/admin/img/nav-bg-grabber.gif create mode 100644 webapp/autoDeploy/static/admin/img/nav-bg-reverse.gif create mode 100644 webapp/autoDeploy/static/admin/img/nav-bg-selected.gif create mode 100644 webapp/autoDeploy/static/admin/img/nav-bg.gif create mode 100644 webapp/autoDeploy/static/admin/img/selector-icons.gif create mode 100644 webapp/autoDeploy/static/admin/img/selector-search.gif create mode 100644 webapp/autoDeploy/static/admin/img/sorting-icons.gif create mode 100644 webapp/autoDeploy/static/admin/img/tooltag-add.png create mode 100644 webapp/autoDeploy/static/admin/img/tooltag-arrowright.png create mode 100644 webapp/autoDeploy/static/admin/js/LICENSE-JQUERY.txt create mode 100644 webapp/autoDeploy/static/admin/js/SelectBox.js create mode 100644 webapp/autoDeploy/static/admin/js/SelectFilter2.js create mode 100644 webapp/autoDeploy/static/admin/js/actions.js create mode 100644 webapp/autoDeploy/static/admin/js/actions.min.js create mode 100644 webapp/autoDeploy/static/admin/js/admin/DateTimeShortcuts.js create mode 100644 webapp/autoDeploy/static/admin/js/admin/RelatedObjectLookups.js create mode 100644 webapp/autoDeploy/static/admin/js/calendar.js create mode 100644 webapp/autoDeploy/static/admin/js/collapse.js create mode 100644 webapp/autoDeploy/static/admin/js/collapse.min.js create mode 100644 webapp/autoDeploy/static/admin/js/core.js create mode 100644 webapp/autoDeploy/static/admin/js/inlines.js create mode 100644 webapp/autoDeploy/static/admin/js/inlines.min.js create mode 100644 webapp/autoDeploy/static/admin/js/jquery.init.js create mode 100644 webapp/autoDeploy/static/admin/js/jquery.js create mode 100644 webapp/autoDeploy/static/admin/js/jquery.min.js create mode 100644 webapp/autoDeploy/static/admin/js/prepopulate.js create mode 100644 webapp/autoDeploy/static/admin/js/prepopulate.min.js create mode 100644 webapp/autoDeploy/static/admin/js/related-widget-wrapper.js create mode 100644 webapp/autoDeploy/static/admin/js/timeparse.js create mode 100644 webapp/autoDeploy/static/admin/js/urlify.js diff --git a/webapp/autoDeploy/autodeploy/admin.py b/webapp/autoDeploy/autodeploy/admin.py index 8c38f3f..883023f 100644 --- a/webapp/autoDeploy/autodeploy/admin.py +++ b/webapp/autoDeploy/autodeploy/admin.py @@ -1,3 +1,10 @@ from django.contrib import admin +from django.apps import apps # Register your models here. +def autoregister(*app_list): + for model in apps.get_models(): + admin.site.register(model) + +autoregister('autodeploy', 'admin') + diff --git a/webapp/autoDeploy/static/admin/css/base.css b/webapp/autoDeploy/static/admin/css/base.css new file mode 100644 index 0000000..47ac79b --- /dev/null +++ b/webapp/autoDeploy/static/admin/css/base.css @@ -0,0 +1,850 @@ +/* + DJANGO Admin styles +*/ + +body { + margin: 0; + padding: 0; + font-size: 12px; + font-family: "Lucida Grande","DejaVu Sans","Bitstream Vera Sans",Verdana,Arial,sans-serif; + color: #333; + background: #fff; +} + +/* LINKS */ + +a:link, a:visited { + color: #5b80b2; + text-decoration: none; +} + +a:hover { + color: #036; +} + +a img { + border: none; +} + +a.section:link, a.section:visited { + color: #fff; + text-decoration: none; +} + +/* GLOBAL DEFAULTS */ + +p, ol, ul, dl { + margin: .2em 0 .8em 0; +} + +p { + padding: 0; + line-height: 140%; +} + +h1,h2,h3,h4,h5 { + font-weight: bold; +} + +h1 { + font-size: 18px; + color: #666; + padding: 0 6px 0 0; + margin: 0 0 .2em 0; +} + +h2 { + font-size: 16px; + margin: 1em 0 .5em 0; +} + +h2.subhead { + font-weight: normal; + margin-top: 0; +} + +h3 { + font-size: 14px; + margin: .8em 0 .3em 0; + color: #666; + font-weight: bold; +} + +h4 { + font-size: 12px; + margin: 1em 0 .8em 0; + padding-bottom: 3px; +} + +h5 { + font-size: 10px; + margin: 1.5em 0 .5em 0; + color: #666; + text-transform: uppercase; + letter-spacing: 1px; +} + +ul li { + list-style-type: square; + padding: 1px 0; +} + +ul.plainlist { + margin-left: 0 !important; +} + +ul.plainlist li { + list-style-type: none; +} + +li ul { + margin-bottom: 0; +} + +li, dt, dd { + font-size: 11px; + line-height: 14px; +} + +dt { + font-weight: bold; + margin-top: 4px; +} + +dd { + margin-left: 0; +} + +form { + margin: 0; + padding: 0; +} + +fieldset { + margin: 0; + padding: 0; +} + +blockquote { + font-size: 11px; + color: #777; + margin-left: 2px; + padding-left: 10px; + border-left: 5px solid #ddd; +} + +code, pre { + font-family: "Bitstream Vera Sans Mono", Monaco, "Courier New", Courier, monospace; + color: #666; + font-size: 11px; +} + +pre.literal-block { + margin: 10px; + background: #eee; + padding: 6px 8px; +} + +code strong { + color: #930; +} + +hr { + clear: both; + color: #eee; + background-color: #eee; + height: 1px; + border: none; + margin: 0; + padding: 0; + font-size: 1px; + line-height: 1px; +} + +/* TEXT STYLES & MODIFIERS */ + +.small { + font-size: 11px; +} + +.tiny { + font-size: 10px; +} + +p.tiny { + margin-top: -2px; +} + +.mini { + font-size: 9px; +} + +p.mini { + margin-top: -3px; +} + +.help, p.help { + font-size: 10px !important; + color: #999; +} + +img.help-tooltip { + cursor: help; +} + +p img, h1 img, h2 img, h3 img, h4 img, td img { + vertical-align: middle; +} + +.quiet, a.quiet:link, a.quiet:visited { + color: #999 !important; + font-weight: normal !important; +} + +.quiet strong { + font-weight: bold !important; +} + +.float-right { + float: right; +} + +.float-left { + float: left; +} + +.clear { + clear: both; +} + +.align-left { + text-align: left; +} + +.align-right { + text-align: right; +} + +.example { + margin: 10px 0; + padding: 5px 10px; + background: #efefef; +} + +.nowrap { + white-space: nowrap; +} + +/* TABLES */ + +table { + border-collapse: collapse; + border-color: #ccc; +} + +td, th { + font-size: 11px; + line-height: 13px; + border-bottom: 1px solid #eee; + vertical-align: top; + padding: 5px; + font-family: "Lucida Grande", Verdana, Arial, sans-serif; +} + +th { + text-align: left; + font-size: 12px; + font-weight: bold; +} + +thead th, +tfoot td { + color: #666; + padding: 2px 5px; + font-size: 11px; + background: #e1e1e1 url(../img/nav-bg.gif) top left repeat-x; + border-left: 1px solid #ddd; + border-bottom: 1px solid #ddd; +} + +tfoot td { + border-bottom: none; + border-top: 1px solid #ddd; +} + +thead th:first-child, +tfoot td:first-child { + border-left: none !important; +} + +thead th.optional { + font-weight: normal !important; +} + +fieldset table { + border-right: 1px solid #eee; +} + +tr.row-label td { + font-size: 9px; + padding-top: 2px; + padding-bottom: 0; + border-bottom: none; + color: #666; + margin-top: -1px; +} + +tr.alt { + background: #f6f6f6; +} + +.row1 { + background: #EDF3FE; +} + +.row2 { + background: #fff; +} + +/* SORTABLE TABLES */ + +thead th { + padding: 2px 5px; + line-height: normal; +} + +thead th a:link, thead th a:visited { + color: #666; +} + +thead th.sorted { + background: #c5c5c5 url(../img/nav-bg-selected.gif) top left repeat-x; +} + +thead th.sorted .text { + padding-right: 42px; +} + +table thead th .text span { + padding: 2px 5px; + display:block; +} + +table thead th .text a { + display: block; + cursor: pointer; + padding: 2px 5px; +} + +table thead th.sortable:hover { + background: #fff url(../img/nav-bg-reverse.gif) 0 -5px repeat-x; +} + +thead th.sorted a.sortremove { + visibility: hidden; +} + +table thead th.sorted:hover a.sortremove { + visibility: visible; +} + +table thead th.sorted .sortoptions { + display: block; + padding: 4px 5px 0 5px; + float: right; + text-align: right; +} + +table thead th.sorted .sortpriority { + font-size: .8em; + min-width: 12px; + text-align: center; + vertical-align: top; +} + +table thead th.sorted .sortoptions a { + width: 14px; + height: 12px; + display: inline-block; +} + +table thead th.sorted .sortoptions a.sortremove { + background: url(../img/sorting-icons.gif) -4px -5px no-repeat; +} + +table thead th.sorted .sortoptions a.sortremove:hover { + background: url(../img/sorting-icons.gif) -4px -27px no-repeat; +} + +table thead th.sorted .sortoptions a.ascending { + background: url(../img/sorting-icons.gif) -5px -50px no-repeat; +} + +table thead th.sorted .sortoptions a.ascending:hover { + background: url(../img/sorting-icons.gif) -5px -72px no-repeat; +} + +table thead th.sorted .sortoptions a.descending { + background: url(../img/sorting-icons.gif) -5px -94px no-repeat; +} + +table thead th.sorted .sortoptions a.descending:hover { + background: url(../img/sorting-icons.gif) -5px -115px no-repeat; +} + +/* ORDERABLE TABLES */ + +table.orderable tbody tr td:hover { + cursor: move; +} + +table.orderable tbody tr td:first-child { + padding-left: 14px; + background-image: url(../img/nav-bg-grabber.gif); + background-repeat: repeat-y; +} + +table.orderable-initalized .order-cell, body>tr>td.order-cell { + display: none; +} + +/* FORM DEFAULTS */ + +input, textarea, select, .form-row p, form .button { + margin: 2px 0; + padding: 2px 3px; + vertical-align: middle; + font-family: "Lucida Grande", Verdana, Arial, sans-serif; + font-weight: normal; + font-size: 11px; +} + +textarea { + vertical-align: top !important; +} + +input[type=text], input[type=password], input[type=email], input[type=url], input[type=number], +textarea, select, .vTextField { + border: 1px solid #ccc; +} + +/* FORM BUTTONS */ + +.button, input[type=submit], input[type=button], .submit-row input, a.button { + background: #fff url(../img/nav-bg.gif) bottom repeat-x; + padding: 3px 5px; + color: black; + border: 1px solid #bbb; + border-color: #ddd #aaa #aaa #ddd; +} + +a.button { + padding: 4px 5px; +} + +.button:active, input[type=submit]:active, input[type=button]:active { + background-image: url(../img/nav-bg-reverse.gif); + background-position: top; +} + +.button[disabled], input[type=submit][disabled], input[type=button][disabled] { + background-image: url(../img/nav-bg.gif); + background-position: bottom; + opacity: 0.4; +} + +.button.default, input[type=submit].default, .submit-row input.default { + border: 2px solid #5b80b2; + background: #7CA0C7 url(../img/default-bg.gif) bottom repeat-x; + font-weight: bold; + color: #fff; + float: right; +} + +.button.default:active, input[type=submit].default:active { + background-image: url(../img/default-bg-reverse.gif); + background-position: top; +} + +.button[disabled].default, input[type=submit][disabled].default, input[type=button][disabled].default { + background-image: url(../img/default-bg.gif); + background-position: bottom; + opacity: 0.4; +} + + +/* MODULES */ + +.module { + border: 1px solid #ccc; + margin-bottom: 5px; + background: #fff; +} + +.module p, .module ul, .module h3, .module h4, .module dl, .module pre { + padding-left: 10px; + padding-right: 10px; +} + +.module blockquote { + margin-left: 12px; +} + +.module ul, .module ol { + margin-left: 1.5em; +} + +.module h3 { + margin-top: .6em; +} + +.module h2, .module caption, .inline-group h2 { + margin: 0; + padding: 2px 5px 3px 5px; + font-size: 11px; + text-align: left; + font-weight: bold; + background: #7CA0C7 url(../img/default-bg.gif) top left repeat-x; + color: #fff; +} + +.module table { + border-collapse: collapse; +} + +/* MESSAGES & ERRORS */ + +ul.messagelist { + padding: 0; + margin: 0; +} + +ul.messagelist li { + font-size: 12px; + font-weight: bold; + display: block; + padding: 5px 5px 4px 25px; + margin: 0 0 3px 0; + border-bottom: 1px solid #ddd; + color: #666; + background: #dfd url(../img/icon_success.gif) 5px .3em no-repeat; +} + +ul.messagelist li.warning { + background: #ffc url(../img/icon_alert.gif) 5px .3em no-repeat; +} + +ul.messagelist li.error { + background: #ffefef url(../img/icon_error.gif) 5px .3em no-repeat; +} + +.errornote { + font-size: 12px !important; + font-weight: bold; + display: block; + padding: 5px 5px 4px 25px; + margin: 0 0 3px 0; + border: 1px solid #c22; + color: #c11; + background: #ffefef url(../img/icon_error.gif) 5px .38em no-repeat; +} + +.errornote, ul.errorlist { + border-radius: 1px; +} + +ul.errorlist { + margin: 0 0 4px !important; + padding: 0 !important; + color: #fff; + background: #c11; +} + +ul.errorlist li { + font-size: 12px !important; + display: block; + padding: 5px 5px 4px 7px; + margin: 3px 0 0 0; +} + +ul.errorlist li:first-child { + margin-top: 0; +} + +ul.errorlist li a { + color: #fff; + text-decoration: underline; +} + +td ul.errorlist { + margin: 0 !important; + padding: 0 !important; +} + +td ul.errorlist li { + margin: 0 !important; +} + +.errors, .form-row.errors { + background: #ffefef; +} + +.form-row.errors { + border: 1px solid #c22; + margin: -1px; +} + +.errors input, .errors select, .errors textarea { + border: 1px solid #c11; +} + +div.system-message { + background: #ffc; + margin: 10px; + padding: 6px 8px; + font-size: .8em; +} + +div.system-message p.system-message-title { + padding: 4px 5px 4px 25px; + margin: 0; + color: #c11; + background: #ffefef url(../img/icon_error.gif) 5px .3em no-repeat; +} + +.description { + font-size: 12px; + padding: 5px 0 0 12px; +} + +/* BREADCRUMBS */ + +div.breadcrumbs { + background: #fff url(../img/nav-bg-reverse.gif) 0 -10px repeat-x; + padding: 2px 8px 3px 8px; + font-size: 11px; + color: #999; + border-top: 1px solid #fff; + border-bottom: 1px solid #ddd; + text-align: left; +} + +/* ACTION ICONS */ + +.addlink { + padding-left: 12px; + background: url(../img/icon_addlink.gif) 0 .2em no-repeat; +} + +.changelink, .inlinechangelink { + padding-left: 12px; + background: url(../img/icon_changelink.gif) 0 .2em no-repeat; +} + +.deletelink { + padding-left: 12px; + background: url(../img/icon_deletelink.gif) 0 .25em no-repeat; +} + +a.deletelink:link, a.deletelink:visited { + color: #CC3434; +} + +a.deletelink:hover { + color: #993333; +} + +/* OBJECT TOOLS */ + +.object-tools { + font-size: 10px; + font-weight: bold; + font-family: Arial,Helvetica,sans-serif; + padding-left: 0; + float: right; + position: relative; + margin-top: -2.4em; + margin-bottom: -2em; +} + +.form-row .object-tools { + margin-top: 5px; + margin-bottom: 5px; + float: none; + height: 2em; + padding-left: 3.5em; +} + +.object-tools li { + display: block; + float: left; + margin-left: 5px; + height: 16px; +} + +.object-tools a { + border-radius: 15px; +} + +.object-tools a:link, .object-tools a:visited { + display: block; + float: left; + color: #fff; + padding: .2em 10px; + background: #999; +} + +.object-tools a:hover, .object-tools li:hover a { + background-color: #5b80b2; +} + +.object-tools a.viewsitelink, .object-tools a.golink { + background: #999 url(../img/tooltag-arrowright.png) 95% center no-repeat; + padding-right: 26px; +} + +.object-tools a.addlink { + background: #999 url(../img/tooltag-add.png) 95% center no-repeat; + padding-right: 26px; +} + +/* OBJECT HISTORY */ + +table#change-history { + width: 100%; +} + +table#change-history tbody th { + width: 16em; +} + +/* PAGE STRUCTURE */ + +#container { + position: relative; + width: 100%; + min-width: 760px; + padding: 0; +} + +#content { + margin: 10px 15px; +} + +#content-main { + float: left; + width: 100%; +} + +#content-related { + float: right; + width: 18em; + position: relative; + margin-right: -19em; +} + +#footer { + clear: both; + padding: 10px; +} + +/* COLUMN TYPES */ + +.colMS { + margin-right: 20em !important; +} + +.colSM { + margin-left: 20em !important; +} + +.colSM #content-related { + float: left; + margin-right: 0; + margin-left: -19em; +} + +.colSM #content-main { + float: right; +} + +.popup .colM { + width: 95%; +} + +.subcol { + float: left; + width: 46%; + margin-right: 15px; +} + +.dashboard #content { + width: 500px; +} + +/* HEADER */ + +#header { + width: 100%; + background: #417690; + color: #ffc; + overflow: hidden; +} + +#header a:link, #header a:visited { + color: #fff; +} + +#header a:hover { + text-decoration: underline; +} + +#branding { + float: left; +} +#branding h1 { + padding: 0 10px; + font-size: 18px; + margin: 8px 0; + font-weight: normal; +} + +#branding h1, #branding h1 a:link, #branding h1 a:visited { + color: #f4f379; +} + +#branding h2 { + padding: 0 10px; + font-size: 14px; + margin: -8px 0 8px 0; + font-weight: normal; + color: #ffc; +} + +#branding a:hover { + text-decoration: none; +} + +#user-tools { + float: right; + padding: 1.2em 10px; + font-size: 11px; + text-align: right; +} + +/* SIDEBAR */ + +#content-related h3 { + font-size: 12px; + color: #666; + margin-bottom: 3px; +} + +#content-related h4 { + font-size: 11px; +} + +#content-related .module h2 { + background: #eee url(../img/nav-bg.gif) bottom left repeat-x; + color: #666; +} diff --git a/webapp/autoDeploy/static/admin/css/changelists.css b/webapp/autoDeploy/static/admin/css/changelists.css new file mode 100644 index 0000000..28021d0 --- /dev/null +++ b/webapp/autoDeploy/static/admin/css/changelists.css @@ -0,0 +1,293 @@ +/* CHANGELISTS */ + +#changelist { + position: relative; + width: 100%; +} + +#changelist table { + width: 100%; +} + +.change-list .hiddenfields { display:none; } + +.change-list .filtered table { + border-right: 1px solid #ddd; +} + +.change-list .filtered { + min-height: 400px; +} + +.change-list .filtered { + background: white url(../img/changelist-bg.gif) top right repeat-y !important; +} + +.change-list .filtered .results, .change-list .filtered .paginator, .filtered #toolbar, .filtered div.xfull { + margin-right: 160px !important; + width: auto !important; +} + +.change-list .filtered table tbody th { + padding-right: 1em; +} + +#changelist-form .results { + overflow-x: auto; +} + +#changelist .toplinks { + border-bottom: 1px solid #ccc !important; +} + +#changelist .paginator { + color: #666; + border-top: 1px solid #eee; + border-bottom: 1px solid #eee; + background: white url(../img/nav-bg.gif) 0 180% repeat-x; + overflow: hidden; +} + +.change-list .filtered .paginator { + border-right: 1px solid #ddd; +} + +/* CHANGELIST TABLES */ + +#changelist table thead th { + padding: 0; + white-space: nowrap; + vertical-align: middle; +} + +#changelist table thead th.action-checkbox-column { + width: 1.5em; + text-align: center; +} + +#changelist table tbody td, #changelist table tbody th { + border-left: 1px solid #ddd; +} + +#changelist table tbody td:first-child, #changelist table tbody th:first-child { + border-left: 0; + border-right: 1px solid #ddd; +} + +#changelist table tbody td.action-checkbox { + text-align:center; +} + +#changelist table tfoot { + color: #666; +} + +/* TOOLBAR */ + +#changelist #toolbar { + padding: 3px; + border-bottom: 1px solid #ddd; + background: #e1e1e1 url(../img/nav-bg.gif) top left repeat-x; + color: #666; +} + +#changelist #toolbar form input { + font-size: 11px; + padding: 1px 2px; +} + +#changelist #toolbar form #searchbar { + padding: 2px; +} + +#changelist #changelist-search img { + vertical-align: middle; +} + +/* FILTER COLUMN */ + +#changelist-filter { + position: absolute; + top: 0; + right: 0; + z-index: 1000; + width: 160px; + border-left: 1px solid #ddd; + background: #efefef; + margin: 0; +} + +#changelist-filter h2 { + font-size: 11px; + padding: 2px 5px; + border-bottom: 1px solid #ddd; +} + +#changelist-filter h3 { + font-size: 12px; + margin-bottom: 0; +} + +#changelist-filter ul { + padding-left: 0; + margin-left: 10px; +} + +#changelist-filter li { + list-style-type: none; + margin-left: 0; + padding-left: 0; +} + +#changelist-filter a { + color: #999; +} + +#changelist-filter a:hover { + color: #036; +} + +#changelist-filter li.selected { + border-left: 5px solid #ccc; + padding-left: 5px; + margin-left: -10px; +} + +#changelist-filter li.selected a { + color: #5b80b2 !important; +} + +/* DATE DRILLDOWN */ + +.change-list ul.toplinks { + display: block; + background: white url(../img/nav-bg-reverse.gif) 0 -10px repeat-x; + border-top: 1px solid white; + float: left; + padding: 0 !important; + margin: 0 !important; + width: 100%; +} + +.change-list ul.toplinks li { + padding: 3px 6px; + font-weight: bold; + list-style-type: none; + display: inline-block; +} + +.change-list ul.toplinks .date-back a { + color: #999; +} + +.change-list ul.toplinks .date-back a:hover { + color: #036; +} + +/* PAGINATOR */ + +.paginator { + font-size: 11px; + padding-top: 10px; + padding-bottom: 10px; + line-height: 22px; + margin: 0; + border-top: 1px solid #ddd; +} + +.paginator a:link, .paginator a:visited { + padding: 2px 6px; + border: solid 1px #ccc; + background: white; + text-decoration: none; +} + +.paginator a.showall { + padding: 0 !important; + border: none !important; +} + +.paginator a.showall:hover { + color: #036 !important; + background: transparent !important; +} + +.paginator .end { + border-width: 2px !important; + margin-right: 6px; +} + +.paginator .this-page { + padding: 2px 6px; + font-weight: bold; + font-size: 13px; + vertical-align: top; +} + +.paginator a:hover { + color: white; + background: #5b80b2; + border-color: #036; +} + +/* ACTIONS */ + +.filtered .actions { + margin-right: 160px !important; + border-right: 1px solid #ddd; +} + +#changelist table input { + margin: 0; +} + +#changelist table tbody tr.selected { + background-color: #FFFFCC; +} + +#changelist .actions { + color: #999; + padding: 3px; + border-top: 1px solid #fff; + border-bottom: 1px solid #ddd; + background: white url(../img/nav-bg-reverse.gif) 0 -10px repeat-x; +} + +#changelist .actions.selected { + background: #fffccf; + border-top: 1px solid #fffee8; + border-bottom: 1px solid #edecd6; +} + +#changelist .actions span.all, +#changelist .actions span.action-counter, +#changelist .actions span.clear, +#changelist .actions span.question { + font-size: 11px; + margin: 0 0.5em; + display: none; +} + +#changelist .actions:last-child { + border-bottom: none; +} + +#changelist .actions select { + border: 1px solid #aaa; + margin-left: 0.5em; + padding: 1px 2px; +} + +#changelist .actions label { + font-size: 11px; + margin-left: 0.5em; +} + +#changelist #action-toggle { + display: none; +} + +#changelist .actions .button { + font-size: 11px; + padding: 1px 2px; +} diff --git a/webapp/autoDeploy/static/admin/css/dashboard.css b/webapp/autoDeploy/static/admin/css/dashboard.css new file mode 100644 index 0000000..05808bc --- /dev/null +++ b/webapp/autoDeploy/static/admin/css/dashboard.css @@ -0,0 +1,30 @@ +/* DASHBOARD */ + +.dashboard .module table th { + width: 100%; +} + +.dashboard .module table td { + white-space: nowrap; +} + +.dashboard .module table td a { + display: block; + padding-right: .6em; +} + +/* RECENT ACTIONS MODULE */ + +.module ul.actionlist { + margin-left: 0; +} + +ul.actionlist li { + list-style-type: none; +} + +ul.actionlist li { + overflow: hidden; + text-overflow: ellipsis; + -o-text-overflow: ellipsis; +} diff --git a/webapp/autoDeploy/static/admin/css/forms.css b/webapp/autoDeploy/static/admin/css/forms.css new file mode 100644 index 0000000..199ab34 --- /dev/null +++ b/webapp/autoDeploy/static/admin/css/forms.css @@ -0,0 +1,395 @@ +@import url('widgets.css'); + +/* FORM ROWS */ + +.form-row { + overflow: hidden; + padding: 8px 12px; + font-size: 11px; + border-bottom: 1px solid #eee; +} + +.form-row img, .form-row input { + vertical-align: middle; +} + +form .form-row p { + padding-left: 0; + font-size: 11px; +} + +.hidden { + display: none; +} + +/* FORM LABELS */ + +form h4 { + margin: 0 !important; + padding: 0 !important; + border: none !important; +} + +label { + font-weight: normal !important; + color: #666; + font-size: 12px; +} + +.required label, label.required { + font-weight: bold !important; + color: #333 !important; +} + +/* RADIO BUTTONS */ + +form ul.radiolist li { + list-style-type: none; +} + +form ul.radiolist label { + float: none; + display: inline; +} + +form ul.inline { + margin-left: 0; + padding: 0; +} + +form ul.inline li { + float: left; + padding-right: 7px; +} + +/* ALIGNED FIELDSETS */ + +.aligned label { + display: block; + padding: 3px 10px 0 0; + float: left; + width: 8em; + word-wrap: break-word; +} + +.aligned ul label { + display: inline; + float: none; + width: auto; +} + +.colMS .aligned .vLargeTextField, .colMS .aligned .vXMLLargeTextField { + width: 350px; +} + +form .aligned p, form .aligned ul { + margin-left: 7em; + padding-left: 30px; +} + +form .aligned table p { + margin-left: 0; + padding-left: 0; +} + +form .aligned p.help { + padding-left: 38px; +} + +.aligned .vCheckboxLabel { + float: none !important; + display: inline; + padding-left: 4px; +} + +.colM .aligned .vLargeTextField, .colM .aligned .vXMLLargeTextField { + width: 610px; +} + +.checkbox-row p.help { + margin-left: 0; + padding-left: 0 !important; +} + +fieldset .field-box { + float: left; + margin-right: 20px; +} + +/* WIDE FIELDSETS */ + +.wide label { + width: 15em !important; +} + +form .wide p { + margin-left: 15em; +} + +form .wide p.help { + padding-left: 38px; +} + +.colM fieldset.wide .vLargeTextField, .colM fieldset.wide .vXMLLargeTextField { + width: 450px; +} + +/* COLLAPSED FIELDSETS */ + +fieldset.collapsed * { + display: none; +} + +fieldset.collapsed h2, fieldset.collapsed { + display: block !important; +} + +fieldset.collapsed h2 { + background-image: url(../img/nav-bg.gif); + background-position: bottom left; + color: #999; +} + +fieldset.collapsed .collapse-toggle { + background: transparent; + display: inline !important; +} + +/* MONOSPACE TEXTAREAS */ + +fieldset.monospace textarea { + font-family: "Bitstream Vera Sans Mono",Monaco,"Courier New",Courier,monospace; +} + +/* SUBMIT ROW */ + +.submit-row { + padding: 5px 7px; + text-align: right; + background: white url(../img/nav-bg.gif) 0 100% repeat-x; + border: 1px solid #ccc; + margin: 5px 0; + overflow: hidden; +} + +body.popup .submit-row { + overflow: auto; +} + +.submit-row input { + margin: 0 0 0 5px; +} + +.submit-row p { + margin: 0.3em; +} + +.submit-row p.deletelink-box { + float: left; +} + +.submit-row .deletelink { + background: url(../img/icon_deletelink.gif) 0 50% no-repeat; + padding-left: 14px; +} + +/* CUSTOM FORM FIELDS */ + +.vSelectMultipleField { + vertical-align: top !important; +} + +.vCheckboxField { + border: none; +} + +.vDateField, .vTimeField { + margin-right: 2px; +} + +.vDateField { + min-width: 6.85em; +} + +.vTimeField { + min-width: 4.7em; +} + +.vURLField { + width: 30em; +} + +.vLargeTextField, .vXMLLargeTextField { + width: 48em; +} + +.flatpages-flatpage #id_content { + height: 40.2em; +} + +.module table .vPositiveSmallIntegerField { + width: 2.2em; +} + +.vTextField { + width: 20em; +} + +.vIntegerField { + width: 5em; +} + +.vBigIntegerField { + width: 10em; +} + +.vForeignKeyRawIdAdminField { + width: 5em; +} + +/* INLINES */ + +.inline-group { + padding: 0; + border: 1px solid #ccc; + margin: 10px 0; +} + +.inline-group .aligned label { + width: 8em; +} + +.inline-related { + position: relative; +} + +.inline-related h3 { + margin: 0; + color: #666; + padding: 3px 5px; + font-size: 11px; + background: #e1e1e1 url(../img/nav-bg.gif) top left repeat-x; + border-bottom: 1px solid #ddd; +} + +.inline-related h3 span.delete { + float: right; +} + +.inline-related h3 span.delete label { + margin-left: 2px; + font-size: 11px; +} + +.inline-related fieldset { + margin: 0; + background: #fff; + border: none; + width: 100%; +} + +.inline-related fieldset.module h3 { + margin: 0; + padding: 2px 5px 3px 5px; + font-size: 11px; + text-align: left; + font-weight: bold; + background: #bcd; + color: #fff; +} + +.inline-group .tabular fieldset.module { + border: none; + border-bottom: 1px solid #ddd; +} + +.inline-related.tabular fieldset.module table { + width: 100%; +} + +.last-related fieldset { + border: none; +} + +.inline-group .tabular tr.has_original td { + padding-top: 2em; +} + +.inline-group .tabular tr td.original { + padding: 2px 0 0 0; + width: 0; + _position: relative; +} + +.inline-group .tabular th.original { + width: 0px; + padding: 0; +} + +.inline-group .tabular td.original p { + position: absolute; + left: 0; + height: 1.1em; + padding: 2px 7px; + overflow: hidden; + font-size: 9px; + font-weight: bold; + color: #666; + _width: 700px; +} + +.inline-group ul.tools { + padding: 0; + margin: 0; + list-style: none; +} + +.inline-group ul.tools li { + display: inline; + padding: 0 5px; +} + +.inline-group div.add-row, +.inline-group .tabular tr.add-row td { + color: #666; + padding: 3px 5px; + border-bottom: 1px solid #ddd; + background: #e1e1e1 url(../img/nav-bg.gif) top left repeat-x; +} + +.inline-group .tabular tr.add-row td { + padding: 4px 5px 3px; + border-bottom: none; +} + +.inline-group ul.tools a.add, +.inline-group div.add-row a, +.inline-group .tabular tr.add-row td a { + background: url(../img/icon_addlink.gif) 0 50% no-repeat; + padding-left: 14px; + font-size: 11px; + outline: 0; /* Remove dotted border around link */ +} + +.empty-form { + display: none; +} + +/* RELATED FIELD ADD ONE / LOOKUP */ + +.add-another, .related-lookup { + margin-left: 5px; + display: inline-block; +} + +.add-another { + width: 10px; + height: 10px; + background-image: url(../img/icon_addlink.gif); +} + +.related-lookup { + width: 16px; + height: 16px; + background-image: url(../img/selector-search.gif); +} diff --git a/webapp/autoDeploy/static/admin/css/ie.css b/webapp/autoDeploy/static/admin/css/ie.css new file mode 100644 index 0000000..8199005 --- /dev/null +++ b/webapp/autoDeploy/static/admin/css/ie.css @@ -0,0 +1,63 @@ +/* IE 6 & 7 */ + +/* Proper fixed width for dashboard in IE6 */ + +.dashboard #content { + *width: 768px; +} + +.dashboard #content-main { + *width: 535px; +} + +/* IE 6 ONLY */ + +/* Keep header from flowing off the page */ + +#container { + _position: static; +} + +/* Put the right sidebars back on the page */ + +.colMS #content-related { + _margin-right: 0; + _margin-left: 10px; + _position: static; +} + +/* Put the left sidebars back on the page */ + +.colSM #content-related { + _margin-right: 10px; + _margin-left: -115px; + _position: static; +} + +.form-row { + _height: 1%; +} + +/* Fix right margin for changelist filters in IE6 */ + +#changelist-filter ul { + _margin-right: -10px; +} + +/* IE ignores min-height, but treats height as if it were min-height */ + +.change-list .filtered { + _height: 400px; +} + +/* IE doesn't know alpha transparency in PNGs */ + +.inline-deletelink { + background: transparent url(../img/inline-delete-8bit.png) no-repeat; +} + +/* IE7 doesn't support inline-block */ +.change-list ul.toplinks li { + zoom: 1; + *display: inline; +} diff --git a/webapp/autoDeploy/static/admin/css/login.css b/webapp/autoDeploy/static/admin/css/login.css new file mode 100644 index 0000000..a91de11 --- /dev/null +++ b/webapp/autoDeploy/static/admin/css/login.css @@ -0,0 +1,60 @@ +/* LOGIN FORM */ + +body.login { + background: #eee; +} + +.login #container { + background: white; + border: 1px solid #ccc; + width: 28em; + min-width: 300px; + margin-left: auto; + margin-right: auto; + margin-top: 100px; +} + +.login #content-main { + width: 100%; +} + +.login form { + margin-top: 1em; +} + +.login .form-row { + padding: 4px 0; + float: left; + width: 100%; +} + +.login .form-row label { + padding-right: 0.5em; + line-height: 2em; + font-size: 1em; + clear: both; + color: #333; +} + +.login .form-row #id_username, .login .form-row #id_password { + clear: both; + padding: 6px; + width: 100%; + -webkit-box-sizing: border-box; + -moz-box-sizing: border-box; + box-sizing: border-box; +} + +.login span.help { + font-size: 10px; + display: block; +} + +.login .submit-row { + clear: both; + padding: 1em 0 0 9.4em; +} + +.login .password-reset-link { + text-align: center; +} diff --git a/webapp/autoDeploy/static/admin/css/rtl.css b/webapp/autoDeploy/static/admin/css/rtl.css new file mode 100644 index 0000000..15db401 --- /dev/null +++ b/webapp/autoDeploy/static/admin/css/rtl.css @@ -0,0 +1,250 @@ +body { + direction: rtl; +} + +/* LOGIN */ + +.login .form-row { + float: right; +} + +.login .form-row label { + float: right; + padding-left: 0.5em; + padding-right: 0; + text-align: left; +} + +.login .submit-row { + clear: both; + padding: 1em 9.4em 0 0; +} + +/* GLOBAL */ + +th { + text-align: right; +} + +.module h2, .module caption { + text-align: right; +} + +.addlink, .changelink { + padding-left: 0px; + padding-right: 12px; + background-position: 100% 0.2em; +} + +.deletelink { + padding-left: 0px; + padding-right: 12px; + background-position: 100% 0.25em; +} + +.object-tools { + float: left; +} + +thead th:first-child, +tfoot td:first-child { + border-left: 1px solid #ddd !important; +} + +/* LAYOUT */ + +#user-tools { + right: auto; + left: 0; + text-align: left; +} + +div.breadcrumbs { + text-align: right; +} + +#content-main { + float: right; +} + +#content-related { + float: left; + margin-left: -19em; + margin-right: auto; +} + +.colMS { + margin-left: 20em !important; + margin-right: 10px !important; +} + +/* SORTABLE TABLES */ + +table thead th.sorted .sortoptions { + float: left; +} + +thead th.sorted .text { + padding-right: 0; + padding-left: 42px; +} + +/* dashboard styles */ + +.dashboard .module table td a { + padding-left: .6em; + padding-right: 12px; +} + +/* changelists styles */ + +.change-list .filtered { + background: white url(../img/changelist-bg_rtl.gif) top left repeat-y !important; +} + +.change-list .filtered table { + border-left: 1px solid #ddd; + border-right: 0px none; +} + +#changelist-filter { + right: auto; + left: 0; + border-left: 0px none; + border-right: 1px solid #ddd; +} + +.change-list .filtered .results, .change-list .filtered .paginator, .filtered #toolbar, .filtered div.xfull { + margin-right: 0px !important; + margin-left: 160px !important; +} + +#changelist-filter li.selected { + border-left: 0px none; + padding-left: 0px; + margin-left: 0; + border-right: 5px solid #ccc; + padding-right: 5px; + margin-right: -10px; +} + +.filtered .actions { + border-left:1px solid #DDDDDD; + margin-left:160px !important; + border-right: 0 none; + margin-right:0 !important; +} + +#changelist table tbody td:first-child, #changelist table tbody th:first-child { + border-right: 0; + border-left: 1px solid #ddd; +} + +/* FORMS */ + +.aligned label { + padding: 0 0 3px 1em; + float: right; +} + +.submit-row { + text-align: left +} + +.submit-row p.deletelink-box { + float: right; +} + +.submit-row .deletelink { + background: url(../img/icon_deletelink.gif) 0 50% no-repeat; + padding-right: 14px; +} + +.vDateField, .vTimeField { + margin-left: 2px; +} + +form ul.inline li { + float: right; + padding-right: 0; + padding-left: 7px; +} + +input[type=submit].default, .submit-row input.default { + float: left; +} + +fieldset .field-box { + float: right; + margin-left: 20px; + margin-right: 0; +} + +.errorlist li { + background-position: 100% .3em; + padding: 4px 25px 4px 5px; +} + +.errornote { + background-position: 100% .3em; + padding: 4px 25px 4px 5px; +} + +/* WIDGETS */ + +.calendarnav-previous { + top: 0; + left: auto; + right: 0; +} + +.calendarnav-next { + top: 0; + right: auto; + left: 0; +} + +.calendar caption, .calendarbox h2 { + text-align: center; +} + +.selector { + float: right; +} + +.selector .selector-filter { + text-align: right; +} + +.inline-deletelink { + float: left; +} + +/* MISC */ + +.inline-related h2, .inline-group h2 { + text-align: right +} + +.inline-related h3 span.delete { + padding-right: 20px; + padding-left: inherit; + left: 10px; + right: inherit; + float:left; +} + +.inline-related h3 span.delete label { + margin-left: inherit; + margin-right: 2px; +} + +/* IE7 specific bug fixes */ + +div.colM { + position: relative; +} + +.submit-row input { + float: left; +} diff --git a/webapp/autoDeploy/static/admin/css/widgets.css b/webapp/autoDeploy/static/admin/css/widgets.css new file mode 100644 index 0000000..0ca42e6 --- /dev/null +++ b/webapp/autoDeploy/static/admin/css/widgets.css @@ -0,0 +1,591 @@ +/* SELECTOR (FILTER INTERFACE) */ + +.selector { + width: 840px; + float: left; +} + +.selector select { + width: 400px; + height: 17.2em; +} + +.selector-available, .selector-chosen { + float: left; + width: 400px; + text-align: center; + margin-bottom: 5px; +} + +.selector-chosen select { + border-top: none; +} + +.selector-available h2, .selector-chosen h2 { + border: 1px solid #ccc; +} + +.selector .selector-available h2 { + background: white url(../img/nav-bg.gif) bottom left repeat-x; + color: #666; +} + +.selector .selector-filter { + background: white; + border: 1px solid #ccc; + border-width: 0 1px; + padding: 3px; + color: #999; + font-size: 10px; + margin: 0; + text-align: left; +} + +.selector .selector-filter label, +.inline-group .aligned .selector .selector-filter label { + width: 16px; + padding: 2px; +} + +.selector .selector-available input { + width: 360px; +} + +.selector ul.selector-chooser { + float: left; + width: 22px; + background-color: #eee; + border-radius: 10px; + margin: 10em 5px 0 5px; + padding: 0; +} + +.selector-chooser li { + margin: 0; + padding: 3px; + list-style-type: none; +} + +.selector select { + margin-bottom: 10px; + margin-top: 0; +} + +.selector-add, .selector-remove { + width: 16px; + height: 16px; + display: block; + text-indent: -3000px; + overflow: hidden; +} + +.selector-add { + background: url(../img/selector-icons.gif) 0 -161px no-repeat; + cursor: default; + margin-bottom: 2px; +} + +.active.selector-add { + background: url(../img/selector-icons.gif) 0 -187px no-repeat; + cursor: pointer; +} + +.selector-remove { + background: url(../img/selector-icons.gif) 0 -109px no-repeat; + cursor: default; +} + +.active.selector-remove { + background: url(../img/selector-icons.gif) 0 -135px no-repeat; + cursor: pointer; +} + +a.selector-chooseall, a.selector-clearall { + display: inline-block; + text-align: left; + margin-left: auto; + margin-right: auto; + font-weight: bold; + color: #666; +} + +a.selector-chooseall { + padding: 3px 18px 3px 0; +} + +a.selector-clearall { + padding: 3px 0 3px 18px; +} + +a.active.selector-chooseall:hover, a.active.selector-clearall:hover { + color: #036; +} + +a.selector-chooseall { + background: url(../img/selector-icons.gif) right -263px no-repeat; + cursor: default; +} + +a.active.selector-chooseall { + background: url(../img/selector-icons.gif) right -289px no-repeat; + cursor: pointer; +} + +a.selector-clearall { + background: url(../img/selector-icons.gif) left -211px no-repeat; + cursor: default; +} + +a.active.selector-clearall { + background: url(../img/selector-icons.gif) left -237px no-repeat; + cursor: pointer; +} + +/* STACKED SELECTORS */ + +.stacked { + float: left; + width: 500px; +} + +.stacked select { + width: 480px; + height: 10.1em; +} + +.stacked .selector-available, .stacked .selector-chosen { + width: 480px; +} + +.stacked .selector-available { + margin-bottom: 0; +} + +.stacked .selector-available input { + width: 442px; +} + +.stacked ul.selector-chooser { + height: 22px; + width: 50px; + margin: 0 0 3px 40%; + background-color: #eee; + border-radius: 10px; +} + +.stacked .selector-chooser li { + float: left; + padding: 3px 3px 3px 5px; +} + +.stacked .selector-chooseall, .stacked .selector-clearall { + display: none; +} + +.stacked .selector-add { + background: url(../img/selector-icons.gif) 0 -57px no-repeat; + cursor: default; +} + +.stacked .active.selector-add { + background: url(../img/selector-icons.gif) 0 -83px no-repeat; + cursor: pointer; +} + +.stacked .selector-remove { + background: url(../img/selector-icons.gif) 0 -5px no-repeat; + cursor: default; +} + +.stacked .active.selector-remove { + background: url(../img/selector-icons.gif) 0 -31px no-repeat; + cursor: pointer; +} + +/* DATE AND TIME */ + +p.datetime { + line-height: 20px; + margin: 0; + padding: 0; + color: #666; + font-size: 11px; + font-weight: bold; +} + +.datetime span { + font-size: 11px; + color: #ccc; + font-weight: normal; + white-space: nowrap; +} + +table p.datetime { + font-size: 10px; + margin-left: 0; + padding-left: 0; +} + +/* URL */ + +p.url { + line-height: 20px; + margin: 0; + padding: 0; + color: #666; + font-size: 11px; + font-weight: bold; +} + +.url a { + font-weight: normal; +} + +/* FILE UPLOADS */ + +p.file-upload { + line-height: 20px; + margin: 0; + padding: 0; + color: #666; + font-size: 11px; + font-weight: bold; +} + +.file-upload a { + font-weight: normal; +} + +.file-upload .deletelink { + margin-left: 5px; +} + +span.clearable-file-input label { + color: #333; + font-size: 11px; + display: inline; + float: none; +} + +/* CALENDARS & CLOCKS */ + +.calendarbox, .clockbox { + margin: 5px auto; + font-size: 11px; + width: 16em; + text-align: center; + background: white; + position: relative; +} + +.clockbox { + width: auto; +} + +.calendar { + margin: 0; + padding: 0; +} + +.calendar table { + margin: 0; + padding: 0; + border-collapse: collapse; + background: white; + width: 100%; +} + +.calendar caption, .calendarbox h2 { + margin: 0; + font-size: 11px; + text-align: center; + border-top: none; +} + +.calendar th { + font-size: 10px; + color: #666; + padding: 2px 3px; + text-align: center; + background: #e1e1e1 url(../img/nav-bg.gif) 0 50% repeat-x; + border-bottom: 1px solid #ddd; +} + +.calendar td { + font-size: 11px; + text-align: center; + padding: 0; + border-top: 1px solid #eee; + border-bottom: none; +} + +.calendar td.selected a { + background: #C9DBED; +} + +.calendar td.nonday { + background: #efefef; +} + +.calendar td.today a { + background: #ffc; +} + +.calendar td a, .timelist a { + display: block; + font-weight: bold; + padding: 4px; + text-decoration: none; + color: #444; +} + +.calendar td a:hover, .timelist a:hover { + background: #5b80b2; + color: white; +} + +.calendar td a:active, .timelist a:active { + background: #036; + color: white; +} + +.calendarnav { + font-size: 10px; + text-align: center; + color: #ccc; + margin: 0; + padding: 1px 3px; +} + +.calendarnav a:link, #calendarnav a:visited, #calendarnav a:hover { + color: #999; +} + +.calendar-shortcuts { + background: white; + font-size: 10px; + line-height: 11px; + border-top: 1px solid #eee; + padding: 3px 0 4px; + color: #ccc; +} + +.calendarbox .calendarnav-previous, .calendarbox .calendarnav-next { + display: block; + position: absolute; + font-weight: bold; + font-size: 12px; + background: #C9DBED url(../img/default-bg.gif) bottom left repeat-x; + padding: 1px 4px 2px 4px; + color: white; +} + +.calendarnav-previous:hover, .calendarnav-next:hover { + background: #036; +} + +.calendarnav-previous { + top: 0; + left: 0; +} + +.calendarnav-next { + top: 0; + right: 0; +} + +.calendar-cancel { + margin: 0 !important; + padding: 0 !important; + font-size: 10px; + background: #e1e1e1 url(../img/nav-bg.gif) 0 50% repeat-x; + border-top: 1px solid #ddd; +} + +.calendar-cancel:hover { + background: #e1e1e1 url(../img/nav-bg-reverse.gif) 0 50% repeat-x; +} + +.calendar-cancel a { + color: black; + display: block; +} + +ul.timelist, .timelist li { + list-style-type: none; + margin: 0; + padding: 0; +} + +.timelist a { + padding: 2px; +} + +/* INLINE ORDERER */ + +ul.orderer { + position: relative; + padding: 0 !important; + margin: 0 !important; + list-style-type: none; +} + +ul.orderer li { + list-style-type: none; + display: block; + padding: 0; + margin: 0; + border: 1px solid #bbb; + border-width: 0 1px 1px 0; + white-space: nowrap; + overflow: hidden; + background: #e2e2e2 url(../img/nav-bg-grabber.gif) repeat-y; +} + +ul.orderer li:hover { + cursor: move; + background-color: #ddd; +} + +ul.orderer li a.selector { + margin-left: 12px; + overflow: hidden; + width: 83%; + font-size: 10px !important; + padding: 0.6em 0; +} + +ul.orderer li a:link, ul.orderer li a:visited { + color: #333; +} + +ul.orderer li .inline-deletelink { + position: absolute; + right: 4px; + margin-top: 0.6em; +} + +ul.orderer li.selected { + background-color: #f8f8f8; + border-right-color: #f8f8f8; +} + +ul.orderer li.deleted { + background: #bbb url(../img/deleted-overlay.gif); +} + +ul.orderer li.deleted a:link, ul.orderer li.deleted a:visited { + color: #888; +} + +ul.orderer li.deleted .inline-deletelink { + background-image: url(../img/inline-restore.png); +} + +ul.orderer li.deleted:hover, ul.orderer li.deleted a.selector:hover { + cursor: default; +} + +/* EDIT INLINE */ + +.inline-deletelink { + float: right; + text-indent: -9999px; + background: transparent url(../img/inline-delete.png) no-repeat; + width: 15px; + height: 15px; + border: 0px none; + outline: 0; /* Remove dotted border around link */ +} + +.inline-deletelink:hover { + background-position: -15px 0; + cursor: pointer; +} + +.editinline button.addlink { + border: 0px none; + color: #5b80b2; + font-size: 100%; + cursor: pointer; +} + +.editinline button.addlink:hover { + color: #036; + cursor: pointer; +} + +.editinline table .help { + text-align: right; + float: right; + padding-left: 2em; +} + +.editinline tfoot .addlink { + white-space: nowrap; +} + +.editinline table thead th:last-child { + border-left: none; +} + +.editinline tr.deleted { + background: #ddd url(../img/deleted-overlay.gif); +} + +.editinline tr.deleted .inline-deletelink { + background-image: url(../img/inline-restore.png); +} + +.editinline tr.deleted td:hover { + cursor: default; +} + +.editinline tr.deleted td:first-child { + background-image: none !important; +} + +/* EDIT INLINE - STACKED */ + +.editinline-stacked { + min-width: 758px; +} + +.editinline-stacked .inline-object { + margin-left: 210px; + background: white; +} + +.editinline-stacked .inline-source { + float: left; + width: 200px; + background: #f8f8f8; +} + +.editinline-stacked .inline-splitter { + float: left; + width: 9px; + background: #f8f8f8 url(../img/inline-splitter-bg.gif) 50% 50% no-repeat; + border-right: 1px solid #ccc; +} + +.editinline-stacked .controls { + clear: both; + background: #e1e1e1 url(../img/nav-bg.gif) top left repeat-x; + padding: 3px 4px; + font-size: 11px; + border-top: 1px solid #ddd; +} + +/* RELATED WIDGET WRAPPER */ +.related-widget-wrapper { + overflow: hidden; /* clear floated contents */ +} + +.related-widget-wrapper-link { + opacity: 0.3; +} + +.related-widget-wrapper-link:link { + opacity: 1; +} diff --git a/webapp/autoDeploy/static/admin/img/changelist-bg.gif b/webapp/autoDeploy/static/admin/img/changelist-bg.gif new file mode 100644 index 0000000000000000000000000000000000000000..94e09f7715e559bf199dc0bec756ae844baa8a6f GIT binary patch literal 50 zcmZ?wbh9u|T*$!0@PUEh{rmTK@7~p600NK*1Ct<6-^$Z(`4`XG5|y^@-k#s`q72pm D$4Cvt?bv=6id7ONcO70{{r%8=U|E literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/default-bg-reverse.gif b/webapp/autoDeploy/static/admin/img/default-bg-reverse.gif new file mode 100644 index 0000000000000000000000000000000000000000..a28f4ad51a64131afbee7e2c3b6af352893c21e5 GIT binary patch literal 835 zcmV-J1HAl4Nk%v~VG#fy0QLX?ywd5g$>Wc((SfDPyV2;h%;kux&VHiEgQv@Yq{*Sa z+l{W!qQ2X>&*yuf#)zuThN#S(y4aey*L$GHimcC{yxF9{+^)ysgs01&yxO+S=DE=5 zq`=*$!rrpW%Ia#o)Ef<&3V-tHt57%Hx^1)~CYVyVB@=p~tMo;ew{h zv&!VG#o?8+)Qqmrnz+`6sm*|+$&#|ts>I*7&E~4Z;GetNkg(B_veJR3%8#$nw9VzU z&E=W6*PXi9oVwYCsLX|_%&NoRhN#WD(ddt_(zwp%xX$ON!QH9E;Dn~jv&-bS&gP%H z*|yE)hN;YZp~kn*=6s;Xx6kLIz1xql(y__nrNG^btIvL;$&0MdEC2ui01*Hm000O7 zfOifPgAR3s6N!Zm4lp*4BuykFJTOf*l}$X9EG!3~2cDpzoqh=-BB!URRtX8Ms!u=z zUbD1M1G%=j2p9;zy>Gw17{$G1Xb@%)%w}{DRc2LX%n%O-*9O`T+}qs-6yY>9I~3y- zJAD*?=sPhn3-R$WM@RDTQ%3>JcA0syKJpvRw!9yxMc>2a`&3xzovx=8UshKv*x zrBwWoF@=l|HCC*s;bR3396o&D2#Io}gqKQ&P@xj@r5G_1lt>sdX2ggH5q<(4L&hf= zpb;u$$grh?Ql=T4R*EFeIr5KLGLmcd%i6bbUe36dy_8@~t=1<8vdNG`N!QKH3#5}!MR z)_mbYfB-X2r#`*swCdC*JV5b~Bz9~MxJ{UV0|gEkBL#wo0UoA+5ir4%YY4HNd5A1o z;>^)NJp}VL4YJ!gaiT$Y@80pSX|Q3#jTWc((SfDPyV2;h%;kux&VHiEgQv@Yq{*Sa z+l{W!qQ2X>&*yuf#)zuThN#S(y4aey*L$GHimcC{yxF9{+^)ysgs01&yxO+S=DE=5 zq`=*$!rrpW%Ia#o)Ef<&3V-tHt57%Hx^1)~CYVyVB@=p~tMo;ew{h zv&!VG#o?8+)Qqmrnz+`6sm*|+$&#|ts>I*7&E~4Z;GetNkg(B_veJR3%8#$nw9VzU z&E=W6*PXi9oVwYCsLX|_%&NoRhN#WD(ddt_(zwp%xX$ON!QH9E;Dn~jv&-bS&gP%H z*|yE)hN;YZp~kn*=6s;Xx6kLIz1xql(y__nrNG^btIvL;$&0MdEC2ui01*Hm000O7 zfB=GngoT0x1WZIsh=@c4X^)Hq8yhz_C@7YhmN%6fC~FO)b|)tdr>LlSYz-PAudpFm zS#fh3xFN7$Mg_iMyEiEN27bWH6 z=HM3>ML{o4NKx(YFF{dAFGWZyZdf27DgX-9f+e7qGeUGM>CmP_hlM&i=nx`A;t~!V zesHj0A)^I895r&}pnw5`k|<3oSa~uJg9;fkY^eZKW(JxS@T~!jKv(R@CsZ0tXHsK5$_Dsx`$288T9sm2&pO+7vRWKDg+S zBgd5z~BMB}|@Q2`r zz!0M(GL*z*R@l?k*F|^NbkFEGAeD6Lr>o96_tdQ_$ug(M$DcUs_2^&rxr;JCKhN^= zGOMd=ghxm3IRAD|6i2K*dHVn8s@NajIqUTR2v1HTb!>_nqp27>`XK0!QyAbG8d0CA^F9Cx|8`Ux^7w#1hTk>)Z> z(jcFpXfa(;R1{={7MV5+3lFf?Vy&HYrCcdFs;KyOm=EBs5ygXBYq_}i>Vb?getdik z1axF^S%p;#RdeO?k9{10j>wELh)9l6DFO8@^|iIO1~iS#7=yKzIPTKvJS0t1(27OX zED#B9m7S%S$g~L?jj;#{HVN{sy_`*bwOnuSu)F(;!=n#WF@q^-d?WC=txYt`YI`}d z2t^e-aTlPLIkSRK-WXXWf($fM@8R|K&W*wM-t4jdY`u~wQq3Z~a_`|Sm6w7`<7)(N zm;x}jwK+A4Y2bAdf6y|d;Bv#1Ml-w-cwE`LQsme{%Sn7BN%F@irYVn1n{=2=V1=U# zEAT(0AgQYR^5Xdfcsfi#;r#0t!86r@QjICV%6p{_bOc97ED*c7B?{Ut#9L~0h(`w!0soRBa=!hZ`i3C(tMK-$w zq0zX*pg%xHYGQBoG7^Fp?f}pI6#xKNE*G6GrH2hC8gPGHzny?LP4i#C0l+j(@bfMu za~&je9lU;SE=0n!TuLi4l;uYlmIlMpLJ2Es7&hpF|OoMDi!f?u@=39aU~C_P=#aL^dh_Y z^LGv_IP*V9D>BBFd}#2i;VJgl&*=_EHTCD=-<4BqAQh@q7p&k5eY7C(@7f)D8DQ$7 zAQv>{)BVrv!0oKw@zG51AmyF|Q4~RQ;VNUzxj#fv1Xr)$IQmdWMruYncy8a%peRXj wVTV2;1d|B?Ap|@JEC~W)u~^{H-_Gvh3u9NM*1xcED*ylh07*qoM6N<$g2#E+6951J literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/icon-no.gif b/webapp/autoDeploy/static/admin/img/icon-no.gif new file mode 100644 index 0000000000000000000000000000000000000000..1b4ee5814570885705399533f1182f8b0491c5fb GIT binary patch literal 176 zcmZ?wbhEHb`H-TFR%!C^)o_GDj!gPtK1gc27Dv@$SQ0{~`FJvsmY literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/icon-unknown.gif b/webapp/autoDeploy/static/admin/img/icon-unknown.gif new file mode 100644 index 0000000000000000000000000000000000000000..cfd2b02ad91b3677dbe59111faaf4f437c362cb8 GIT binary patch literal 130 zcmV-|0Db>QNk%w1VF~~W0J9GO^z`(anwr7E!O_vts;a8Fxw+ur;K|9!=;-Lh#l`#k z`?0aH)z#IOmX?c)i~s-sA^8LW000jFEC2ui015yK000Cp@IAI#TTH&>x=&LlD2fp{ kltU;-pbSpsb&B9v9)J|xHP4tFtdrsVKoW`tBZ&Y2J8`5w82|tP literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/icon-yes.gif b/webapp/autoDeploy/static/admin/img/icon-yes.gif new file mode 100644 index 0000000000000000000000000000000000000000..73992827403791d6c1a75a079880e41dce7e0214 GIT binary patch literal 299 zcmZ?wbhEHbb?NhTQ$x_deWPc4O)NkN2|oXRf%p{M+wuUw(Z# z`TWGXJ8Mf07p=Or^7yl3mtJ2C+~V)C-fh~&DX}}E_C4PF@Y93ee}B)tGUw-?pC_Il zZ#vO%{oS?y|Nqw=uUUR`+4?){5_iQh&Q{xM6OkFieY2o T4)tf0@^WEj=4)bdWUvMRbX#E6 literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/icon_addlink.gif b/webapp/autoDeploy/static/admin/img/icon_addlink.gif new file mode 100644 index 0000000000000000000000000000000000000000..ee70e1adba52480cc6aedbee650000c5d55b0088 GIT binary patch literal 119 zcmZ?wbhEHb(s)E@aY^3 F)&O8RB1ZrK literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/icon_alert.gif b/webapp/autoDeploy/static/admin/img/icon_alert.gif new file mode 100644 index 0000000000000000000000000000000000000000..a1dde2625445b76d041ae02ccfcb83481ca63c5e GIT binary patch literal 145 zcmV;C0B-+BNk%w1VGsZi0J9GO|G@+Q!3O`;RR7pu|IkAJ%Ps%YPXF0v|INcdJ{u&=}=IXLDhr+J%S1nrq(gCL;wIgri4F* literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/icon_calendar.gif b/webapp/autoDeploy/static/admin/img/icon_calendar.gif new file mode 100644 index 0000000000000000000000000000000000000000..7587b305a4ee702cbed3bee1ae17c78feb85d00b GIT binary patch literal 192 zcmV;x06+gnNk%w1VGsZi0J8u9nVFf2iHY^~_4)bv@bK{4+uQ&D|FN{U?d|Qf&F0D5 z?Wd=w{QUgs>FMX^=l}ozA^8LW000jFEC2ui01yBW000DS@X1N*1UPGamH(iU1QH+` z43ii};vPZqm~L$+una7G@AI)4YnU1cj)Wk=I*&Aa=g_Vl48 zmH)wj0Spv>vM@3*@G|Itcpx(vSX4HgyeYC&>*nrB_bxSQsBGn6*)YRRaLr}Q6>6LJ P$Rx*~-FRR+2ZJ>L#Kbnb literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/icon_clock.gif b/webapp/autoDeploy/static/admin/img/icon_clock.gif new file mode 100644 index 0000000000000000000000000000000000000000..ff2d57e0a3b6373b7bd9540e688b1b4c71081cb7 GIT binary patch literal 390 zcmV;10eSvMNk%w1VGsZi0M$DH{QUg>{{H#-`S$kq$lLA4+3fD_?(*{T{{H>?`uXqg z@BaV(?CkCH^Yi-p`u6wt#Mtch_4dHk>iGEh^7Hca^z*{j>crRU`1twz{QT_e?DqEc z$J*@b>gvMQ>+|&V$lC14+wAM>>;3)w@9*%!*X#51^1;{Z`}_OH+U@-O`^ehu#MkWU z>FEFe{^{xI#n|ld@$l~N@5kBgv9!0z+wHW?=G)ubr>Cd?|NohpnY8A@0000000000 z00000A^8LW0027xEC2ui01yBW000J~z@2cXD;jmfB(YW_ga{xGQmJF&uGa!=Dy-IU zx$q)@gRrJva4tXt05Uks30VcZ5F=VbfDzy%IyZGW2r3RV4+8@cI5vSg1UL%-4ihvL z4F?pBk1IFOZ1vml&CJGE4FE})gH$(*xI2#8t kA}zwiLpm2FSXaY=R2~vG+}zkoL`Ox%;6gX&=t@BVI|kg>kN^Mx literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/icon_deletelink.gif b/webapp/autoDeploy/static/admin/img/icon_deletelink.gif new file mode 100644 index 0000000000000000000000000000000000000000..72523e3a3ba1446c8f768c157cea642119a02741 GIT binary patch literal 181 zcmZ?wbhEHbc&kkH2hg{xUB9fxq8%JG(R5 zT3?Eao`!{eDJnj1U~tLY{9|s;X>G0VWo1vp!yowhEs~V{|NlP&4xspxg^__loIwX9 z53-Yi)#yQKi;S#{{sX6 zi;Dh#`0#&e>3>Vh|D2rv=gC*q|>i-WM_<#QV|C1;G zS5*8rF!=rZ_kUyK|3JV%TcG%pg^__lo4aiRnY%vG=3p{kB40{i-Of=+@!=XF*PxeFcKRp5+{MAgNb8s5C%r0Nf+V(Fc^hI32V>!mF$oB=+5Fr} zS@EPfJ&q(r71kQJj|+D5gx-cdfOUJF*3qLUpX@fhwj2Z2NqP6D^+9o>vF~16iNV_P zex5r<@ABBawmM*6NbZs;Z(r0sJ19qig#gHWiPP;Qdj|l(`@h|k4Q2l`VT~qprl8mW O0000z_u719puq!NScSPpF zg#4pv1xM2>&lOf*D6TwP`0>{VkG0l*8=OKmdxUNAj@;&(aUeGLNb=vme}Ptmoj^XJ z_>+Z^fkBHw2V?}uPYi5D4pR#}bfiS5bS&9qz$LFSv4l%VM0VNAuq7M$%x`OYevyni z6y)sQCFr(n`AWsDVxcXCnHqNfPZgaKf;1I5H8q8UQ?&$wdD=UoSe-bM`a7eHH~@pX3AZUw**Q-a$B>F! ztrKr=Yc}9;F^sEP<>n$(`sY7?u41ok{?o=aDc_ikE__wyGB|VQ^y4}i)8{7jjRziW zWUGH=WYhPK*<`iF!A)ju@)o}Kg)K}zLYiIb+Pf7eGI?>na!@|xVkorHV+YfQ?MuAg z@|CcCdDQaSD5k#PP-zbv&$a)aU$%TM?7cSs{*JlDYX#Oi?a^KlyEQB$CcW%X`i6gI z?dKote=zN6@Xw<+-ygU)|H5tdm42e~0drUR>AA++`7K+t{M~&$wP%?>-X)!`lzy#O bcZ8c|t#ZiQiz<~spD}p4`njxgN@xNAak0;{ literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/inline-delete.png b/webapp/autoDeploy/static/admin/img/inline-delete.png new file mode 100644 index 0000000000000000000000000000000000000000..c5fe53c4e3bbd5f2e349be9c87c896ab99f7b6c3 GIT binary patch literal 707 zcmeAS@N?(olHy`uVBq!ia0vp^3P8-y!3-of#o4MdFfg(P_=LCux&QzF2afeg65dw;$omkMMVXW?CtFZk`pIR1d({T}zkh%K{{83Apa1^-`}_AVkOX=^Bseb$ zXk1uHkY6w`V3=6hIXJnvdHDDRg+wJJrDYYA)wOi>^bL$m&CIQA?d%<#T)lmK{emN- zV&W1~QqwZB^9qZKYisN38@hTXOqe-)(UN5=R&O|P@X@QU-+%lB+H!Mm$rGT-;+`&! zAr-e;Cq{-Ja^PuYcU{#KefL!pw}wQabHGaP2^;l#oTg{~{$Jnq@=QSgz6$wC?Z4;F zncX5<*Znupk-2PZ*!}3avlz}rF0bBaJeT>JqK52Q%>_lhUgq6w8ghqKZ-z)2vqWtF z;bS)S-X1oY3Jwbf{&@-08`So>F$KEh-w1Np$hl76a{52nIT2@ex$F0|b{rP3S(9== zh(XZP$?gDGw7ZIu=Lz>aXBebCEu%l?lwsCvUAE-@q8|1er`{)A(RgVs@%7ZRNlR literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/inline-restore-8bit.png b/webapp/autoDeploy/static/admin/img/inline-restore-8bit.png new file mode 100644 index 0000000000000000000000000000000000000000..d29fe1da636554080638326474fd122a52d2580a GIT binary patch literal 363 zcmeAS@N?(olHy`uVBq!ia0vp^3P8-y!3-of#o4L?DUSf35ZC|z|Ns8|`}_CrpFe+o z|Ni}}SFfHud-mwjqkH%6-MV$_+O=z!E?qiz?%dI%M-Lu6xOeZ~ty{Nl+_-V&%9RTi zESNE4#)JtI8X6jah8%q?0Ww;mB*-rq$i)U2&I;?j0;<{N>EaktajSLWZN3%-9+%Up zue-X;r~LnaIoDd^+gVS88J07rXkHa(d|>%Jbw&TBz*Cmx2cDnZ@@rMsQ?uBOjCps> z*dB`Pe^<@&kkRLnu#rib`1}cl5)ZB{7tlEpzTVC-+9TwF@;*(D17Ef6>R3IvHmDk~ zPr4m2S+yrw;pB{o7t$2moMtO>OfYB`s**6)Sm(6=vd9=Y0kbtDnm{r-UW|Qe3-Z literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/inline-restore.png b/webapp/autoDeploy/static/admin/img/inline-restore.png new file mode 100644 index 0000000000000000000000000000000000000000..2a6778884027c4ec32dcadb1a06874549e3f7dc5 GIT binary patch literal 557 zcmeAS@N?(olHy`uVBq!ia0vp^3P8-y!3-of#o4L?sRIE%A+A9B|Ns9$a`1!w`}ZF` zdi3(;%TJ#^eevSO%a<>KF1J&*-Vb!TWl4}p~_mQGJnv%`q&x#~R-L{~x|2{j$-oNBdI0&7SLF-wH+rxxP#7 zuP1YPJbQii(Yq~dP3f;q_7ymM@$-|P&Q+m*ZIiNEIupx$mp2`2I28ol zEyZ+|jP^OIj@Aj>X>S{JXDn^bV=UatdgKOEd4O-t9mlDyRi6I^|6Sg>J7q`9{w&%0 qi*h}eZttiIyT8tSGt2p3-)FP?x|keocymf06y2V#elF{r5}E)*XPtQf literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/inline-splitter-bg.gif b/webapp/autoDeploy/static/admin/img/inline-splitter-bg.gif new file mode 100644 index 0000000000000000000000000000000000000000..2fc918db98f2730cdf7660ab08bdc57f4a406f20 GIT binary patch literal 94 zcmZ?wbh9u|WMyDw_{_jyV{4#2a57-S&KT*C(G{DQl+NNW9y=`fHnu-v==- Ot=>b+CQo8uum%9*_Ae;_ literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/nav-bg-reverse.gif b/webapp/autoDeploy/static/admin/img/nav-bg-reverse.gif new file mode 100644 index 0000000000000000000000000000000000000000..19913fb0b069276d27d11e90842792284ecc5cd8 GIT binary patch literal 178 zcmV;j08Rf#Nk%v~VG#fy0P_F<|NsB^`1t<*{`U6v@$vEd`}^(f?dRv`;^N}{{r&3d z>hA9DU$B!R9e*F0P^XD&Kym`~Lm=e{4X9 z0SG{LF|hV2sP&~}&dXS}F6Z^GaGmodx!1$iy|0P;dtku_cTK7O6OU3(=2%Uiw4%hT z*KOU6HQ%^iR_%ZAF4;$K_VK literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/nav-bg.gif b/webapp/autoDeploy/static/admin/img/nav-bg.gif new file mode 100644 index 0000000000000000000000000000000000000000..d7e22ff1b3ba4c2e4c0995adf9e8defb8f9b32d7 GIT binary patch literal 265 zcmZ?wbh9u|6l9QR_`<;O{rmT~Z{I$D{`}ReSAYNh{q^hDhYue(@t*9{u_A=gpfpKY#xG_U+rVXV3oq`}hCvu4kkJBw+-!bOW0h%H;bV&yW+$#R@9*pI_UiEW z?CP?Ck95?C|R9>g4S7hI*~?c(b5<>~I>>hs{~^5^I0=I80; z=IGz%@8ag`<>lq%*5<_4=+e^C z#nk1*)a1g{=h4y8!qVf<&(F@z&b-j%ywK&%&CR~h<;={?xXN z&E(0+$+peq$jHdI%ip)m;Iz!+w9MqT%HPMw$F$4hwaenO%j2}k;Izu%vdZJM$=|Zc z;j_rz#Kgq1$KA2V-NVDftj6HN!otD9!KlRGz`(%2zrU)&+P=QNr@`C2yu78s+@-+W zroh{!z}uj}25$81 znTg4wKV*_V0SZ({QZjm6}T8>Lu zxjGjJ)+xulI<9B;qVJnt{R*M#&-Y#bxc995vnxO+na5sZdb#&&u1=qRmR%x-M3#sxVCMpF zM)_t4c82h#EK=5a=bwS9!2+Lmh7dxTW=hHBop%bsr7UTxAq1q7a#@O-V_v!d4{KVP zr4Xc&%0j7s=B=|F-c zK>^HRP9tb=A*~?X*zo{Cb_@eY8{Br=#w+&yb=oDHs5S!M>yn1Bo=p=wh%g8vwPz!3OK2&oU50>;X_7L=3TT*kpXd2@U|| zzzH-UgA6wKNQ2JFZsccxDd4oMPaN%ZBl8p-G`Jj% z!Xz!s6@Vx$Otk~qAx-e$zfEprRTWH%Oow9jPh8 z1m3CnV1VVRVZK`2id^Qo0RTv#I_8(frida+Fa-cpn7{6N>9W&KhwXC5Mh8%;t8RO2 zn#AV20U#K!i1CV{^7`vwfbjhDlL20OW~*Vg8RCjeKKb&83v@RsqKA%(YX!mGJ1TX% z?f(1lGgQMQ!renoAu;r|(vAV(bxFp%-Y;(rJ{gEC?ykUGS|MQ1SAGh$SO z`xWAXPPo7YH&}@5bO=LEFu({nbfIUQ;T~1f0#h!)!a`83KmM4(K z$ic%{Fl7Wlj0F$>$zh=(l4BAgG~y8JPy_OqXA&}4j}D{5KL*8uLCO%IK*sY7t65Ep z1+1dglyQ#%8f1R;yI=m|$Hq3s4+&9X3zc|akPuuV6QpWE3nZ0^OE6#{A&>>DT9v9* z5fW8>+y@dep(X~jU`&~4K`GRv1_m%7Q)=j=Ah~48PF`|LnE(`9w&cl93PFyt7-c0( z$$(6TGL>ynR0ulh%21X~)kfJQsE zvX+74Wih*%%u-+go5?I^I~!WhWFR!36>T3!bDA(#;WVfTL~35F8rHP753YF)Y+@r@ zLCl6WdUP|JNKL9z3lf7sKm!_qhyg+fpax)wp$J6~12EJ;0E4K35;e)e5h$UCg3KTp zUP$W^Brt=tCSwK!Q3NQc0)(;XfGVI+1VOAZ3r4Jf0Du(&D+X(gy*A?y82~H+l#qxkpsX!!5Wy=>p*6(4T*qa3J3^-M79A}f~Wx&T&hA4PFvQ3P}LZ8=m{N+ z!BvF+%s>&;poSt!yVTzL_P4#U0Vc#D4ouhpAqkM0FZQqpUx>pF2{4Eqd=ZA~Vxb9P z@P)bvVgqq7cMn*ozz&!zj^hpl6TZL%CYq3d1nfY)=_QCb(rbhECZGwv$geo$I}J>5 zz`jkGhJg2bUU`UP8arq&7KkekOmJ5o0-i<~?kiw^xt(K0HGWe3p!hdNxXX?bKL8&QBj8J?XD3l~Ic!Z5=ll-6NG+o2uB Zpam_8(T+!#coX3W$0kPo=cNV&06TG~#AN^g literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/selector-search.gif b/webapp/autoDeploy/static/admin/img/selector-search.gif new file mode 100644 index 0000000000000000000000000000000000000000..6d5f4c74923af2daba13baa484364380fb1614b9 GIT binary patch literal 552 zcmZ?wbhEHb6krfwc*ekR;r}fg8=Jp>|9X0Qe){yu!NI}X+uO&-$I8koH8s`3!otqZ z?(W^YSy@?TW@e{PpT2zg^6J&ABO)T)-Q5!s60Tjl=Ire3>gqaW%9PsL+PQP*Ha9mX zCnrZoN9W|^#K*^f{rYv@ym@clym|8E$=&V_@LPJBVtE(?uxDXW;RaaLxbLLEYd;7Mww%N01*VNRUKY#wgg9n+J znUg0^j*E-y=;*j{51X2rQc_ZG-@bkS{(VPBM~0yT6o0ZXf?TTuB0zD%z~0)x z(A3=0+M*~cF2*k1)@;Hotjo#FYS$;lCc@9cB5K1e*(T4%&$OJ0N1L&YotI^~f{vr% zn$~qnssdI5qW0Tb4Ak_r)E!)0jSnm~~hECZvY5o%BVqvfb0K*)eZU6uP literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/sorting-icons.gif b/webapp/autoDeploy/static/admin/img/sorting-icons.gif new file mode 100644 index 0000000000000000000000000000000000000000..451aae59874c795763cee9b044bf2c487f15a853 GIT binary patch literal 369 zcmZ?wbhEHb6k}*%IKsg2;>C++&z_w!(hg+Pin}?%lgLZrnIy)1g(XR`svm zGk^a4IdkUBoH=vGj2X$3R|a-2{Qv(y1JOY7CkrDxgCK(rNC(JH2G(~8Dt#%L^DAd!+Lo{0I{PlaWBPvS zl4w&vYiXCFU#`t13Om+FTO9ns`tXZiGLm(GX1Uw7}z rTlY@?-zz3A8IKJL+X^m4Dfq0|aN9iZ(F((o&leUP?N)YTV6X-NKX0r` literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/tooltag-add.png b/webapp/autoDeploy/static/admin/img/tooltag-add.png new file mode 100644 index 0000000000000000000000000000000000000000..1488ecf2ef9be1d5ba1541904b0761831eacf942 GIT binary patch literal 119 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!63?wyl`GbKJTYyi9>who^t@)Y*6k#k0@(X5g zcy=QV$dUJSaSW-rwe;*lMj)@r;OGC$*+-Xki)?Au7Z81S`izJHgX-)r-*y8f89ZJ6 KT-G@yGywo`GbQ~1 literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/img/tooltag-arrowright.png b/webapp/autoDeploy/static/admin/img/tooltag-arrowright.png new file mode 100644 index 0000000000000000000000000000000000000000..2f05598f53be50627daf5265ce2fa3c7fc48b3cf GIT binary patch literal 200 zcmeAS@N?(olHy`uVBq!ia0vp^0wB!61|;P_|4#%`{hlt4Ar-gIUf#&r>>$#R*xah< z%NF1bP0l+XkKCcREV literal 0 HcmV?d00001 diff --git a/webapp/autoDeploy/static/admin/js/LICENSE-JQUERY.txt b/webapp/autoDeploy/static/admin/js/LICENSE-JQUERY.txt new file mode 100644 index 0000000..a4c5bd7 --- /dev/null +++ b/webapp/autoDeploy/static/admin/js/LICENSE-JQUERY.txt @@ -0,0 +1,20 @@ +Copyright (c) 2010 John Resig, http://jquery.com/ + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/webapp/autoDeploy/static/admin/js/SelectBox.js b/webapp/autoDeploy/static/admin/js/SelectBox.js new file mode 100644 index 0000000..db3206c --- /dev/null +++ b/webapp/autoDeploy/static/admin/js/SelectBox.js @@ -0,0 +1,114 @@ +var SelectBox = { + cache: new Object(), + init: function(id) { + var box = document.getElementById(id); + var node; + SelectBox.cache[id] = new Array(); + var cache = SelectBox.cache[id]; + for (var i = 0; (node = box.options[i]); i++) { + cache.push({value: node.value, text: node.text, displayed: 1}); + } + }, + redisplay: function(id) { + // Repopulate HTML select box from cache + var box = document.getElementById(id); + box.options.length = 0; // clear all options + for (var i = 0, j = SelectBox.cache[id].length; i < j; i++) { + var node = SelectBox.cache[id][i]; + if (node.displayed) { + var new_option = new Option(node.text, node.value, false, false); + // Shows a tooltip when hovering over the option + new_option.setAttribute("title", node.text); + box.options[box.options.length] = new_option; + } + } + }, + filter: function(id, text) { + // Redisplay the HTML select box, displaying only the choices containing ALL + // the words in text. (It's an AND search.) + var tokens = text.toLowerCase().split(/\s+/); + var node, token; + for (var i = 0; (node = SelectBox.cache[id][i]); i++) { + node.displayed = 1; + for (var j = 0; (token = tokens[j]); j++) { + if (node.text.toLowerCase().indexOf(token) == -1) { + node.displayed = 0; + } + } + } + SelectBox.redisplay(id); + }, + delete_from_cache: function(id, value) { + var node, delete_index = null; + for (var i = 0; (node = SelectBox.cache[id][i]); i++) { + if (node.value == value) { + delete_index = i; + break; + } + } + var j = SelectBox.cache[id].length - 1; + for (var i = delete_index; i < j; i++) { + SelectBox.cache[id][i] = SelectBox.cache[id][i+1]; + } + SelectBox.cache[id].length--; + }, + add_to_cache: function(id, option) { + SelectBox.cache[id].push({value: option.value, text: option.text, displayed: 1}); + }, + cache_contains: function(id, value) { + // Check if an item is contained in the cache + var node; + for (var i = 0; (node = SelectBox.cache[id][i]); i++) { + if (node.value == value) { + return true; + } + } + return false; + }, + move: function(from, to) { + var from_box = document.getElementById(from); + var to_box = document.getElementById(to); + var option; + for (var i = 0; (option = from_box.options[i]); i++) { + if (option.selected && SelectBox.cache_contains(from, option.value)) { + SelectBox.add_to_cache(to, {value: option.value, text: option.text, displayed: 1}); + SelectBox.delete_from_cache(from, option.value); + } + } + SelectBox.redisplay(from); + SelectBox.redisplay(to); + }, + move_all: function(from, to) { + var from_box = document.getElementById(from); + var to_box = document.getElementById(to); + var option; + for (var i = 0; (option = from_box.options[i]); i++) { + if (SelectBox.cache_contains(from, option.value)) { + SelectBox.add_to_cache(to, {value: option.value, text: option.text, displayed: 1}); + SelectBox.delete_from_cache(from, option.value); + } + } + SelectBox.redisplay(from); + SelectBox.redisplay(to); + }, + sort: function(id) { + SelectBox.cache[id].sort( function(a, b) { + a = a.text.toLowerCase(); + b = b.text.toLowerCase(); + try { + if (a > b) return 1; + if (a < b) return -1; + } + catch (e) { + // silently fail on IE 'unknown' exception + } + return 0; + } ); + }, + select_all: function(id) { + var box = document.getElementById(id); + for (var i = 0; i < box.options.length; i++) { + box.options[i].selected = 'selected'; + } + } +} diff --git a/webapp/autoDeploy/static/admin/js/SelectFilter2.js b/webapp/autoDeploy/static/admin/js/SelectFilter2.js new file mode 100644 index 0000000..6c8a4b4 --- /dev/null +++ b/webapp/autoDeploy/static/admin/js/SelectFilter2.js @@ -0,0 +1,166 @@ +/* +SelectFilter2 - Turns a multiple-select box into a filter interface. + +Requires core.js, SelectBox.js and addevent.js. +*/ +(function($) { +function findForm(node) { + // returns the node of the form containing the given node + if (node.tagName.toLowerCase() != 'form') { + return findForm(node.parentNode); + } + return node; +} + +window.SelectFilter = { + init: function(field_id, field_name, is_stacked, admin_static_prefix) { + if (field_id.match(/__prefix__/)){ + // Don't initialize on empty forms. + return; + } + var from_box = document.getElementById(field_id); + from_box.id += '_from'; // change its ID + from_box.className = 'filtered'; + + var ps = from_box.parentNode.getElementsByTagName('p'); + for (var i=0; i, because it just gets in the way. + from_box.parentNode.removeChild(ps[i]); + } else if (ps[i].className.indexOf("help") != -1) { + // Move help text up to the top so it isn't below the select + // boxes or wrapped off on the side to the right of the add + // button: + from_box.parentNode.insertBefore(ps[i], from_box.parentNode.firstChild); + } + } + + //
    or
    + var selector_div = quickElement('div', from_box.parentNode); + selector_div.className = is_stacked ? 'selector stacked' : 'selector'; + + //
    + var selector_available = quickElement('div', selector_div); + selector_available.className = 'selector-available'; + var title_available = quickElement('h2', selector_available, interpolate(gettext('Available %s') + ' ', [field_name])); + quickElement('img', title_available, '', 'src', admin_static_prefix + 'img/icon-unknown.gif', 'width', '10', 'height', '10', 'class', 'help help-tooltip', 'title', interpolate(gettext('This is the list of available %s. You may choose some by selecting them in the box below and then clicking the "Choose" arrow between the two boxes.'), [field_name])); + + var filter_p = quickElement('p', selector_available, '', 'id', field_id + '_filter'); + filter_p.className = 'selector-filter'; + + var search_filter_label = quickElement('label', filter_p, '', 'for', field_id + "_input"); + + var search_selector_img = quickElement('img', search_filter_label, '', 'src', admin_static_prefix + 'img/selector-search.gif', 'class', 'help-tooltip', 'alt', '', 'title', interpolate(gettext("Type into this box to filter down the list of available %s."), [field_name])); + + filter_p.appendChild(document.createTextNode(' ')); + + var filter_input = quickElement('input', filter_p, '', 'type', 'text', 'placeholder', gettext("Filter")); + filter_input.id = field_id + '_input'; + + selector_available.appendChild(from_box); + var choose_all = quickElement('a', selector_available, gettext('Choose all'), 'title', interpolate(gettext('Click to choose all %s at once.'), [field_name]), 'href', 'javascript: (function(){ SelectBox.move_all("' + field_id + '_from", "' + field_id + '_to"); SelectFilter.refresh_icons("' + field_id + '");})()', 'id', field_id + '_add_all_link'); + choose_all.className = 'selector-chooseall'; + + //
      + var selector_chooser = quickElement('ul', selector_div); + selector_chooser.className = 'selector-chooser'; + var add_link = quickElement('a', quickElement('li', selector_chooser), gettext('Choose'), 'title', gettext('Choose'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_from","' + field_id + '_to"); SelectFilter.refresh_icons("' + field_id + '");})()', 'id', field_id + '_add_link'); + add_link.className = 'selector-add'; + var remove_link = quickElement('a', quickElement('li', selector_chooser), gettext('Remove'), 'title', gettext('Remove'), 'href', 'javascript: (function(){ SelectBox.move("' + field_id + '_to","' + field_id + '_from"); SelectFilter.refresh_icons("' + field_id + '");})()', 'id', field_id + '_remove_link'); + remove_link.className = 'selector-remove'; + + //
      + var selector_chosen = quickElement('div', selector_div); + selector_chosen.className = 'selector-chosen'; + var title_chosen = quickElement('h2', selector_chosen, interpolate(gettext('Chosen %s') + ' ', [field_name])); + quickElement('img', title_chosen, '', 'src', admin_static_prefix + 'img/icon-unknown.gif', 'width', '10', 'height', '10', 'class', 'help help-tooltip', 'title', interpolate(gettext('This is the list of chosen %s. You may remove some by selecting them in the box below and then clicking the "Remove" arrow between the two boxes.'), [field_name])); + + var to_box = quickElement('select', selector_chosen, '', 'id', field_id + '_to', 'multiple', 'multiple', 'size', from_box.size, 'name', from_box.getAttribute('name')); + to_box.className = 'filtered'; + var clear_all = quickElement('a', selector_chosen, gettext('Remove all'), 'title', interpolate(gettext('Click to remove all chosen %s at once.'), [field_name]), 'href', 'javascript: (function() { SelectBox.move_all("' + field_id + '_to", "' + field_id + '_from"); SelectFilter.refresh_icons("' + field_id + '");})()', 'id', field_id + '_remove_all_link'); + clear_all.className = 'selector-clearall'; + + from_box.setAttribute('name', from_box.getAttribute('name') + '_old'); + + // Set up the JavaScript event handlers for the select box filter interface + addEvent(filter_input, 'keypress', function(e) { SelectFilter.filter_key_press(e, field_id); }); + addEvent(filter_input, 'keyup', function(e) { SelectFilter.filter_key_up(e, field_id); }); + addEvent(filter_input, 'keydown', function(e) { SelectFilter.filter_key_down(e, field_id); }); + addEvent(from_box, 'change', function(e) { SelectFilter.refresh_icons(field_id) }); + addEvent(to_box, 'change', function(e) { SelectFilter.refresh_icons(field_id) }); + addEvent(from_box, 'dblclick', function() { SelectBox.move(field_id + '_from', field_id + '_to'); SelectFilter.refresh_icons(field_id); }); + addEvent(to_box, 'dblclick', function() { SelectBox.move(field_id + '_to', field_id + '_from'); SelectFilter.refresh_icons(field_id); }); + addEvent(findForm(from_box), 'submit', function() { SelectBox.select_all(field_id + '_to'); }); + SelectBox.init(field_id + '_from'); + SelectBox.init(field_id + '_to'); + // Move selected from_box options to to_box + SelectBox.move(field_id + '_from', field_id + '_to'); + + if (!is_stacked) { + // In horizontal mode, give the same height to the two boxes. + var j_from_box = $(from_box); + var j_to_box = $(to_box); + var resize_filters = function() { j_to_box.height($(filter_p).outerHeight() + j_from_box.outerHeight()); } + if (j_from_box.outerHeight() > 0) { + resize_filters(); // This fieldset is already open. Resize now. + } else { + // This fieldset is probably collapsed. Wait for its 'show' event. + j_to_box.closest('fieldset').one('show.fieldset', resize_filters); + } + } + + // Initial icon refresh + SelectFilter.refresh_icons(field_id); + }, + refresh_icons: function(field_id) { + var from = $('#' + field_id + '_from'); + var to = $('#' + field_id + '_to'); + var is_from_selected = from.find('option:selected').length > 0; + var is_to_selected = to.find('option:selected').length > 0; + // Active if at least one item is selected + $('#' + field_id + '_add_link').toggleClass('active', is_from_selected); + $('#' + field_id + '_remove_link').toggleClass('active', is_to_selected); + // Active if the corresponding box isn't empty + $('#' + field_id + '_add_all_link').toggleClass('active', from.find('option').length > 0); + $('#' + field_id + '_remove_all_link').toggleClass('active', to.find('option').length > 0); + }, + filter_key_press: function(event, field_id) { + var from = document.getElementById(field_id + '_from'); + // don't submit form if user pressed Enter + if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) { + from.selectedIndex = 0; + SelectBox.move(field_id + '_from', field_id + '_to'); + from.selectedIndex = 0; + event.preventDefault() + return false; + } + }, + filter_key_up: function(event, field_id) { + var from = document.getElementById(field_id + '_from'); + var temp = from.selectedIndex; + SelectBox.filter(field_id + '_from', document.getElementById(field_id + '_input').value); + from.selectedIndex = temp; + return true; + }, + filter_key_down: function(event, field_id) { + var from = document.getElementById(field_id + '_from'); + // right arrow -- move across + if ((event.which && event.which == 39) || (event.keyCode && event.keyCode == 39)) { + var old_index = from.selectedIndex; + SelectBox.move(field_id + '_from', field_id + '_to'); + from.selectedIndex = (old_index == from.length) ? from.length - 1 : old_index; + return false; + } + // down arrow -- wrap around + if ((event.which && event.which == 40) || (event.keyCode && event.keyCode == 40)) { + from.selectedIndex = (from.length == from.selectedIndex + 1) ? 0 : from.selectedIndex + 1; + } + // up arrow -- wrap around + if ((event.which && event.which == 38) || (event.keyCode && event.keyCode == 38)) { + from.selectedIndex = (from.selectedIndex == 0) ? from.length - 1 : from.selectedIndex - 1; + } + return true; + } +} + +})(django.jQuery); diff --git a/webapp/autoDeploy/static/admin/js/actions.js b/webapp/autoDeploy/static/admin/js/actions.js new file mode 100644 index 0000000..58f572f --- /dev/null +++ b/webapp/autoDeploy/static/admin/js/actions.js @@ -0,0 +1,144 @@ +(function($) { + var lastChecked; + + $.fn.actions = function(opts) { + var options = $.extend({}, $.fn.actions.defaults, opts); + var actionCheckboxes = $(this); + var list_editable_changed = false; + var checker = function(checked) { + if (checked) { + showQuestion(); + } else { + reset(); + } + $(actionCheckboxes).prop("checked", checked) + .parent().parent().toggleClass(options.selectedClass, checked); + }, + updateCounter = function() { + var sel = $(actionCheckboxes).filter(":checked").length; + // _actions_icnt is defined in the generated HTML + // and contains the total amount of objects in the queryset + $(options.counterContainer).html(interpolate( + ngettext('%(sel)s of %(cnt)s selected', '%(sel)s of %(cnt)s selected', sel), { + sel: sel, + cnt: _actions_icnt + }, true)); + $(options.allToggle).prop("checked", function() { + var value; + if (sel == actionCheckboxes.length) { + value = true; + showQuestion(); + } else { + value = false; + clearAcross(); + } + return value; + }); + }, + showQuestion = function() { + $(options.acrossClears).hide(); + $(options.acrossQuestions).show(); + $(options.allContainer).hide(); + }, + showClear = function() { + $(options.acrossClears).show(); + $(options.acrossQuestions).hide(); + $(options.actionContainer).toggleClass(options.selectedClass); + $(options.allContainer).show(); + $(options.counterContainer).hide(); + }, + reset = function() { + $(options.acrossClears).hide(); + $(options.acrossQuestions).hide(); + $(options.allContainer).hide(); + $(options.counterContainer).show(); + }, + clearAcross = function() { + reset(); + $(options.acrossInput).val(0); + $(options.actionContainer).removeClass(options.selectedClass); + }; + // Show counter by default + $(options.counterContainer).show(); + // Check state of checkboxes and reinit state if needed + $(this).filter(":checked").each(function(i) { + $(this).parent().parent().toggleClass(options.selectedClass); + updateCounter(); + if ($(options.acrossInput).val() == 1) { + showClear(); + } + }); + $(options.allToggle).show().click(function() { + checker($(this).prop("checked")); + updateCounter(); + }); + $("a", options.acrossQuestions).click(function(event) { + event.preventDefault(); + $(options.acrossInput).val(1); + showClear(); + }); + $("a", options.acrossClears).click(function(event) { + event.preventDefault(); + $(options.allToggle).prop("checked", false); + clearAcross(); + checker(0); + updateCounter(); + }); + lastChecked = null; + $(actionCheckboxes).click(function(event) { + if (!event) { event = window.event; } + var target = event.target ? event.target : event.srcElement; + if (lastChecked && $.data(lastChecked) != $.data(target) && event.shiftKey === true) { + var inrange = false; + $(lastChecked).prop("checked", target.checked) + .parent().parent().toggleClass(options.selectedClass, target.checked); + $(actionCheckboxes).each(function() { + if ($.data(this) == $.data(lastChecked) || $.data(this) == $.data(target)) { + inrange = (inrange) ? false : true; + } + if (inrange) { + $(this).prop("checked", target.checked) + .parent().parent().toggleClass(options.selectedClass, target.checked); + } + }); + } + $(target).parent().parent().toggleClass(options.selectedClass, target.checked); + lastChecked = target; + updateCounter(); + }); + $('form#changelist-form table#result_list tr').find('td:gt(0) :input').change(function() { + list_editable_changed = true; + }); + $('form#changelist-form button[name="index"]').click(function(event) { + if (list_editable_changed) { + return confirm(gettext("You have unsaved changes on individual editable fields. If you run an action, your unsaved changes will be lost.")); + } + }); + $('form#changelist-form input[name="_save"]').click(function(event) { + var action_changed = false; + $('select option:selected', options.actionContainer).each(function() { + if ($(this).val()) { + action_changed = true; + } + }); + if (action_changed) { + if (list_editable_changed) { + return confirm(gettext("You have selected an action, but you haven't saved your changes to individual fields yet. Please click OK to save. You'll need to re-run the action.")); + } else { + return confirm(gettext("You have selected an action, and you haven't made any changes on individual fields. You're probably looking for the Go button rather than the Save button.")); + } + } + }); + }; + /* Setup plugin defaults */ + $.fn.actions.defaults = { + actionContainer: "div.actions", + counterContainer: "span.action-counter", + allContainer: "div.actions span.all", + acrossInput: "div.actions input.select-across", + acrossQuestions: "div.actions span.question", + acrossClears: "div.actions span.clear", + allToggle: "#action-toggle", + selectedClass: "selected" + }; +})(django.jQuery); diff --git a/webapp/autoDeploy/static/admin/js/actions.min.js b/webapp/autoDeploy/static/admin/js/actions.min.js new file mode 100644 index 0000000..0dd6683 --- /dev/null +++ b/webapp/autoDeploy/static/admin/js/actions.min.js @@ -0,0 +1,6 @@ +(function(a){var f;a.fn.actions=function(q){var b=a.extend({},a.fn.actions.defaults,q),g=a(this),e=!1,m=function(c){c?k():l();a(g).prop("checked",c).parent().parent().toggleClass(b.selectedClass,c)},h=function(){var c=a(g).filter(":checked").length;a(b.counterContainer).html(interpolate(ngettext("%(sel)s of %(cnt)s selected","%(sel)s of %(cnt)s selected",c),{sel:c,cnt:_actions_icnt},!0));a(b.allToggle).prop("checked",function(){var a;c==g.length?(a=!0,k()):(a=!1,n());return a})},k=function(){a(b.acrossClears).hide(); +a(b.acrossQuestions).show();a(b.allContainer).hide()},p=function(){a(b.acrossClears).show();a(b.acrossQuestions).hide();a(b.actionContainer).toggleClass(b.selectedClass);a(b.allContainer).show();a(b.counterContainer).hide()},l=function(){a(b.acrossClears).hide();a(b.acrossQuestions).hide();a(b.allContainer).hide();a(b.counterContainer).show()},n=function(){l();a(b.acrossInput).val(0);a(b.actionContainer).removeClass(b.selectedClass)};a(b.counterContainer).show();a(this).filter(":checked").each(function(c){a(this).parent().parent().toggleClass(b.selectedClass); +h();1==a(b.acrossInput).val()&&p()});a(b.allToggle).show().click(function(){m(a(this).prop("checked"));h()});a("a",b.acrossQuestions).click(function(c){c.preventDefault();a(b.acrossInput).val(1);p()});a("a",b.acrossClears).click(function(c){c.preventDefault();a(b.allToggle).prop("checked",!1);n();m(0);h()});f=null;a(g).click(function(c){c||(c=window.event);var d=c.target?c.target:c.srcElement;if(f&&a.data(f)!=a.data(d)&&!0===c.shiftKey){var e=!1;a(f).prop("checked",d.checked).parent().parent().toggleClass(b.selectedClass, +d.checked);a(g).each(function(){if(a.data(this)==a.data(f)||a.data(this)==a.data(d))e=e?!1:!0;e&&a(this).prop("checked",d.checked).parent().parent().toggleClass(b.selectedClass,d.checked)})}a(d).parent().parent().toggleClass(b.selectedClass,d.checked);f=d;h()});a("form#changelist-form table#result_list tr").find("td:gt(0) :input").change(function(){e=!0});a('form#changelist-form button[name="index"]').click(function(a){if(e)return confirm(gettext("You have unsaved changes on individual editable fields. If you run an action, your unsaved changes will be lost."))}); +a('form#changelist-form input[name="_save"]').click(function(c){var d=!1;a("select option:selected",b.actionContainer).each(function(){a(this).val()&&(d=!0)});if(d)return e?confirm(gettext("You have selected an action, but you haven't saved your changes to individual fields yet. Please click OK to save. You'll need to re-run the action.")):confirm(gettext("You have selected an action, and you haven't made any changes on individual fields. You're probably looking for the Go button rather than the Save button."))})}; +a.fn.actions.defaults={actionContainer:"div.actions",counterContainer:"span.action-counter",allContainer:"div.actions span.all",acrossInput:"div.actions input.select-across",acrossQuestions:"div.actions span.question",acrossClears:"div.actions span.clear",allToggle:"#action-toggle",selectedClass:"selected"}})(django.jQuery); diff --git a/webapp/autoDeploy/static/admin/js/admin/DateTimeShortcuts.js b/webapp/autoDeploy/static/admin/js/admin/DateTimeShortcuts.js new file mode 100644 index 0000000..faec5a4 --- /dev/null +++ b/webapp/autoDeploy/static/admin/js/admin/DateTimeShortcuts.js @@ -0,0 +1,357 @@ +// Inserts shortcut buttons after all of the following: +// +// + +var DateTimeShortcuts = { + calendars: [], + calendarInputs: [], + clockInputs: [], + dismissClockFunc: [], + dismissCalendarFunc: [], + calendarDivName1: 'calendarbox', // name of calendar
      that gets toggled + calendarDivName2: 'calendarin', // name of
      that contains calendar + calendarLinkName: 'calendarlink',// name of the link that is used to toggle + clockDivName: 'clockbox', // name of clock
      that gets toggled + clockLinkName: 'clocklink', // name of the link that is used to toggle + shortCutsClass: 'datetimeshortcuts', // class of the clock and cal shortcuts + timezoneWarningClass: 'timezonewarning', // class of the warning for timezone mismatch + timezoneOffset: 0, + admin_media_prefix: '', + init: function() { + // Get admin_media_prefix by grabbing it off the window object. It's + // set in the admin/base.html template, so if it's not there, someone's + // overridden the template. In that case, we'll set a clearly-invalid + // value in the hopes that someone will examine HTTP requests and see it. + if (window.__admin_media_prefix__ != undefined) { + DateTimeShortcuts.admin_media_prefix = window.__admin_media_prefix__; + } else { + DateTimeShortcuts.admin_media_prefix = '/missing-admin-media-prefix/'; + } + + if (window.__admin_utc_offset__ != undefined) { + var serverOffset = window.__admin_utc_offset__; + var localOffset = new Date().getTimezoneOffset() * -60; + DateTimeShortcuts.timezoneOffset = localOffset - serverOffset; + } + + var inputs = document.getElementsByTagName('input'); + for (i=0; i 0) { + message = ngettext( + 'Note: You are %s hour ahead of server time.', + 'Note: You are %s hours ahead of server time.', + timezoneOffset + ); + } + else { + timezoneOffset *= -1 + message = ngettext( + 'Note: You are %s hour behind server time.', + 'Note: You are %s hours behind server time.', + timezoneOffset + ); + } + message = interpolate(message, [timezoneOffset]); + + var $warning = $(''); + $warning.attr('class', warningClass); + $warning.text(message); + + $(inp).parent() + .append($('
      ')) + .append($warning) + }, + // Add clock widget to a given field + addClock: function(inp) { + var num = DateTimeShortcuts.clockInputs.length; + DateTimeShortcuts.clockInputs[num] = inp; + DateTimeShortcuts.dismissClockFunc[num] = function() { DateTimeShortcuts.dismissClock(num); return true; }; + + // Shortcut links (clock icon and "Now" link) + var shortcuts_span = document.createElement('span'); + shortcuts_span.className = DateTimeShortcuts.shortCutsClass; + inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling); + var now_link = document.createElement('a'); + now_link.setAttribute('href', "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", -1);"); + now_link.appendChild(document.createTextNode(gettext('Now'))); + var clock_link = document.createElement('a'); + clock_link.setAttribute('href', 'javascript:DateTimeShortcuts.openClock(' + num + ');'); + clock_link.id = DateTimeShortcuts.clockLinkName + num; + quickElement('img', clock_link, '', 'src', DateTimeShortcuts.admin_media_prefix + 'img/icon_clock.gif', 'alt', gettext('Clock')); + shortcuts_span.appendChild(document.createTextNode('\240')); + shortcuts_span.appendChild(now_link); + shortcuts_span.appendChild(document.createTextNode('\240|\240')); + shortcuts_span.appendChild(clock_link); + + // Create clock link div + // + // Markup looks like: + //
      + //

      Choose a time

      + // + //

      Cancel

      + //
      + + var clock_box = document.createElement('div'); + clock_box.style.display = 'none'; + clock_box.style.position = 'absolute'; + clock_box.className = 'clockbox module'; + clock_box.setAttribute('id', DateTimeShortcuts.clockDivName + num); + document.body.appendChild(clock_box); + addEvent(clock_box, 'click', cancelEventPropagation); + + quickElement('h2', clock_box, gettext('Choose a time')); + var time_list = quickElement('ul', clock_box); + time_list.className = 'timelist'; + quickElement("a", quickElement("li", time_list), gettext("Now"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", -1);"); + quickElement("a", quickElement("li", time_list), gettext("Midnight"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", 0);"); + quickElement("a", quickElement("li", time_list), gettext("6 a.m."), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", 6);"); + quickElement("a", quickElement("li", time_list), gettext("Noon"), "href", "javascript:DateTimeShortcuts.handleClockQuicklink(" + num + ", 12);"); + + var cancel_p = quickElement('p', clock_box); + cancel_p.className = 'calendar-cancel'; + quickElement('a', cancel_p, gettext('Cancel'), 'href', 'javascript:DateTimeShortcuts.dismissClock(' + num + ');'); + django.jQuery(document).bind('keyup', function(event) { + if (event.which == 27) { + // ESC key closes popup + DateTimeShortcuts.dismissClock(num); + event.preventDefault(); + } + }); + }, + openClock: function(num) { + var clock_box = document.getElementById(DateTimeShortcuts.clockDivName+num) + var clock_link = document.getElementById(DateTimeShortcuts.clockLinkName+num) + + // Recalculate the clockbox position + // is it left-to-right or right-to-left layout ? + if (getStyle(document.body,'direction')!='rtl') { + clock_box.style.left = findPosX(clock_link) + 17 + 'px'; + } + else { + // since style's width is in em, it'd be tough to calculate + // px value of it. let's use an estimated px for now + // TODO: IE returns wrong value for findPosX when in rtl mode + // (it returns as it was left aligned), needs to be fixed. + clock_box.style.left = findPosX(clock_link) - 110 + 'px'; + } + clock_box.style.top = Math.max(0, findPosY(clock_link) - 30) + 'px'; + + // Show the clock box + clock_box.style.display = 'block'; + addEvent(document, 'click', DateTimeShortcuts.dismissClockFunc[num]); + }, + dismissClock: function(num) { + document.getElementById(DateTimeShortcuts.clockDivName + num).style.display = 'none'; + removeEvent(document, 'click', DateTimeShortcuts.dismissClockFunc[num]); + }, + handleClockQuicklink: function(num, val) { + var d; + if (val == -1) { + d = DateTimeShortcuts.now(); + } + else { + d = new Date(1970, 1, 1, val, 0, 0, 0) + } + DateTimeShortcuts.clockInputs[num].value = d.strftime(get_format('TIME_INPUT_FORMATS')[0]); + DateTimeShortcuts.clockInputs[num].focus(); + DateTimeShortcuts.dismissClock(num); + }, + // Add calendar widget to a given field. + addCalendar: function(inp) { + var num = DateTimeShortcuts.calendars.length; + + DateTimeShortcuts.calendarInputs[num] = inp; + DateTimeShortcuts.dismissCalendarFunc[num] = function() { DateTimeShortcuts.dismissCalendar(num); return true; }; + + // Shortcut links (calendar icon and "Today" link) + var shortcuts_span = document.createElement('span'); + shortcuts_span.className = DateTimeShortcuts.shortCutsClass; + inp.parentNode.insertBefore(shortcuts_span, inp.nextSibling); + var today_link = document.createElement('a'); + today_link.setAttribute('href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);'); + today_link.appendChild(document.createTextNode(gettext('Today'))); + var cal_link = document.createElement('a'); + cal_link.setAttribute('href', 'javascript:DateTimeShortcuts.openCalendar(' + num + ');'); + cal_link.id = DateTimeShortcuts.calendarLinkName + num; + quickElement('img', cal_link, '', 'src', DateTimeShortcuts.admin_media_prefix + 'img/icon_calendar.gif', 'alt', gettext('Calendar')); + shortcuts_span.appendChild(document.createTextNode('\240')); + shortcuts_span.appendChild(today_link); + shortcuts_span.appendChild(document.createTextNode('\240|\240')); + shortcuts_span.appendChild(cal_link); + + // Create calendarbox div. + // + // Markup looks like: + // + //
      + //

      + // + // February 2003 + //

      + //
      + // + //
      + //
      + // Yesterday | Today | Tomorrow + //
      + //

      Cancel

      + //
      + var cal_box = document.createElement('div'); + cal_box.style.display = 'none'; + cal_box.style.position = 'absolute'; + cal_box.className = 'calendarbox module'; + cal_box.setAttribute('id', DateTimeShortcuts.calendarDivName1 + num); + document.body.appendChild(cal_box); + addEvent(cal_box, 'click', cancelEventPropagation); + + // next-prev links + var cal_nav = quickElement('div', cal_box); + var cal_nav_prev = quickElement('a', cal_nav, '<', 'href', 'javascript:DateTimeShortcuts.drawPrev('+num+');'); + cal_nav_prev.className = 'calendarnav-previous'; + var cal_nav_next = quickElement('a', cal_nav, '>', 'href', 'javascript:DateTimeShortcuts.drawNext('+num+');'); + cal_nav_next.className = 'calendarnav-next'; + + // main box + var cal_main = quickElement('div', cal_box, '', 'id', DateTimeShortcuts.calendarDivName2 + num); + cal_main.className = 'calendar'; + DateTimeShortcuts.calendars[num] = new Calendar(DateTimeShortcuts.calendarDivName2 + num, DateTimeShortcuts.handleCalendarCallback(num)); + DateTimeShortcuts.calendars[num].drawCurrent(); + + // calendar shortcuts + var shortcuts = quickElement('div', cal_box); + shortcuts.className = 'calendar-shortcuts'; + quickElement('a', shortcuts, gettext('Yesterday'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', -1);'); + shortcuts.appendChild(document.createTextNode('\240|\240')); + quickElement('a', shortcuts, gettext('Today'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', 0);'); + shortcuts.appendChild(document.createTextNode('\240|\240')); + quickElement('a', shortcuts, gettext('Tomorrow'), 'href', 'javascript:DateTimeShortcuts.handleCalendarQuickLink(' + num + ', +1);'); + + // cancel bar + var cancel_p = quickElement('p', cal_box); + cancel_p.className = 'calendar-cancel'; + quickElement('a', cancel_p, gettext('Cancel'), 'href', 'javascript:DateTimeShortcuts.dismissCalendar(' + num + ');'); + django.jQuery(document).bind('keyup', function(event) { + if (event.which == 27) { + // ESC key closes popup + DateTimeShortcuts.dismissCalendar(num); + event.preventDefault(); + } + }); + }, + openCalendar: function(num) { + var cal_box = document.getElementById(DateTimeShortcuts.calendarDivName1+num) + var cal_link = document.getElementById(DateTimeShortcuts.calendarLinkName+num) + var inp = DateTimeShortcuts.calendarInputs[num]; + + // Determine if the current value in the input has a valid date. + // If so, draw the calendar with that date's year and month. + if (inp.value) { + var format = get_format('DATE_INPUT_FORMATS')[0]; + var selected = inp.value.strptime(format); + var year = selected.getFullYear(); + var month = selected.getMonth() + 1; + var re = /\d{4}/ + if (re.test(year.toString()) && month >= 1 && month <= 12) { + DateTimeShortcuts.calendars[num].drawDate(month, year, selected); + } + } + + // Recalculate the clockbox position + // is it left-to-right or right-to-left layout ? + if (getStyle(document.body,'direction')!='rtl') { + cal_box.style.left = findPosX(cal_link) + 17 + 'px'; + } + else { + // since style's width is in em, it'd be tough to calculate + // px value of it. let's use an estimated px for now + // TODO: IE returns wrong value for findPosX when in rtl mode + // (it returns as it was left aligned), needs to be fixed. + cal_box.style.left = findPosX(cal_link) - 180 + 'px'; + } + cal_box.style.top = Math.max(0, findPosY(cal_link) - 75) + 'px'; + + cal_box.style.display = 'block'; + addEvent(document, 'click', DateTimeShortcuts.dismissCalendarFunc[num]); + }, + dismissCalendar: function(num) { + document.getElementById(DateTimeShortcuts.calendarDivName1+num).style.display = 'none'; + removeEvent(document, 'click', DateTimeShortcuts.dismissCalendarFunc[num]); + }, + drawPrev: function(num) { + DateTimeShortcuts.calendars[num].drawPreviousMonth(); + }, + drawNext: function(num) { + DateTimeShortcuts.calendars[num].drawNextMonth(); + }, + handleCalendarCallback: function(num) { + var format = get_format('DATE_INPUT_FORMATS')[0]; + // the format needs to be escaped a little + format = format.replace('\\', '\\\\'); + format = format.replace('\r', '\\r'); + format = format.replace('\n', '\\n'); + format = format.replace('\t', '\\t'); + format = format.replace("'", "\\'"); + return ["function(y, m, d) { DateTimeShortcuts.calendarInputs[", + num, + "].value = new Date(y, m-1, d).strftime('", + format, + "');DateTimeShortcuts.calendarInputs[", + num, + "].focus();document.getElementById(DateTimeShortcuts.calendarDivName1+", + num, + ").style.display='none';}"].join(''); + }, + handleCalendarQuickLink: function(num, offset) { + var d = DateTimeShortcuts.now(); + d.setDate(d.getDate() + offset) + DateTimeShortcuts.calendarInputs[num].value = d.strftime(get_format('DATE_INPUT_FORMATS')[0]); + DateTimeShortcuts.calendarInputs[num].focus(); + DateTimeShortcuts.dismissCalendar(num); + } +} + +addEvent(window, 'load', DateTimeShortcuts.init); diff --git a/webapp/autoDeploy/static/admin/js/admin/RelatedObjectLookups.js b/webapp/autoDeploy/static/admin/js/admin/RelatedObjectLookups.js new file mode 100644 index 0000000..ffba7cd --- /dev/null +++ b/webapp/autoDeploy/static/admin/js/admin/RelatedObjectLookups.js @@ -0,0 +1,130 @@ +// Handles related-objects functionality: lookup link for raw_id_fields +// and Add Another links. + +function html_unescape(text) { + // Unescape a string that was escaped using django.utils.html.escape. + text = text.replace(/</g, '<'); + text = text.replace(/>/g, '>'); + text = text.replace(/"/g, '"'); + text = text.replace(/'/g, "'"); + text = text.replace(/&/g, '&'); + return text; +} + +// IE doesn't accept periods or dashes in the window name, but the element IDs +// we use to generate popup window names may contain them, therefore we map them +// to allowed characters in a reversible way so that we can locate the correct +// element when the popup window is dismissed. +function id_to_windowname(text) { + text = text.replace(/\./g, '__dot__'); + text = text.replace(/\-/g, '__dash__'); + return text; +} + +function windowname_to_id(text) { + text = text.replace(/__dot__/g, '.'); + text = text.replace(/__dash__/g, '-'); + return text; +} + +function showAdminPopup(triggeringLink, name_regexp) { + var name = triggeringLink.id.replace(name_regexp, ''); + name = id_to_windowname(name); + var href = triggeringLink.href; + if (href.indexOf('?') == -1) { + href += '?_popup=1'; + } else { + href += '&_popup=1'; + } + var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes'); + win.focus(); + return false; +} + +function showRelatedObjectLookupPopup(triggeringLink) { + return showAdminPopup(triggeringLink, /^lookup_/); +} + +function dismissRelatedLookupPopup(win, chosenId) { + var name = windowname_to_id(win.name); + var elem = document.getElementById(name); + if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) { + elem.value += ',' + chosenId; + } else { + document.getElementById(name).value = chosenId; + } + win.close(); +} + +function showRelatedObjectPopup(triggeringLink) { + var name = triggeringLink.id.replace(/^(change|add|delete)_/, ''); + name = id_to_windowname(name); + var href = triggeringLink.href; + var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes'); + win.focus(); + return false; +} + +function dismissAddRelatedObjectPopup(win, newId, newRepr) { + // newId and newRepr are expected to have previously been escaped by + // django.utils.html.escape. + newId = html_unescape(newId); + newRepr = html_unescape(newRepr); + var name = windowname_to_id(win.name); + var elem = document.getElementById(name); + var o; + if (elem) { + var elemName = elem.nodeName.toUpperCase(); + if (elemName == 'SELECT') { + o = new Option(newRepr, newId); + elem.options[elem.options.length] = o; + o.selected = true; + } else if (elemName == 'INPUT') { + if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) { + elem.value += ',' + newId; + } else { + elem.value = newId; + } + } + // Trigger a change event to update related links if required. + django.jQuery(elem).trigger('change'); + } else { + var toId = name + "_to"; + o = new Option(newRepr, newId); + SelectBox.add_to_cache(toId, o); + SelectBox.redisplay(toId); + } + win.close(); +} + +function dismissChangeRelatedObjectPopup(win, objId, newRepr, newId) { + objId = html_unescape(objId); + newRepr = html_unescape(newRepr); + var id = windowname_to_id(win.name).replace(/^edit_/, ''); + var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]); + var selects = django.jQuery(selectsSelector); + selects.find('option').each(function() { + if (this.value == objId) { + this.innerHTML = newRepr; + this.value = newId; + } + }); + win.close(); +}; + +function dismissDeleteRelatedObjectPopup(win, objId) { + objId = html_unescape(objId); + var id = windowname_to_id(win.name).replace(/^delete_/, ''); + var selectsSelector = interpolate('#%s, #%s_from, #%s_to', [id, id, id]); + var selects = django.jQuery(selectsSelector); + selects.find('option').each(function() { + if (this.value == objId) { + django.jQuery(this).remove(); + } + }).trigger('change'); + win.close(); +}; + +// Kept for backward compatibility +showAddAnotherPopup = showRelatedObjectPopup; +dismissAddAnotherPopup = dismissAddRelatedObjectPopup; diff --git a/webapp/autoDeploy/static/admin/js/calendar.js b/webapp/autoDeploy/static/admin/js/calendar.js new file mode 100644 index 0000000..458eece --- /dev/null +++ b/webapp/autoDeploy/static/admin/js/calendar.js @@ -0,0 +1,169 @@ +/* +calendar.js - Calendar functions by Adrian Holovaty +depends on core.js for utility functions like removeChildren or quickElement +*/ + +// CalendarNamespace -- Provides a collection of HTML calendar-related helper functions +var CalendarNamespace = { + monthsOfYear: gettext('January February March April May June July August September October November December').split(' '), + daysOfWeek: gettext('S M T W T F S').split(' '), + firstDayOfWeek: parseInt(get_format('FIRST_DAY_OF_WEEK')), + isLeapYear: function(year) { + return (((year % 4)==0) && ((year % 100)!=0) || ((year % 400)==0)); + }, + getDaysInMonth: function(month,year) { + var days; + if (month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12) { + days = 31; + } + else if (month==4 || month==6 || month==9 || month==11) { + days = 30; + } + else if (month==2 && CalendarNamespace.isLeapYear(year)) { + days = 29; + } + else { + days = 28; + } + return days; + }, + draw: function(month, year, div_id, callback, selected) { // month = 1-12, year = 1-9999 + var today = new Date(); + var todayDay = today.getDate(); + var todayMonth = today.getMonth()+1; + var todayYear = today.getFullYear(); + var todayClass = ''; + + // Use UTC functions here because the date field does not contain time + // and using the UTC function variants prevent the local time offset + // from altering the date, specifically the day field. For example: + // + // ``` + // var x = new Date('2013-10-02'); + // var day = x.getDate(); + // ``` + // + // The day variable above will be 1 instead of 2 in, say, US Pacific time + // zone. + var isSelectedMonth = false; + if (typeof selected != 'undefined') { + isSelectedMonth = (selected.getUTCFullYear() == year && (selected.getUTCMonth()+1) == month); + } + + month = parseInt(month); + year = parseInt(year); + var calDiv = document.getElementById(div_id); + removeChildren(calDiv); + var calTable = document.createElement('table'); + quickElement('caption', calTable, CalendarNamespace.monthsOfYear[month-1] + ' ' + year); + var tableBody = quickElement('tbody', calTable); + + // Draw days-of-week header + var tableRow = quickElement('tr', tableBody); + for (var i = 0; i < 7; i++) { + quickElement('th', tableRow, CalendarNamespace.daysOfWeek[(i + CalendarNamespace.firstDayOfWeek) % 7]); + } + + var startingPos = new Date(year, month-1, 1 - CalendarNamespace.firstDayOfWeek).getDay(); + var days = CalendarNamespace.getDaysInMonth(month, year); + + // Draw blanks before first of month + tableRow = quickElement('tr', tableBody); + for (var i = 0; i < startingPos; i++) { + var _cell = quickElement('td', tableRow, ' '); + _cell.className = "nonday"; + } + + // Draw days of month + var currentDay = 1; + for (var i = startingPos; currentDay <= days; i++) { + if (i%7 == 0 && currentDay != 1) { + tableRow = quickElement('tr', tableBody); + } + if ((currentDay==todayDay) && (month==todayMonth) && (year==todayYear)) { + todayClass='today'; + } else { + todayClass=''; + } + + // use UTC function; see above for explanation. + if (isSelectedMonth && currentDay == selected.getUTCDate()) { + if (todayClass != '') todayClass += " "; + todayClass += "selected"; + } + + var cell = quickElement('td', tableRow, '', 'class', todayClass); + + quickElement('a', cell, currentDay, 'href', 'javascript:void(' + callback + '('+year+','+month+','+currentDay+'));'); + currentDay++; + } + + // Draw blanks after end of month (optional, but makes for valid code) + while (tableRow.childNodes.length < 7) { + var _cell = quickElement('td', tableRow, ' '); + _cell.className = "nonday"; + } + + calDiv.appendChild(calTable); + } +} + +// Calendar -- A calendar instance +function Calendar(div_id, callback, selected) { + // div_id (string) is the ID of the element in which the calendar will + // be displayed + // callback (string) is the name of a JavaScript function that will be + // called with the parameters (year, month, day) when a day in the + // calendar is clicked + this.div_id = div_id; + this.callback = callback; + this.today = new Date(); + this.currentMonth = this.today.getMonth() + 1; + this.currentYear = this.today.getFullYear(); + if (typeof selected != 'undefined') { + this.selected = selected; + } +} +Calendar.prototype = { + drawCurrent: function() { + CalendarNamespace.draw(this.currentMonth, this.currentYear, this.div_id, this.callback, this.selected); + }, + drawDate: function(month, year, selected) { + this.currentMonth = month; + this.currentYear = year; + + if(selected) { + this.selected = selected; + } + + this.drawCurrent(); + }, + drawPreviousMonth: function() { + if (this.currentMonth == 1) { + this.currentMonth = 12; + this.currentYear--; + } + else { + this.currentMonth--; + } + this.drawCurrent(); + }, + drawNextMonth: function() { + if (this.currentMonth == 12) { + this.currentMonth = 1; + this.currentYear++; + } + else { + this.currentMonth++; + } + this.drawCurrent(); + }, + drawPreviousYear: function() { + this.currentYear--; + this.drawCurrent(); + }, + drawNextYear: function() { + this.currentYear++; + this.drawCurrent(); + } +} diff --git a/webapp/autoDeploy/static/admin/js/collapse.js b/webapp/autoDeploy/static/admin/js/collapse.js new file mode 100644 index 0000000..3b1f31b --- /dev/null +++ b/webapp/autoDeploy/static/admin/js/collapse.js @@ -0,0 +1,24 @@ +(function($) { + $(document).ready(function() { + // Add anchor tag for Show/Hide link + $("fieldset.collapse").each(function(i, elem) { + // Don't hide if fields in this fieldset have errors + if ($(elem).find("div.errors").length == 0) { + $(elem).addClass("collapsed").find("h2").first().append(' (' + gettext("Show") + + ')'); + } + }); + // Add toggle to anchor tag + $("fieldset.collapse a.collapse-toggle").click(function(ev) { + if ($(this).closest("fieldset").hasClass("collapsed")) { + // Show + $(this).text(gettext("Hide")).closest("fieldset").removeClass("collapsed").trigger("show.fieldset", [$(this).attr("id")]); + } else { + // Hide + $(this).text(gettext("Show")).closest("fieldset").addClass("collapsed").trigger("hide.fieldset", [$(this).attr("id")]); + } + return false; + }); + }); +})(django.jQuery); diff --git a/webapp/autoDeploy/static/admin/js/collapse.min.js b/webapp/autoDeploy/static/admin/js/collapse.min.js new file mode 100644 index 0000000..0a8c20e --- /dev/null +++ b/webapp/autoDeploy/static/admin/js/collapse.min.js @@ -0,0 +1,2 @@ +(function(a){a(document).ready(function(){a("fieldset.collapse").each(function(c,b){a(b).find("div.errors").length==0&&a(b).addClass("collapsed").find("h2").first().append(' ('+gettext("Show")+")")});a("fieldset.collapse a.collapse-toggle").click(function(){a(this).closest("fieldset").hasClass("collapsed")?a(this).text(gettext("Hide")).closest("fieldset").removeClass("collapsed").trigger("show.fieldset",[a(this).attr("id")]):a(this).text(gettext("Show")).closest("fieldset").addClass("collapsed").trigger("hide.fieldset", +[a(this).attr("id")]);return false})})})(django.jQuery); diff --git a/webapp/autoDeploy/static/admin/js/core.js b/webapp/autoDeploy/static/admin/js/core.js new file mode 100644 index 0000000..2c096aa --- /dev/null +++ b/webapp/autoDeploy/static/admin/js/core.js @@ -0,0 +1,246 @@ +// Core javascript helper functions + +// basic browser identification & version +var isOpera = (navigator.userAgent.indexOf("Opera")>=0) && parseFloat(navigator.appVersion); +var isIE = ((document.all) && (!isOpera)) && parseFloat(navigator.appVersion.split("MSIE ")[1].split(";")[0]); + +// Cross-browser event handlers. +function addEvent(obj, evType, fn) { + if (obj.addEventListener) { + obj.addEventListener(evType, fn, false); + return true; + } else if (obj.attachEvent) { + var r = obj.attachEvent("on" + evType, fn); + return r; + } else { + return false; + } +} + +function removeEvent(obj, evType, fn) { + if (obj.removeEventListener) { + obj.removeEventListener(evType, fn, false); + return true; + } else if (obj.detachEvent) { + obj.detachEvent("on" + evType, fn); + return true; + } else { + return false; + } +} + +function cancelEventPropagation(e) { + if (!e) e = window.event; + e.cancelBubble = true; + if (e.stopPropagation) e.stopPropagation(); +} + +// quickElement(tagType, parentReference [, textInChildNode, attribute, attributeValue ...]); +function quickElement() { + var obj = document.createElement(arguments[0]); + if (arguments[2]) { + var textNode = document.createTextNode(arguments[2]); + obj.appendChild(textNode); + } + var len = arguments.length; + for (var i = 3; i < len; i += 2) { + obj.setAttribute(arguments[i], arguments[i+1]); + } + arguments[1].appendChild(obj); + return obj; +} + +// "a" is reference to an object +function removeChildren(a) { + while (a.hasChildNodes()) a.removeChild(a.lastChild); +} + +// ---------------------------------------------------------------------------- +// Cross-browser xmlhttp object +// from http://jibbering.com/2002/4/httprequest.html +// ---------------------------------------------------------------------------- +var xmlhttp; +/*@cc_on @*/ +/*@if (@_jscript_version >= 5) + try { + xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); + } catch (e) { + try { + xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); + } catch (E) { + xmlhttp = false; + } + } +@else + xmlhttp = false; +@end @*/ +if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { + xmlhttp = new XMLHttpRequest(); +} + +// ---------------------------------------------------------------------------- +// Find-position functions by PPK +// See http://www.quirksmode.org/js/findpos.html +// ---------------------------------------------------------------------------- +function findPosX(obj) { + var curleft = 0; + if (obj.offsetParent) { + while (obj.offsetParent) { + curleft += obj.offsetLeft - ((isOpera) ? 0 : obj.scrollLeft); + obj = obj.offsetParent; + } + // IE offsetParent does not include the top-level + if (isIE && obj.parentElement){ + curleft += obj.offsetLeft - obj.scrollLeft; + } + } else if (obj.x) { + curleft += obj.x; + } + return curleft; +} + +function findPosY(obj) { + var curtop = 0; + if (obj.offsetParent) { + while (obj.offsetParent) { + curtop += obj.offsetTop - ((isOpera) ? 0 : obj.scrollTop); + obj = obj.offsetParent; + } + // IE offsetParent does not include the top-level + if (isIE && obj.parentElement){ + curtop += obj.offsetTop - obj.scrollTop; + } + } else if (obj.y) { + curtop += obj.y; + } + return curtop; +} + +//----------------------------------------------------------------------------- +// Date object extensions +// ---------------------------------------------------------------------------- + +Date.prototype.getTwelveHours = function() { + hours = this.getHours(); + if (hours == 0) { + return 12; + } + else { + return hours <= 12 ? hours : hours-12 + } +} + +Date.prototype.getTwoDigitMonth = function() { + return (this.getMonth() < 9) ? '0' + (this.getMonth()+1) : (this.getMonth()+1); +} + +Date.prototype.getTwoDigitDate = function() { + return (this.getDate() < 10) ? '0' + this.getDate() : this.getDate(); +} + +Date.prototype.getTwoDigitTwelveHour = function() { + return (this.getTwelveHours() < 10) ? '0' + this.getTwelveHours() : this.getTwelveHours(); +} + +Date.prototype.getTwoDigitHour = function() { + return (this.getHours() < 10) ? '0' + this.getHours() : this.getHours(); +} + +Date.prototype.getTwoDigitMinute = function() { + return (this.getMinutes() < 10) ? '0' + this.getMinutes() : this.getMinutes(); +} + +Date.prototype.getTwoDigitSecond = function() { + return (this.getSeconds() < 10) ? '0' + this.getSeconds() : this.getSeconds(); +} + +Date.prototype.getHourMinute = function() { + return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute(); +} + +Date.prototype.getHourMinuteSecond = function() { + return this.getTwoDigitHour() + ':' + this.getTwoDigitMinute() + ':' + this.getTwoDigitSecond(); +} + +Date.prototype.strftime = function(format) { + var fields = { + c: this.toString(), + d: this.getTwoDigitDate(), + H: this.getTwoDigitHour(), + I: this.getTwoDigitTwelveHour(), + m: this.getTwoDigitMonth(), + M: this.getTwoDigitMinute(), + p: (this.getHours() >= 12) ? 'PM' : 'AM', + S: this.getTwoDigitSecond(), + w: '0' + this.getDay(), + x: this.toLocaleDateString(), + X: this.toLocaleTimeString(), + y: ('' + this.getFullYear()).substr(2, 4), + Y: '' + this.getFullYear(), + '%' : '%' + }; + var result = '', i = 0; + while (i < format.length) { + if (format.charAt(i) === '%') { + result = result + fields[format.charAt(i + 1)]; + ++i; + } + else { + result = result + format.charAt(i); + } + ++i; + } + return result; +} + +// ---------------------------------------------------------------------------- +// String object extensions +// ---------------------------------------------------------------------------- +String.prototype.pad_left = function(pad_length, pad_string) { + var new_string = this; + for (var i = 0; new_string.length < pad_length; i++) { + new_string = pad_string + new_string; + } + return new_string; +} + +String.prototype.strptime = function(format) { + var split_format = format.split(/[.\-/]/); + var date = this.split(/[.\-/]/); + var i = 0; + while (i < split_format.length) { + switch (split_format[i]) { + case "%d": + var day = date[i]; + break; + case "%m": + var month = date[i] - 1; + break; + case "%Y": + var year = date[i]; + break; + case "%y": + var year = date[i]; + break; + } + ++i; + }; + return new Date(year, month, day); +} + +// ---------------------------------------------------------------------------- +// Get the computed style for and element +// ---------------------------------------------------------------------------- +function getStyle(oElm, strCssRule){ + var strValue = ""; + if(document.defaultView && document.defaultView.getComputedStyle){ + strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule); + } + else if(oElm.currentStyle){ + strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){ + return p1.toUpperCase(); + }); + strValue = oElm.currentStyle[strCssRule]; + } + return strValue; +} diff --git a/webapp/autoDeploy/static/admin/js/inlines.js b/webapp/autoDeploy/static/admin/js/inlines.js new file mode 100644 index 0000000..0bfcd34 --- /dev/null +++ b/webapp/autoDeploy/static/admin/js/inlines.js @@ -0,0 +1,272 @@ +/** + * Django admin inlines + * + * Based on jQuery Formset 1.1 + * @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com) + * @requires jQuery 1.2.6 or later + * + * Copyright (c) 2009, Stanislaus Madueke + * All rights reserved. + * + * Spiced up with Code from Zain Memon's GSoC project 2009 + * and modified for Django by Jannis Leidel, Travis Swicegood and Julien Phalip. + * + * Licensed under the New BSD License + * See: http://www.opensource.org/licenses/bsd-license.php + */ +(function($) { + $.fn.formset = function(opts) { + var options = $.extend({}, $.fn.formset.defaults, opts); + var $this = $(this); + var $parent = $this.parent(); + var updateElementIndex = function(el, prefix, ndx) { + var id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))"); + var replacement = prefix + "-" + ndx; + if ($(el).prop("for")) { + $(el).prop("for", $(el).prop("for").replace(id_regex, replacement)); + } + if (el.id) { + el.id = el.id.replace(id_regex, replacement); + } + if (el.name) { + el.name = el.name.replace(id_regex, replacement); + } + }; + var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS").prop("autocomplete", "off"); + var nextIndex = parseInt(totalForms.val(), 10); + var maxForms = $("#id_" + options.prefix + "-MAX_NUM_FORMS").prop("autocomplete", "off"); + // only show the add button if we are allowed to add more items, + // note that max_num = None translates to a blank string. + var showAddButton = maxForms.val() === '' || (maxForms.val()-totalForms.val()) > 0; + $this.each(function(i) { + $(this).not("." + options.emptyCssClass).addClass(options.formCssClass); + }); + if ($this.length && showAddButton) { + var addButton; + if ($this.prop("tagName") == "TR") { + // If forms are laid out as table rows, insert the + // "add" button in a new table row: + var numCols = this.eq(-1).children().length; + $parent.append('' + options.addText + ""); + addButton = $parent.find("tr:last a"); + } else { + // Otherwise, insert it immediately after the last form: + $this.filter(":last").after('"); + addButton = $this.filter(":last").next().find("a"); + } + addButton.click(function(e) { + e.preventDefault(); + var totalForms = $("#id_" + options.prefix + "-TOTAL_FORMS"); + var template = $("#" + options.prefix + "-empty"); + var row = template.clone(true); + row.removeClass(options.emptyCssClass) + .addClass(options.formCssClass) + .attr("id", options.prefix + "-" + nextIndex); + if (row.is("tr")) { + // If the forms are laid out in table rows, insert + // the remove button into the last table cell: + row.children(":last").append('"); + } else if (row.is("ul") || row.is("ol")) { + // If they're laid out as an ordered/unordered list, + // insert an
    • after the last list item: + row.append('
    • ' + options.deleteText + "
    • "); + } else { + // Otherwise, just insert the remove button as the + // last child element of the form's container: + row.children(":first").append('' + options.deleteText + ""); + } + row.find("*").each(function() { + updateElementIndex(this, options.prefix, totalForms.val()); + }); + // Insert the new form when it has been fully edited + row.insertBefore($(template)); + // Update number of total forms + $(totalForms).val(parseInt(totalForms.val(), 10) + 1); + nextIndex += 1; + // Hide add button in case we've hit the max, except we want to add infinitely + if ((maxForms.val() !== '') && (maxForms.val()-totalForms.val()) <= 0) { + addButton.parent().hide(); + } + // The delete button of each row triggers a bunch of other things + row.find("a." + options.deleteCssClass).click(function(e) { + e.preventDefault(); + // Remove the parent form containing this button: + var row = $(this).parents("." + options.formCssClass); + row.remove(); + nextIndex -= 1; + // If a post-delete callback was provided, call it with the deleted form: + if (options.removed) { + options.removed(row); + } + // Update the TOTAL_FORMS form count. + var forms = $("." + options.formCssClass); + $("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length); + // Show add button again once we drop below max + if ((maxForms.val() === '') || (maxForms.val()-forms.length) > 0) { + addButton.parent().show(); + } + // Also, update names and ids for all remaining form controls + // so they remain in sequence: + for (var i=0, formCount=forms.length; i0;i.each(function(){a(this).not("."+ +b.emptyCssClass).addClass(b.formCssClass)});if(i.length&&l){var f;if(i.prop("tagName")=="TR"){i=this.eq(-1).children().length;g.append(''+b.addText+"");f=g.find("tr:last a")}else{i.filter(":last").after('");f=i.filter(":last").next().find("a")}f.click(function(e){e.preventDefault();var k=a("#id_"+b.prefix+"-TOTAL_FORMS");e=a("#"+ +b.prefix+"-empty");var h=e.clone(true);h.removeClass(b.emptyCssClass).addClass(b.formCssClass).attr("id",b.prefix+"-"+d);if(h.is("tr"))h.children(":last").append('");else h.is("ul")||h.is("ol")?h.append('
    • '+b.deleteText+"
    • "):h.children(":first").append(''+b.deleteText+""); +h.find("*").each(function(){m(this,b.prefix,k.val())});h.insertBefore(a(e));a(k).val(parseInt(k.val(),10)+1);d+=1;c.val()!==""&&c.val()-k.val()<=0&&f.parent().hide();h.find("a."+b.deleteCssClass).click(function(j){j.preventDefault();j=a(this).parents("."+b.formCssClass);j.remove();d-=1;b.removed&&b.removed(j);j=a("."+b.formCssClass);a("#id_"+b.prefix+"-TOTAL_FORMS").val(j.length);if(c.val()===""||c.val()-j.length>0)f.parent().show();for(var n=0,o=j.length;n= 0 && j < len ? [ this[j] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(null); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: deletedIds.sort, + splice: deletedIds.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var src, copyIsArray, copy, name, options, clone, + target = arguments[0] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + target = {}; + } + + // extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values + if ( (options = arguments[ i ]) != null ) { + // Extend the base object + for ( name in options ) { + src = target[ name ]; + copy = options[ name ]; + + // Prevent never-ending loop + if ( target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( copyIsArray ) { + copyIsArray = false; + clone = src && jQuery.isArray(src) ? src : []; + + } else { + clone = src && jQuery.isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend({ + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + // See test/unit/core.js for details concerning isFunction. + // Since version 1.3, DOM methods and functions like alert + // aren't supported. They return false on IE (#2968). + isFunction: function( obj ) { + return jQuery.type(obj) === "function"; + }, + + isArray: Array.isArray || function( obj ) { + return jQuery.type(obj) === "array"; + }, + + isWindow: function( obj ) { + /* jshint eqeqeq: false */ + return obj != null && obj == obj.window; + }, + + isNumeric: function( obj ) { + // parseFloat NaNs numeric-cast false positives (null|true|false|"") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + // adding 1 corrects loss of precision from parseFloat (#15100) + return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; + }, + + isEmptyObject: function( obj ) { + var name; + for ( name in obj ) { + return false; + } + return true; + }, + + isPlainObject: function( obj ) { + var key; + + // Must be an Object. + // Because of IE, we also have to check the presence of the constructor property. + // Make sure that DOM nodes and window objects don't pass through, as well + if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + return false; + } + + try { + // Not own constructor property must be Object + if ( obj.constructor && + !hasOwn.call(obj, "constructor") && + !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { + return false; + } + } catch ( e ) { + // IE8,9 Will throw exceptions on certain host objects #9897 + return false; + } + + // Support: IE<9 + // Handle iteration over inherited properties before own properties. + if ( support.ownLast ) { + for ( key in obj ) { + return hasOwn.call( obj, key ); + } + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + for ( key in obj ) {} + + return key === undefined || hasOwn.call( obj, key ); + }, + + type: function( obj ) { + if ( obj == null ) { + return obj + ""; + } + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call(obj) ] || "object" : + typeof obj; + }, + + // Evaluates a script in a global context + // Workarounds based on findings by Jim Driscoll + // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context + globalEval: function( data ) { + if ( data && jQuery.trim( data ) ) { + // We use execScript on Internet Explorer + // We use an anonymous function so that context is window + // rather than jQuery in Firefox + ( window.execScript || function( data ) { + window[ "eval" ].call( window, data ); + } )( data ); + } + }, + + // Convert dashed to camelCase; used by the css and data modules + // Microsoft forgot to hump their vendor prefix (#9572) + camelCase: function( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); + }, + + nodeName: function( elem, name ) { + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + }, + + // args is for internal usage only + each: function( obj, callback, args ) { + var value, + i = 0, + length = obj.length, + isArray = isArraylike( obj ); + + if ( args ) { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.apply( obj[ i ], args ); + + if ( value === false ) { + break; + } + } + } + + // A special, fast, case for the most common use of each + } else { + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } else { + for ( i in obj ) { + value = callback.call( obj[ i ], i, obj[ i ] ); + + if ( value === false ) { + break; + } + } + } + } + + return obj; + }, + + // Support: Android<4.1, IE<9 + trim: function( text ) { + return text == null ? + "" : + ( text + "" ).replace( rtrim, "" ); + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArraylike( Object(arr) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + var len; + + if ( arr ) { + if ( indexOf ) { + return indexOf.call( arr, elem, i ); + } + + len = arr.length; + i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; + + for ( ; i < len; i++ ) { + // Skip accessing in sparse arrays + if ( i in arr && arr[ i ] === elem ) { + return i; + } + } + } + + return -1; + }, + + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + while ( j < len ) { + first[ i++ ] = second[ j++ ]; + } + + // Support: IE<9 + // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) + if ( len !== len ) { + while ( second[j] !== undefined ) { + first[ i++ ] = second[ j++ ]; + } + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var value, + i = 0, + length = elems.length, + isArray = isArraylike( elems ), + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArray ) { + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return concat.apply( [], ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // Bind a function to a context, optionally partially applying any + // arguments. + proxy: function( fn, context ) { + var args, proxy, tmp; + + if ( typeof context === "string" ) { + tmp = fn[ context ]; + context = fn; + fn = tmp; + } + + // Quick check to determine if target is callable, in the spec + // this throws a TypeError, but we will just return undefined. + if ( !jQuery.isFunction( fn ) ) { + return undefined; + } + + // Simulated bind + args = slice.call( arguments, 2 ); + proxy = function() { + return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); + }; + + // Set the guid of unique handler to the same of original handler, so it can be removed + proxy.guid = fn.guid = fn.guid || jQuery.guid++; + + return proxy; + }, + + now: function() { + return +( new Date() ); + }, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +}); + +// Populate the class2type map +jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +}); + +function isArraylike( obj ) { + var length = obj.length, + type = jQuery.type( obj ); + + if ( type === "function" || jQuery.isWindow( obj ) ) { + return false; + } + + if ( obj.nodeType === 1 && length ) { + return true; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.2.0-pre + * http://sizzlejs.com/ + * + * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors + * Released under the MIT license + * http://jquery.org/license + * + * Date: 2014-12-16 + */ +(function( window ) { + +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // General-purpose constants + MAX_NEGATIVE = 1 << 31, + + // Instance methods + hasOwn = ({}).hasOwnProperty, + arr = [], + pop = arr.pop, + push_native = arr.push, + push = arr.push, + slice = arr.slice, + // Use a stripped-down indexOf as it's faster than native + // http://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[i] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + // http://www.w3.org/TR/css3-syntax/#characters + characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", + + // Loosely modeled on CSS identifier characters + // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors + // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = characterEncoding.replace( "w", "w#" ), + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + + "*\\]", + + pseudos = ":(" + characterEncoding + ")(?:\\((" + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), + + rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + characterEncoding + ")" ), + "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), + "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + rescape = /'|\\/g, + + // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), + funescape = function( _, escaped, escapedWhitespace ) { + var high = "0x" + escaped - 0x10000; + // NaN means non-codepoint + // Support: Firefox<24 + // Workaround erroneous numeric interpretation of +"0x" + return high !== high || escapedWhitespace ? + escaped : + high < 0 ? + // BMP codepoint + String.fromCharCode( high + 0x10000 ) : + // Supplemental Plane codepoint (surrogate pair) + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }; + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + (arr = slice.call( preferredDoc.childNodes )), + preferredDoc.childNodes + ); + // Support: Android<4.0 + // Detect silently failing push.apply + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + push_native.apply( target, slice.call(els) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + // Can't trust NodeList.length + while ( (target[j++] = els[i++]) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var match, elem, m, nodeType, + // QSA vars + i, groups, old, nid, newContext, newSelector; + + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + + context = context || document; + results = results || []; + nodeType = context.nodeType; + + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + if ( !seed && documentIsHTML ) { + + // Try to shortcut find operations when possible (e.g., not under DocumentFragment) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + // Speed-up: Sizzle("#ID") + if ( (m = match[1]) ) { + if ( nodeType === 9 ) { + elem = context.getElementById( m ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document (jQuery #6963) + if ( elem && elem.parentNode ) { + // Handle the case where IE, Opera, and Webkit return items + // by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + } else { + // Context is not a document + if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && + contains( context, elem ) && elem.id === m ) { + results.push( elem ); + return results; + } + } + + // Speed-up: Sizzle("TAG") + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Speed-up: Sizzle(".CLASS") + } else if ( (m = match[3]) && support.getElementsByClassName ) { + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // QSA path + if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { + nid = old = expando; + newContext = context; + newSelector = nodeType !== 1 && selector; + + // qSA works strangely on Element-rooted queries + // We can work around this by specifying an extra ID on the root + // and working up from there (Thanks to Andrew Dupont for the technique) + // IE 8 doesn't work on object elements + if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { + groups = tokenize( selector ); + + if ( (old = context.getAttribute("id")) ) { + nid = old.replace( rescape, "\\$&" ); + } else { + context.setAttribute( "id", nid ); + } + nid = "[id='" + nid + "'] "; + + i = groups.length; + while ( i-- ) { + groups[i] = nid + toSelector( groups[i] ); + } + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; + newSelector = groups.join(","); + } + + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch(qsaError) { + } finally { + if ( !old ) { + context.removeAttribute("id"); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return (cache[ key + " " ] = value); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created div and expects a boolean result + */ +function assert( fn ) { + var div = document.createElement("div"); + + try { + return !!fn( div ); + } catch (e) { + return false; + } finally { + // Remove from its parent by default + if ( div.parentNode ) { + div.parentNode.removeChild( div ); + } + // release memory in IE + div = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split("|"), + i = attrs.length; + + while ( i-- ) { + Expr.attrHandle[ arr[i] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + ( ~b.sourceIndex || MAX_NEGATIVE ) - + ( ~a.sourceIndex || MAX_NEGATIVE ); + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( (cur = cur.nextSibling) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return (name === "input" || name === "button") && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction(function( argument ) { + argument = +argument; + return markFunction(function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ (j = matchIndexes[i]) ] ) { + seed[j] = !(matches[j] = seed[j]); + } + } + }); + }); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + // documentElement is verified for cases where it doesn't yet exist + // (such as loading iframes in IE - #4833) + var documentElement = elem && (elem.ownerDocument || elem).documentElement; + return documentElement ? documentElement.nodeName !== "HTML" : false; +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, parent, + doc = node ? node.ownerDocument || node : preferredDoc; + + // If no document and documentElement is available, return + if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Set our document + document = doc; + docElem = doc.documentElement; + parent = doc.defaultView; + + // Support: IE>8 + // If iframe document is assigned to "document" variable and if iframe has been reloaded, + // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 + // IE6-8 do not support the defaultView property so parent will be undefined + if ( parent && parent !== parent.top ) { + // IE11 does not have attachEvent, so all must suffer + if ( parent.addEventListener ) { + parent.addEventListener( "unload", unloadHandler, false ); + } else if ( parent.attachEvent ) { + parent.attachEvent( "onunload", unloadHandler ); + } + } + + /* Support tests + ---------------------------------------------------------------------- */ + documentIsHTML = !isXML( doc ); + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert(function( div ) { + div.className = "i"; + return !div.getAttribute("className"); + }); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert(function( div ) { + div.appendChild( doc.createComment("") ); + return !div.getElementsByTagName("*").length; + }); + + // Support: IE<9 + support.getElementsByClassName = rnative.test( doc.getElementsByClassName ); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert(function( div ) { + docElem.appendChild( div ).id = expando; + return !doc.getElementsByName || !doc.getElementsByName( expando ).length; + }); + + // ID find and filter + if ( support.getById ) { + Expr.find["ID"] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var m = context.getElementById( id ); + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + return m && m.parentNode ? [ m ] : []; + } + }; + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute("id") === attrId; + }; + }; + } else { + // Support: IE6/7 + // getElementById is not reliable as a find shortcut + delete Expr.find["ID"]; + + Expr.filter["ID"] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id"); + return node && node.value === attrId; + }; + }; + } + + // Tag + Expr.find["TAG"] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( (elem = results[i++]) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { + if ( documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See http://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert(function( div ) { + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // http://bugs.jquery.com/ticket/12359 + docElem.appendChild( div ).innerHTML = "" + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( div.querySelectorAll("[msallowcapture^='']").length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !div.querySelectorAll("[selected]").length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+ + if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push("~="); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":checked").length ) { + rbuggyQSA.push(":checked"); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibing-combinator selector` fails + if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push(".#.+[+~]"); + } + }); + + assert(function( div ) { + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = doc.createElement("input"); + input.setAttribute( "type", "hidden" ); + div.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( div.querySelectorAll("[name=d]").length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( !div.querySelectorAll(":enabled").length ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Opera 10-11 does not throw on post-comma invalid pseudos + div.querySelectorAll("*,:x"); + rbuggyQSA.push(",.*:"); + }); + } + + if ( (support.matchesSelector = rnative.test( (matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector) )) ) { + + assert(function( div ) { + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( div, "div" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( div, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + }); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully does not implement inclusive descendent + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + )); + } : + function( a, b ) { + if ( b ) { + while ( (b = b.parentNode) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { + + // Choose the first element that is related to our preferred document + if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { + return -1; + } + if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + return a === doc ? -1 : + b === doc ? 1 : + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( (cur = cur.parentNode) ) { + ap.unshift( cur ); + } + cur = b; + while ( (cur = cur.parentNode) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[i] === bp[i] ) { + i++; + } + + return i ? + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[i], bp[i] ) : + + // Otherwise nodes in our document sort first + ap[i] === preferredDoc ? -1 : + bp[i] === preferredDoc ? 1 : + 0; + }; + + return doc; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + // Make sure that attribute selectors are quoted + expr = expr.replace( rattributeQuotes, "='$1']" ); + + if ( support.matchesSelector && documentIsHTML && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch (e) {} + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + // Set document vars if needed + if ( ( context.ownerDocument || context ) !== document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + // Set document vars if needed + if ( ( elem.ownerDocument || elem ) !== document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + (val = elem.getAttributeNode(name)) && val.specified ? + val.value : + null; +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( (elem = results[i++]) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + // If no nodeType, this is expected to be an array + while ( (node = elem[i++]) ) { + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[1] = match[1].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape ); + + if ( match[2] === "~=" ) { + match[3] = " " + match[3] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[1] = match[1].toLowerCase(); + + if ( match[1].slice( 0, 3 ) === "nth" ) { + // nth-* requires argument + if ( !match[3] ) { + Sizzle.error( match[0] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); + match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); + + // other types prohibit arguments + } else if ( match[3] ) { + Sizzle.error( match[0] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[6] && match[2]; + + if ( matchExpr["CHILD"].test( match[0] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[3] ) { + match[2] = match[4] || match[5] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + // Get excess from tokenize (recursively) + (excess = tokenize( unquoted, true )) && + // advance to the next closing parenthesis + (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { + + // excess is a negative index + match[0] = match[0].slice( 0, excess ); + match[2] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { return true; } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && + classCache( className, function( elem ) { + return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute("class") || "" ); + }); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + }; + }, + + "CHILD": function( type, what, argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, context, xml ) { + var cache, outerCache, node, diff, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( (node = node[ dir ]) ) { + if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { + return false; + } + } + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + // Seek `elem` from a previously-cached index + outerCache = parent[ expando ] || (parent[ expando ] = {}); + cache = outerCache[ type ] || []; + nodeIndex = cache[0] === dirruns && cache[1]; + diff = cache[0] === dirruns && cache[2]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( (node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + (diff = nodeIndex = 0) || start.pop()) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + outerCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + // Use previously-cached element index if available + } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { + diff = cache[1]; + + // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) + } else { + // Use the same loop as above to seek `elem` from the start + while ( (node = ++nodeIndex && node && node[ dir ] || + (diff = nodeIndex = 0) || start.pop()) ) { + + if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { + // Cache the index of each encountered element + if ( useCache ) { + (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction(function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[i] ); + seed[ idx ] = !( matches[ idx ] = matched[i] ); + } + }) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + // Potentially complex pseudos + "not": markFunction(function( selector ) { + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction(function( seed, matches, context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( (elem = unmatched[i]) ) { + seed[i] = !(matches[i] = elem); + } + } + }) : + function( elem, context, xml ) { + input[0] = elem; + matcher( input, null, xml, results ); + // Don't keep the element (issue #299) + input[0] = null; + return !results.pop(); + }; + }), + + "has": markFunction(function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + }), + + "contains": markFunction(function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; + }; + }), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + // lang value must be a valid identifier + if ( !ridentifier.test(lang || "") ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( (elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); + return false; + }; + }), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); + }, + + // Boolean properties + "enabled": function( elem ) { + return elem.disabled === false; + }, + + "disabled": function( elem ) { + return elem.disabled === true; + }, + + "checked": function( elem ) { + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); + }, + + "selected": function( elem ) { + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos["empty"]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo(function() { + return [ 0 ]; + }), + + "last": createPositionalPseudo(function( matchIndexes, length ) { + return [ length - 1 ]; + }), + + "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + }), + + "even": createPositionalPseudo(function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "odd": createPositionalPseudo(function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }), + + "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + }) + } +}; + +Expr.pseudos["nth"] = Expr.pseudos["eq"]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || (match = rcomma.exec( soFar )) ) { + if ( match ) { + // Don't consume trailing commas as valid + soFar = soFar.slice( match[0].length ) || soFar; + } + groups.push( (tokens = []) ); + } + + matched = false; + + // Combinators + if ( (match = rcombinators.exec( soFar )) ) { + matched = match.shift(); + tokens.push({ + value: matched, + // Cast descendant combinators to space + type: match[0].replace( rtrim, " " ) + }); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || + (match = preFilters[ type ]( match ))) ) { + matched = match.shift(); + tokens.push({ + value: matched, + type: type, + matches: match + }); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[i].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + checkNonElements = base && dir === "parentNode", + doneName = done++; + + return combinator.first ? + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching + if ( xml ) { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( (elem = elem[ dir ]) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || (elem[ expando ] = {}); + if ( (oldCache = outerCache[ dir ]) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return (newCache[ 2 ] = oldCache[ 2 ]); + } else { + // Reuse newcache so results back-propagate to previous elements + outerCache[ dir ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) { + return true; + } + } + } + } + } + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[i]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[0]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[i], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( (elem = unmatched[i]) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction(function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( (elem = temp[i]) ) { + matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) ) { + // Restore matcherIn since elem is not yet a final match + temp.push( (matcherIn[i] = elem) ); + } + } + postFinder( null, (matcherOut = []), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( (elem = matcherOut[i]) && + (temp = postFinder ? indexOf( seed, elem ) : preMap[i]) > -1 ) { + + seed[temp] = !(results[temp] = elem); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + }); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[0].type ], + implicitRelative = leadingRelative || Expr.relative[" "], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + (checkContext = context).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( (matcher = Expr.relative[ tokens[i].type ]) ) { + matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; + } else { + matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[j].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find["TAG"]( "*", outermost ), + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1), + len = elems.length; + + if ( outermost ) { + outermostContext = context !== document && context; + } + + // Add elements passing elementMatchers directly to results + // Keep `i` a string if there are no elements so `matchedCount` will be "00" below + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && (elem = elems[i]) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + while ( (matcher = elementMatchers[j++]) ) { + if ( matcher( elem, context, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + // They will have gone through all possible matchers + if ( (elem = !matcher && elem) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // Apply set filters to unmatched elements + matchedCount += i; + if ( bySet && i !== matchedCount ) { + j = 0; + while ( (matcher = setMatchers[j++]) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !(unmatched[i] || setMatched[i]) ) { + setMatched[i] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[i] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( (selector = compiled.selector || selector) ); + + results = results || []; + + // Try to minimize operations if there is no seed and only one group + if ( match.length === 1 ) { + + // Take a shortcut and set the context if the root selector is an ID + tokens = match[0] = match[0].slice( 0 ); + if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && + support.getById && context.nodeType === 9 && documentIsHTML && + Expr.relative[ tokens[1].type ] ) { + + context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[i]; + + // Abort if we hit a combinator + if ( Expr.relative[ (type = token.type) ] ) { + break; + } + if ( (find = Expr.find[ type ]) ) { + // Search, expanding context for leading sibling combinators + if ( (seed = find( + token.matches[0].replace( runescape, funescape ), + rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context + )) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; + +// Support: Chrome 14-35+ +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert(function( div1 ) { + // Should return 1, but returns 4 (following) + return div1.compareDocumentPosition( document.createElement("div") ) & 1; +}); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert(function( div ) { + div.innerHTML = ""; + return div.firstChild.getAttribute("href") === "#" ; +}) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + }); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert(function( div ) { + div.innerHTML = ""; + div.firstChild.setAttribute( "value", "" ); + return div.firstChild.getAttribute( "value" ) === ""; +}) ) { + addHandle( "value", function( elem, name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + }); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert(function( div ) { + return div.getAttribute("disabled") == null; +}) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + (val = elem.getAttributeNode( name )) && val.specified ? + val.value : + null; + } + }); +} + +return Sizzle; + +})( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; +jQuery.expr[":"] = jQuery.expr.pseudos; +jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; + + + +var rneedsContext = jQuery.expr.match.needsContext; + +var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/); + + + +var risSimple = /^.[^:#\[\.,]*$/; + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( jQuery.isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + /* jshint -W018 */ + return !!qualifier.call( elem, i, elem ) !== not; + }); + + } + + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + }); + + } + + if ( typeof qualifier === "string" ) { + if ( risSimple.test( qualifier ) ) { + return jQuery.filter( qualifier, elements, not ); + } + + qualifier = jQuery.filter( qualifier, elements ); + } + + return jQuery.grep( elements, function( elem ) { + return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not; + }); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + return elems.length === 1 && elem.nodeType === 1 ? + jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : + jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + })); +}; + +jQuery.fn.extend({ + find: function( selector ) { + var i, + ret = [], + self = this, + len = self.length; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + }) ); + } + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + // Needed because $( selector, context ) becomes $( context ).find( selector ) + ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); + ret.selector = this.selector ? this.selector + " " + selector : selector; + return ret; + }, + filter: function( selector ) { + return this.pushStack( winnow(this, selector || [], false) ); + }, + not: function( selector ) { + return this.pushStack( winnow(this, selector || [], true) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +}); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // Use the correct document accordingly with window argument (sandbox) + document = window.document, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, + + init = jQuery.fn.init = function( selector, context ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && (match[1] || !context) ) { + + // HANDLE: $(html) -> $(array) + if ( match[1] ) { + context = context instanceof jQuery ? context[0] : context; + + // scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[1], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + // Properties of context are called as methods if possible + if ( jQuery.isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[2] ); + + // Check parentNode to catch when Blackberry 4.6 returns + // nodes that are no longer in the document #6963 + if ( elem && elem.parentNode ) { + // Handle the case where IE and Opera return items + // by name instead of ID + if ( elem.id !== match[2] ) { + return rootjQuery.find( selector ); + } + + // Otherwise, we inject the element directly into the jQuery object + this.length = 1; + this[0] = elem; + } + + this.context = document; + this.selector = selector; + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || rootjQuery ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this.context = this[0] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( jQuery.isFunction( selector ) ) { + return typeof rootjQuery.ready !== "undefined" ? + rootjQuery.ready( selector ) : + // Execute immediately if ready is not present + selector( jQuery ); + } + + if ( selector.selector !== undefined ) { + this.selector = selector.selector; + this.context = selector.context; + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + // methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.extend({ + dir: function( elem, dir, until ) { + var matched = [], + cur = elem[ dir ]; + + while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { + if ( cur.nodeType === 1 ) { + matched.push( cur ); + } + cur = cur[dir]; + } + return matched; + }, + + sibling: function( n, elem ) { + var r = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + r.push( n ); + } + } + + return r; + } +}); + +jQuery.fn.extend({ + has: function( target ) { + var i, + targets = jQuery( target, this ), + len = targets.length; + + return this.filter(function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( this, targets[i] ) ) { + return true; + } + } + }); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? + jQuery( selectors, context || this.context ) : + 0; + + for ( ; i < l; i++ ) { + for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { + // Always skip document fragments + if ( cur.nodeType < 11 && (pos ? + pos.index(cur) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector(cur, selectors)) ) { + + matched.push( cur ); + break; + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); + }, + + // Determine the position of an element within + // the matched set of elements + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; + } + + // index in selector + if ( typeof elem === "string" ) { + return jQuery.inArray( this[0], jQuery( elem ) ); + } + + // Locate the position of the desired element + return jQuery.inArray( + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[0] : elem, this ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.unique( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter(selector) + ); + } +}); + +function sibling( cur, dir ) { + do { + cur = cur[ dir ]; + } while ( cur && cur.nodeType !== 1 ); + + return cur; +} + +jQuery.each({ + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return jQuery.dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, i, until ) { + return jQuery.dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return jQuery.dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return jQuery.dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, i, until ) { + return jQuery.dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, i, until ) { + return jQuery.dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return jQuery.sibling( elem.firstChild ); + }, + contents: function( elem ) { + return jQuery.nodeName( elem, "iframe" ) ? + elem.contentDocument || elem.contentWindow.document : + jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var ret = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + ret = jQuery.filter( selector, ret ); + } + + if ( this.length > 1 ) { + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + ret = jQuery.unique( ret ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + ret = ret.reverse(); + } + } + + return this.pushStack( ret ); + }; +}); +var rnotwhite = (/\S+/g); + + + +// String to Object options format cache +var optionsCache = {}; + +// Convert String-formatted options into Object-formatted ones and store in cache +function createOptions( options ) { + var object = optionsCache[ options ] = {}; + jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) { + object[ flag ] = true; + }); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + ( optionsCache[ options ] || createOptions( options ) ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + // Last fire value (for non-forgettable lists) + memory, + // Flag to know if list was already fired + fired, + // End of the loop when firing + firingLength, + // Index of currently firing callback (modified by remove if needed) + firingIndex, + // First callback to fire (used internally by add and fireWith) + firingStart, + // Actual callback list + list = [], + // Stack of fire calls for repeatable lists + stack = !options.once && [], + // Fire callbacks + fire = function( data ) { + memory = options.memory && data; + fired = true; + firingIndex = firingStart || 0; + firingStart = 0; + firingLength = list.length; + firing = true; + for ( ; list && firingIndex < firingLength; firingIndex++ ) { + if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { + memory = false; // To prevent further calls using add + break; + } + } + firing = false; + if ( list ) { + if ( stack ) { + if ( stack.length ) { + fire( stack.shift() ); + } + } else if ( memory ) { + list = []; + } else { + self.disable(); + } + } + }, + // Actual Callbacks object + self = { + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + // First, we save the current length + var start = list.length; + (function add( args ) { + jQuery.each( args, function( _, arg ) { + var type = jQuery.type( arg ); + if ( type === "function" ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && type !== "string" ) { + // Inspect recursively + add( arg ); + } + }); + })( arguments ); + // Do we need to add the callbacks to the + // current firing batch? + if ( firing ) { + firingLength = list.length; + // With memory, if we're not firing then + // we should call right away + } else if ( memory ) { + firingStart = start; + fire( memory ); + } + } + return this; + }, + // Remove a callback from the list + remove: function() { + if ( list ) { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + // Handle firing indexes + if ( firing ) { + if ( index <= firingLength ) { + firingLength--; + } + if ( index <= firingIndex ) { + firingIndex--; + } + } + } + }); + } + return this; + }, + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); + }, + // Remove all callbacks from the list + empty: function() { + list = []; + firingLength = 0; + return this; + }, + // Have the list do nothing anymore + disable: function() { + list = stack = memory = undefined; + return this; + }, + // Is it disabled? + disabled: function() { + return !list; + }, + // Lock the list in its current state + lock: function() { + stack = undefined; + if ( !memory ) { + self.disable(); + } + return this; + }, + // Is it locked? + locked: function() { + return !stack; + }, + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( list && ( !fired || stack ) ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + if ( firing ) { + stack.push( args ); + } else { + fire( args ); + } + } + return this; + }, + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +jQuery.extend({ + + Deferred: function( func ) { + var tuples = [ + // action, add listener, listener list, final state + [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], + [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], + [ "notify", "progress", jQuery.Callbacks("memory") ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + then: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + return jQuery.Deferred(function( newDefer ) { + jQuery.each( tuples, function( i, tuple ) { + var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; + // deferred[ done | fail | progress ] for forwarding actions to newDefer + deferred[ tuple[1] ](function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && jQuery.isFunction( returned.promise ) ) { + returned.promise() + .done( newDefer.resolve ) + .fail( newDefer.reject ) + .progress( newDefer.notify ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); + } + }); + }); + fns = null; + }).promise(); + }, + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Keep pipe for back-compat + promise.pipe = promise.then; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 3 ]; + + // promise[ done | fail | progress ] = list.add + promise[ tuple[1] ] = list.add; + + // Handle state + if ( stateString ) { + list.add(function() { + // state = [ resolved | rejected ] + state = stateString; + + // [ reject_list | resolve_list ].disable; progress_list.lock + }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); + } + + // deferred[ resolve | reject | notify ] + deferred[ tuple[0] ] = function() { + deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); + return this; + }; + deferred[ tuple[0] + "With" ] = list.fireWith; + }); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( subordinate /* , ..., subordinateN */ ) { + var i = 0, + resolveValues = slice.call( arguments ), + length = resolveValues.length, + + // the count of uncompleted subordinates + remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, + + // the master Deferred. If resolveValues consist of only a single Deferred, just use that. + deferred = remaining === 1 ? subordinate : jQuery.Deferred(), + + // Update function for both resolve and progress values + updateFunc = function( i, contexts, values ) { + return function( value ) { + contexts[ i ] = this; + values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( values === progressValues ) { + deferred.notifyWith( contexts, values ); + + } else if ( !(--remaining) ) { + deferred.resolveWith( contexts, values ); + } + }; + }, + + progressValues, progressContexts, resolveContexts; + + // add listeners to Deferred subordinates; treat others as resolved + if ( length > 1 ) { + progressValues = new Array( length ); + progressContexts = new Array( length ); + resolveContexts = new Array( length ); + for ( ; i < length; i++ ) { + if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { + resolveValues[ i ].promise() + .done( updateFunc( i, resolveContexts, resolveValues ) ) + .fail( deferred.reject ) + .progress( updateFunc( i, progressContexts, progressValues ) ); + } else { + --remaining; + } + } + } + + // if we're not waiting on anything, resolve the master + if ( !remaining ) { + deferred.resolveWith( resolveContexts, resolveValues ); + } + + return deferred.promise(); + } +}); + + +// The deferred used on DOM ready +var readyList; + +jQuery.fn.ready = function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; +}; + +jQuery.extend({ + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). + if ( !document.body ) { + return setTimeout( jQuery.ready ); + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + jQuery( document ).off( "ready" ); + } + } +}); + +/** + * Clean-up method for dom ready events + */ +function detach() { + if ( document.addEventListener ) { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); + + } else { + document.detachEvent( "onreadystatechange", completed ); + window.detachEvent( "onload", completed ); + } +} + +/** + * The ready event handler and self cleanup method + */ +function completed() { + // readyState === "complete" is good enough for us to call the dom ready in oldIE + if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { + detach(); + jQuery.ready(); + } +} + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // we once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + // Standards-based browsers support DOMContentLoaded + } else if ( document.addEventListener ) { + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); + + // If IE event model is used + } else { + // Ensure firing before onload, maybe late but safe also for iframes + document.attachEvent( "onreadystatechange", completed ); + + // A fallback to window.onload, that will always work + window.attachEvent( "onload", completed ); + + // If IE and not a frame + // continually check to see if the document is ready + var top = false; + + try { + top = window.frameElement == null && document.documentElement; + } catch(e) {} + + if ( top && top.doScroll ) { + (function doScrollCheck() { + if ( !jQuery.isReady ) { + + try { + // Use the trick by Diego Perini + // http://javascript.nwbox.com/IEContentLoaded/ + top.doScroll("left"); + } catch(e) { + return setTimeout( doScrollCheck, 50 ); + } + + // detach all dom ready events + detach(); + + // and execute any waiting functions + jQuery.ready(); + } + })(); + } + } + } + return readyList.promise( obj ); +}; + + +var strundefined = typeof undefined; + + + +// Support: IE<9 +// Iteration over object's inherited properties before its own +var i; +for ( i in jQuery( support ) ) { + break; +} +support.ownLast = i !== "0"; + +// Note: most support tests are defined in their respective modules. +// false until the test is run +support.inlineBlockNeedsLayout = false; + +// Execute ASAP in case we need to set body.style.zoom +jQuery(function() { + // Minified: var a,b,c,d + var val, div, body, container; + + body = document.getElementsByTagName( "body" )[ 0 ]; + if ( !body || !body.style ) { + // Return for frameset docs that don't have a body + return; + } + + // Setup + div = document.createElement( "div" ); + container = document.createElement( "div" ); + container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; + body.appendChild( container ).appendChild( div ); + + if ( typeof div.style.zoom !== strundefined ) { + // Support: IE<8 + // Check if natively block-level elements act like inline-block + // elements when setting their display to 'inline' and giving + // them layout + div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; + + support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; + if ( val ) { + // Prevent IE 6 from affecting layout for positioned elements #11048 + // Prevent IE from shrinking the body in IE 7 mode #12869 + // Support: IE<8 + body.style.zoom = 1; + } + } + + body.removeChild( container ); +}); + + + + +(function() { + var div = document.createElement( "div" ); + + // Execute the test only if not already executed in another module. + if (support.deleteExpando == null) { + // Support: IE<9 + support.deleteExpando = true; + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + } + + // Null elements to avoid leaks in IE. + div = null; +})(); + + +/** + * Determines whether an object can have data + */ +jQuery.acceptData = function( elem ) { + var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ], + nodeType = +elem.nodeType || 1; + + // Do not set data on non-element DOM nodes because it will not be cleared (#8335). + return nodeType !== 1 && nodeType !== 9 ? + false : + + // Nodes accept data unless otherwise specified; rejection can be conditional + !noData || noData !== true && elem.getAttribute("classid") === noData; +}; + + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /([A-Z])/g; + +function dataAttr( elem, key, data ) { + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + + var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); + + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = data === "true" ? true : + data === "false" ? false : + data === "null" ? null : + // Only convert to a number if it doesn't change the string + +data + "" === data ? +data : + rbrace.test( data ) ? jQuery.parseJSON( data ) : + data; + } catch( e ) {} + + // Make sure we set the data so it isn't changed later + jQuery.data( elem, key, data ); + + } else { + data = undefined; + } + } + + return data; +} + +// checks a cache object for emptiness +function isEmptyDataObject( obj ) { + var name; + for ( name in obj ) { + + // if the public data object is empty, the private is still empty + if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { + continue; + } + if ( name !== "toJSON" ) { + return false; + } + } + + return true; +} + +function internalData( elem, name, data, pvt /* Internal Use Only */ ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var ret, thisCache, + internalKey = jQuery.expando, + + // We have to handle DOM nodes and JS objects differently because IE6-7 + // can't GC object references properly across the DOM-JS boundary + isNode = elem.nodeType, + + // Only DOM nodes need the global jQuery cache; JS object data is + // attached directly to the object so GC can occur automatically + cache = isNode ? jQuery.cache : elem, + + // Only defining an ID for JS objects if its cache already exists allows + // the code to shortcut on the same path as a DOM node with no cache + id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; + + // Avoid doing any more work than we need to when trying to get data on an + // object that has no data at all + if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) { + return; + } + + if ( !id ) { + // Only DOM nodes need a new unique ID for each element since their data + // ends up in the global cache + if ( isNode ) { + id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++; + } else { + id = internalKey; + } + } + + if ( !cache[ id ] ) { + // Avoid exposing jQuery metadata on plain JS objects when the object + // is serialized using JSON.stringify + cache[ id ] = isNode ? {} : { toJSON: jQuery.noop }; + } + + // An object can be passed to jQuery.data instead of a key/value pair; this gets + // shallow copied over onto the existing cache + if ( typeof name === "object" || typeof name === "function" ) { + if ( pvt ) { + cache[ id ] = jQuery.extend( cache[ id ], name ); + } else { + cache[ id ].data = jQuery.extend( cache[ id ].data, name ); + } + } + + thisCache = cache[ id ]; + + // jQuery data() is stored in a separate object inside the object's internal data + // cache in order to avoid key collisions between internal data and user-defined + // data. + if ( !pvt ) { + if ( !thisCache.data ) { + thisCache.data = {}; + } + + thisCache = thisCache.data; + } + + if ( data !== undefined ) { + thisCache[ jQuery.camelCase( name ) ] = data; + } + + // Check for both converted-to-camel and non-converted data property names + // If a data property was specified + if ( typeof name === "string" ) { + + // First Try to find as-is property data + ret = thisCache[ name ]; + + // Test for null|undefined property data + if ( ret == null ) { + + // Try to find the camelCased property + ret = thisCache[ jQuery.camelCase( name ) ]; + } + } else { + ret = thisCache; + } + + return ret; +} + +function internalRemoveData( elem, name, pvt ) { + if ( !jQuery.acceptData( elem ) ) { + return; + } + + var thisCache, i, + isNode = elem.nodeType, + + // See jQuery.data for more information + cache = isNode ? jQuery.cache : elem, + id = isNode ? elem[ jQuery.expando ] : jQuery.expando; + + // If there is already no cache entry for this object, there is no + // purpose in continuing + if ( !cache[ id ] ) { + return; + } + + if ( name ) { + + thisCache = pvt ? cache[ id ] : cache[ id ].data; + + if ( thisCache ) { + + // Support array or space separated string names for data keys + if ( !jQuery.isArray( name ) ) { + + // try the string as a key before any manipulation + if ( name in thisCache ) { + name = [ name ]; + } else { + + // split the camel cased version by spaces unless a key with the spaces exists + name = jQuery.camelCase( name ); + if ( name in thisCache ) { + name = [ name ]; + } else { + name = name.split(" "); + } + } + } else { + // If "name" is an array of keys... + // When data is initially created, via ("key", "val") signature, + // keys will be converted to camelCase. + // Since there is no way to tell _how_ a key was added, remove + // both plain key and camelCase key. #12786 + // This will only penalize the array argument path. + name = name.concat( jQuery.map( name, jQuery.camelCase ) ); + } + + i = name.length; + while ( i-- ) { + delete thisCache[ name[i] ]; + } + + // If there is no data left in the cache, we want to continue + // and let the cache object itself get destroyed + if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) { + return; + } + } + } + + // See jQuery.data for more information + if ( !pvt ) { + delete cache[ id ].data; + + // Don't destroy the parent cache unless the internal data object + // had been the only thing left in it + if ( !isEmptyDataObject( cache[ id ] ) ) { + return; + } + } + + // Destroy the cache + if ( isNode ) { + jQuery.cleanData( [ elem ], true ); + + // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) + /* jshint eqeqeq: false */ + } else if ( support.deleteExpando || cache != cache.window ) { + /* jshint eqeqeq: true */ + delete cache[ id ]; + + // When all else fails, null + } else { + cache[ id ] = null; + } +} + +jQuery.extend({ + cache: {}, + + // The following elements (space-suffixed to avoid Object.prototype collisions) + // throw uncatchable exceptions if you attempt to set expando properties + noData: { + "applet ": true, + "embed ": true, + // ...but Flash objects (which have this classid) *can* handle expandos + "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" + }, + + hasData: function( elem ) { + elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; + return !!elem && !isEmptyDataObject( elem ); + }, + + data: function( elem, name, data ) { + return internalData( elem, name, data ); + }, + + removeData: function( elem, name ) { + return internalRemoveData( elem, name ); + }, + + // For internal use only. + _data: function( elem, name, data ) { + return internalData( elem, name, data, true ); + }, + + _removeData: function( elem, name ) { + return internalRemoveData( elem, name, true ); + } +}); + +jQuery.fn.extend({ + data: function( key, value ) { + var i, name, data, + elem = this[0], + attrs = elem && elem.attributes; + + // Special expections of .data basically thwart jQuery.access, + // so implement the relevant behavior ourselves + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = jQuery.data( elem ); + + if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE11+ + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = jQuery.camelCase( name.slice(5) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + jQuery._data( elem, "parsedAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each(function() { + jQuery.data( this, key ); + }); + } + + return arguments.length > 1 ? + + // Sets one value + this.each(function() { + jQuery.data( this, key, value ); + }) : + + // Gets one value + // Try to fetch any internally stored data first + elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined; + }, + + removeData: function( key ) { + return this.each(function() { + jQuery.removeData( this, key ); + }); + } +}); + + +jQuery.extend({ + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = jQuery._data( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || jQuery.isArray(data) ) { + queue = jQuery._data( elem, type, jQuery.makeArray(data) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // not intended for public consumption - generates a queueHooks object, or returns the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return jQuery._data( elem, key ) || jQuery._data( elem, key, { + empty: jQuery.Callbacks("once memory").add(function() { + jQuery._removeData( elem, type + "queue" ); + jQuery._removeData( elem, key ); + }) + }); + } +}); + +jQuery.fn.extend({ + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[0], type ); + } + + return data === undefined ? + this : + this.each(function() { + var queue = jQuery.queue( this, type, data ); + + // ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[0] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + }); + }, + dequeue: function( type ) { + return this.each(function() { + jQuery.dequeue( this, type ); + }); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = jQuery._data( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +}); +var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source; + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var isHidden = function( elem, el ) { + // isHidden might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); + }; + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + length = elems.length, + bulk = key == null; + + // Sets many values + if ( jQuery.type( key ) === "object" ) { + chainable = true; + for ( i in key ) { + jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !jQuery.isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < length; i++ ) { + fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); + } + } + } + + return chainable ? + elems : + + // Gets + bulk ? + fn.call( elems ) : + length ? fn( elems[0], key ) : emptyGet; +}; +var rcheckableType = (/^(?:checkbox|radio)$/i); + + + +(function() { + // Minified: var a,b,c + var input = document.createElement( "input" ), + div = document.createElement( "div" ), + fragment = document.createDocumentFragment(); + + // Setup + div.innerHTML = "
      a"; + + // IE strips leading whitespace when .innerHTML is used + support.leadingWhitespace = div.firstChild.nodeType === 3; + + // Make sure that tbody elements aren't automatically inserted + // IE will insert them into empty tables + support.tbody = !div.getElementsByTagName( "tbody" ).length; + + // Make sure that link elements get serialized correctly by innerHTML + // This requires a wrapper element in IE + support.htmlSerialize = !!div.getElementsByTagName( "link" ).length; + + // Makes sure cloning an html5 element does not cause problems + // Where outerHTML is undefined, this still works + support.html5Clone = + document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav>"; + + // Check if a disconnected checkbox will retain its checked + // value of true after appended to the DOM (IE6/7) + input.type = "checkbox"; + input.checked = true; + fragment.appendChild( input ); + support.appendChecked = input.checked; + + // Make sure textarea (and checkbox) defaultValue is properly cloned + // Support: IE6-IE11+ + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; + + // #11217 - WebKit loses check when the name is after the checked attribute + fragment.appendChild( div ); + div.innerHTML = ""; + + // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 + // old WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE<9 + // Opera does not clone events (and typeof div.attachEvent === undefined). + // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() + support.noCloneEvent = true; + if ( div.attachEvent ) { + div.attachEvent( "onclick", function() { + support.noCloneEvent = false; + }); + + div.cloneNode( true ).click(); + } + + // Execute the test only if not already executed in another module. + if (support.deleteExpando == null) { + // Support: IE<9 + support.deleteExpando = true; + try { + delete div.test; + } catch( e ) { + support.deleteExpando = false; + } + } +})(); + + +(function() { + var i, eventName, + div = document.createElement( "div" ); + + // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event) + for ( i in { submit: true, change: true, focusin: true }) { + eventName = "on" + i; + + if ( !(support[ i + "Bubbles" ] = eventName in window) ) { + // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) + div.setAttribute( eventName, "t" ); + support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false; + } + } + + // Null elements to avoid leaks in IE. + div = null; +})(); + + +var rformElems = /^(?:input|select|textarea)$/i, + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/, + rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + var tmp, events, t, handleObjIn, + special, eventHandle, handleObj, + handlers, type, namespaces, origType, + elemData = jQuery._data( elem ); + + // Don't attach events to noData or text/comment nodes (but allow plain objects) + if ( !elemData ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !(events = elemData.events) ) { + events = elemData.events = {}; + } + if ( !(eventHandle = elemData.handle) ) { + eventHandle = elemData.handle = function( e ) { + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ? + jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : + undefined; + }; + // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events + eventHandle.elem = elem; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend({ + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join(".") + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !(handlers = events[ type ]) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener/attachEvent if the special events handler returns false + if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + // Bind the global event handler to the element + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle, false ); + + } else if ( elem.attachEvent ) { + elem.attachEvent( "on" + type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + // Nullify elem to prevent memory leaks in IE + elem = null; + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + var j, handleObj, tmp, + origCount, t, events, + special, handlers, type, + namespaces, origType, + elemData = jQuery.hasData( elem ) && jQuery._data( elem ); + + if ( !elemData || !(events = elemData.events) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnotwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[t] ) || []; + type = origType = tmp[1]; + namespaces = ( tmp[2] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + delete elemData.handle; + + // removeData also checks for emptiness and clears the expando if empty + // so use it instead of delete + jQuery._removeData( elem, "events" ); + } + }, + + trigger: function( event, data, elem, onlyHandlers ) { + var handle, ontype, cur, + bubbleType, special, tmp, i, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; + + cur = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf(".") >= 0 ) { + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split("."); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf(":") < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join("."); + event.namespace_re = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === (elem.ownerDocument || document) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { + + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && jQuery.acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && + jQuery.acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name name as the event. + // Can't use an .isFunction() check here because IE6/7 fails that test. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + try { + elem[ type ](); + } catch ( e ) { + // IE<9 dies on focus/blur to hidden element (#1486,#12518) + // only reproducible on winXP IE8 native, not IE9 in IE8 mode + } + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + dispatch: function( event ) { + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( event ); + + var i, ret, handleObj, matched, j, + handlerQueue = [], + args = slice.call( arguments ), + handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[0] = event; + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { + + // Triggered event must either 1) have no namespace, or + // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). + if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) + .apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( (event.result = ret) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var sel, handleObj, matches, i, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + // Black-hole SVG instance trees (#13180) + // Avoid non-left-click bubbling in Firefox (#3861) + if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { + + /* jshint eqeqeq: false */ + for ( ; cur != this; cur = cur.parentNode || this ) { + /* jshint eqeqeq: true */ + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { + matches = []; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matches[ sel ] === undefined ) { + matches[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) >= 0 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matches[ sel ] ) { + matches.push( handleObj ); + } + } + if ( matches.length ) { + handlerQueue.push({ elem: cur, handlers: matches }); + } + } + } + } + + // Add the remaining (directly-bound) handlers + if ( delegateCount < handlers.length ) { + handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); + } + + return handlerQueue; + }, + + fix: function( event ) { + if ( event[ jQuery.expando ] ) { + return event; + } + + // Create a writable copy of the event object and normalize some properties + var i, prop, copy, + type = event.type, + originalEvent = event, + fixHook = this.fixHooks[ type ]; + + if ( !fixHook ) { + this.fixHooks[ type ] = fixHook = + rmouseEvent.test( type ) ? this.mouseHooks : + rkeyEvent.test( type ) ? this.keyHooks : + {}; + } + copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; + + event = new jQuery.Event( originalEvent ); + + i = copy.length; + while ( i-- ) { + prop = copy[ i ]; + event[ prop ] = originalEvent[ prop ]; + } + + // Support: IE<9 + // Fix target property (#1925) + if ( !event.target ) { + event.target = originalEvent.srcElement || document; + } + + // Support: Chrome 23+, Safari? + // Target should not be a text node (#504, #13143) + if ( event.target.nodeType === 3 ) { + event.target = event.target.parentNode; + } + + // Support: IE<9 + // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) + event.metaKey = !!event.metaKey; + + return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; + }, + + // Includes some event props shared by KeyEvent and MouseEvent + props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), + + fixHooks: {}, + + keyHooks: { + props: "char charCode key keyCode".split(" "), + filter: function( event, original ) { + + // Add which for key events + if ( event.which == null ) { + event.which = original.charCode != null ? original.charCode : original.keyCode; + } + + return event; + } + }, + + mouseHooks: { + props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), + filter: function( event, original ) { + var body, eventDoc, doc, + button = original.button, + fromElement = original.fromElement; + + // Calculate pageX/Y if missing and clientX/Y available + if ( event.pageX == null && original.clientX != null ) { + eventDoc = event.target.ownerDocument || document; + doc = eventDoc.documentElement; + body = eventDoc.body; + + event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); + event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); + } + + // Add relatedTarget, if necessary + if ( !event.relatedTarget && fromElement ) { + event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + // Note: button is not normalized, so don't use it + if ( !event.which && button !== undefined ) { + event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); + } + + return event; + } + }, + + special: { + load: { + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + focus: { + // Fire native event if possible so blur/focus sequence is correct + trigger: function() { + if ( this !== safeActiveElement() && this.focus ) { + try { + this.focus(); + return false; + } catch ( e ) { + // Support: IE<9 + // If we error on focus to hidden element (#1486, #12518), + // let .trigger() run the handlers + } + } + }, + delegateType: "focusin" + }, + blur: { + trigger: function() { + if ( this === safeActiveElement() && this.blur ) { + this.blur(); + return false; + } + }, + delegateType: "focusout" + }, + click: { + // For checkbox, fire native event so checked state will be right + trigger: function() { + if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { + this.click(); + return false; + } + }, + + // For cross-browser consistency, don't fire native .click() on links + _default: function( event ) { + return jQuery.nodeName( event.target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + }, + + simulate: function( type, elem, event, bubble ) { + // Piggyback on a donor event to simulate a different one. + // Fake originalEvent to avoid donor's stopPropagation, but if the + // simulated event prevents default then we do the same on the donor. + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true, + originalEvent: {} + } + ); + if ( bubble ) { + jQuery.event.trigger( e, null, elem ); + } else { + jQuery.event.dispatch.call( elem, e ); + } + if ( e.isDefaultPrevented() ) { + event.preventDefault(); + } + } +}; + +jQuery.removeEvent = document.removeEventListener ? + function( elem, type, handle ) { + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle, false ); + } + } : + function( elem, type, handle ) { + var name = "on" + type; + + if ( elem.detachEvent ) { + + // #8545, #7054, preventing memory leaks for custom events in IE6-8 + // detachEvent needed property on element, by name of that event, to properly expose it to GC + if ( typeof elem[ name ] === strundefined ) { + elem[ name ] = null; + } + + elem.detachEvent( name, handle ); + } + }; + +jQuery.Event = function( src, props ) { + // Allow instantiation without the 'new' keyword + if ( !(this instanceof jQuery.Event) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + // Support: IE < 9, Android < 4.0 + src.returnValue === false ? + returnTrue : + returnFalse; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || jQuery.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + if ( !e ) { + return; + } + + // If preventDefault exists, run it on the original event + if ( e.preventDefault ) { + e.preventDefault(); + + // Support: IE + // Otherwise set the returnValue property of the original event to false + } else { + e.returnValue = false; + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + if ( !e ) { + return; + } + // If stopPropagation exists, run it on the original event + if ( e.stopPropagation ) { + e.stopPropagation(); + } + + // Support: IE + // Set the cancelBubble property of the original event to true + e.cancelBubble = true; + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && e.stopImmediatePropagation ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Create mouseenter/leave events using mouseover/out and event-time checks +jQuery.each({ + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mousenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || (related !== target && !jQuery.contains( target, related )) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +}); + +// IE submit delegation +if ( !support.submitBubbles ) { + + jQuery.event.special.submit = { + setup: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Lazy-add a submit handler when a descendant form may potentially be submitted + jQuery.event.add( this, "click._submit keypress._submit", function( e ) { + // Node name check avoids a VML-related crash in IE (#9807) + var elem = e.target, + form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; + if ( form && !jQuery._data( form, "submitBubbles" ) ) { + jQuery.event.add( form, "submit._submit", function( event ) { + event._submit_bubble = true; + }); + jQuery._data( form, "submitBubbles", true ); + } + }); + // return undefined since we don't need an event listener + }, + + postDispatch: function( event ) { + // If form was submitted by the user, bubble the event up the tree + if ( event._submit_bubble ) { + delete event._submit_bubble; + if ( this.parentNode && !event.isTrigger ) { + jQuery.event.simulate( "submit", this.parentNode, event, true ); + } + } + }, + + teardown: function() { + // Only need this for delegated form submit events + if ( jQuery.nodeName( this, "form" ) ) { + return false; + } + + // Remove delegated handlers; cleanData eventually reaps submit handlers attached above + jQuery.event.remove( this, "._submit" ); + } + }; +} + +// IE change delegation and checkbox/radio fix +if ( !support.changeBubbles ) { + + jQuery.event.special.change = { + + setup: function() { + + if ( rformElems.test( this.nodeName ) ) { + // IE doesn't fire change on a check/radio until blur; trigger it on click + // after a propertychange. Eat the blur-change in special.change.handle. + // This still fires onchange a second time for check/radio after blur. + if ( this.type === "checkbox" || this.type === "radio" ) { + jQuery.event.add( this, "propertychange._change", function( event ) { + if ( event.originalEvent.propertyName === "checked" ) { + this._just_changed = true; + } + }); + jQuery.event.add( this, "click._change", function( event ) { + if ( this._just_changed && !event.isTrigger ) { + this._just_changed = false; + } + // Allow triggered, simulated change events (#11500) + jQuery.event.simulate( "change", this, event, true ); + }); + } + return false; + } + // Delegated event; lazy-add a change handler on descendant inputs + jQuery.event.add( this, "beforeactivate._change", function( e ) { + var elem = e.target; + + if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { + jQuery.event.add( elem, "change._change", function( event ) { + if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { + jQuery.event.simulate( "change", this.parentNode, event, true ); + } + }); + jQuery._data( elem, "changeBubbles", true ); + } + }); + }, + + handle: function( event ) { + var elem = event.target; + + // Swallow native change events from checkbox/radio, we already triggered them above + if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { + return event.handleObj.handler.apply( this, arguments ); + } + }, + + teardown: function() { + jQuery.event.remove( this, "._change" ); + + return !rformElems.test( this.nodeName ); + } + }; +} + +// Create "bubbling" focus and blur events +if ( !support.focusinBubbles ) { + jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + var doc = this.ownerDocument || this, + attaches = jQuery._data( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + jQuery._data( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this, + attaches = jQuery._data( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + jQuery._removeData( doc, fix ); + } else { + jQuery._data( doc, fix, attaches ); + } + } + }; + }); +} + +jQuery.fn.extend({ + + on: function( types, selector, data, fn, /*INTERNAL*/ one ) { + var type, origFn; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + this.on( type, selector, data, types[ type ], one ); + } + return this; + } + + if ( data == null && fn == null ) { + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return this; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return this.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + }); + }, + one: function( types, selector, data, fn ) { + return this.on( types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each(function() { + jQuery.event.remove( this, types, fn, selector ); + }); + }, + + trigger: function( type, data ) { + return this.each(function() { + jQuery.event.trigger( type, data, this ); + }); + }, + triggerHandler: function( type, data ) { + var elem = this[0]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +}); + + +function createSafeFragment( document ) { + var list = nodeNames.split( "|" ), + safeFrag = document.createDocumentFragment(); + + if ( safeFrag.createElement ) { + while ( list.length ) { + safeFrag.createElement( + list.pop() + ); + } + } + return safeFrag; +} + +var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", + rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, + rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), + rleadingWhitespace = /^\s+/, + rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, + rtagName = /<([\w:]+)/, + rtbody = /\s*$/g, + + // We have to close these tags to support XHTML (#13200) + wrapMap = { + option: [ 1, "" ], + legend: [ 1, "
      ", "
      " ], + area: [ 1, "", "" ], + param: [ 1, "", "" ], + thead: [ 1, "", "
      " ], + tr: [ 2, "", "
      " ], + col: [ 2, "", "
      " ], + td: [ 3, "", "
      " ], + + // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, + // unless wrapped in a div with non-breaking characters in front of it. + _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X
      ", "
      " ] + }, + safeFragment = createSafeFragment( document ), + fragmentDiv = safeFragment.appendChild( document.createElement("div") ); + +wrapMap.optgroup = wrapMap.option; +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +function getAll( context, tag ) { + var elems, elem, + i = 0, + found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) : + typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) : + undefined; + + if ( !found ) { + for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { + if ( !tag || jQuery.nodeName( elem, tag ) ) { + found.push( elem ); + } else { + jQuery.merge( found, getAll( elem, tag ) ); + } + } + } + + return tag === undefined || tag && jQuery.nodeName( context, tag ) ? + jQuery.merge( [ context ], found ) : + found; +} + +// Used in buildFragment, fixes the defaultChecked property +function fixDefaultChecked( elem ) { + if ( rcheckableType.test( elem.type ) ) { + elem.defaultChecked = elem.checked; + } +} + +// Support: IE<8 +// Manipulating tables requires a tbody +function manipulationTarget( elem, content ) { + return jQuery.nodeName( elem, "table" ) && + jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ? + + elem.getElementsByTagName("tbody")[0] || + elem.appendChild( elem.ownerDocument.createElement("tbody") ) : + elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + var match = rscriptTypeMasked.exec( elem.type ); + if ( match ) { + elem.type = match[1]; + } else { + elem.removeAttribute("type"); + } + return elem; +} + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var elem, + i = 0; + for ( ; (elem = elems[i]) != null; i++ ) { + jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); + } +} + +function cloneCopyEvent( src, dest ) { + + if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { + return; + } + + var type, i, l, + oldData = jQuery._data( src ), + curData = jQuery._data( dest, oldData ), + events = oldData.events; + + if ( events ) { + delete curData.handle; + curData.events = {}; + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + + // make the cloned public data object a copy from the original + if ( curData.data ) { + curData.data = jQuery.extend( {}, curData.data ); + } +} + +function fixCloneNodeIssues( src, dest ) { + var nodeName, e, data; + + // We do not need to do anything for non-Elements + if ( dest.nodeType !== 1 ) { + return; + } + + nodeName = dest.nodeName.toLowerCase(); + + // IE6-8 copies events bound via attachEvent when using cloneNode. + if ( !support.noCloneEvent && dest[ jQuery.expando ] ) { + data = jQuery._data( dest ); + + for ( e in data.events ) { + jQuery.removeEvent( dest, e, data.handle ); + } + + // Event data gets referenced instead of copied if the expando gets copied too + dest.removeAttribute( jQuery.expando ); + } + + // IE blanks contents when cloning scripts, and tries to evaluate newly-set text + if ( nodeName === "script" && dest.text !== src.text ) { + disableScript( dest ).text = src.text; + restoreScript( dest ); + + // IE6-10 improperly clones children of object elements using classid. + // IE10 throws NoModificationAllowedError if parent is null, #12132. + } else if ( nodeName === "object" ) { + if ( dest.parentNode ) { + dest.outerHTML = src.outerHTML; + } + + // This path appears unavoidable for IE9. When cloning an object + // element in IE9, the outerHTML strategy above is not sufficient. + // If the src has innerHTML and the destination does not, + // copy the src.innerHTML into the dest.innerHTML. #10324 + if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { + dest.innerHTML = src.innerHTML; + } + + } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + // IE6-8 fails to persist the checked state of a cloned checkbox + // or radio button. Worse, IE6-7 fail to give the cloned element + // a checked appearance if the defaultChecked value isn't also set + + dest.defaultChecked = dest.checked = src.checked; + + // IE6-7 get confused and end up setting the value of a cloned + // checkbox/radio button to an empty string instead of "on" + if ( dest.value !== src.value ) { + dest.value = src.value; + } + + // IE6-8 fails to return the selected option to the default selected + // state when cloning options + } else if ( nodeName === "option" ) { + dest.defaultSelected = dest.selected = src.defaultSelected; + + // IE6-8 fails to set the defaultValue to the correct value when + // cloning other types of input fields + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +jQuery.extend({ + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var destElements, node, clone, i, srcElements, + inPage = jQuery.contains( elem.ownerDocument, elem ); + + if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { + clone = elem.cloneNode( true ); + + // IE<=8 does not properly clone detached, unknown element nodes + } else { + fragmentDiv.innerHTML = elem.outerHTML; + fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); + } + + if ( (!support.noCloneEvent || !support.noCloneChecked) && + (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { + + // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + // Fix all IE cloning issues + for ( i = 0; (node = srcElements[i]) != null; ++i ) { + // Ensure that the destination node is not null; Fixes #9587 + if ( destElements[i] ) { + fixCloneNodeIssues( node, destElements[i] ); + } + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0; (node = srcElements[i]) != null; i++ ) { + cloneCopyEvent( node, destElements[i] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + destElements = srcElements = node = null; + + // Return the cloned set + return clone; + }, + + buildFragment: function( elems, context, scripts, selection ) { + var j, elem, contains, + tmp, tag, tbody, wrap, + l = elems.length, + + // Ensure a safe fragment + safe = createSafeFragment( context ), + + nodes = [], + i = 0; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( jQuery.type( elem ) === "object" ) { + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || safe.appendChild( context.createElement("div") ); + + // Deserialize a standard representation + tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + + tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1>" ) + wrap[2]; + + // Descend through wrappers to the right content + j = wrap[0]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Manually add leading whitespace removed by IE + if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { + nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); + } + + // Remove IE's autoinserted from table fragments + if ( !support.tbody ) { + + // String was a , *may* have spurious + elem = tag === "table" && !rtbody.test( elem ) ? + tmp.firstChild : + + // String was a bare or + wrap[1] === "
      " && !rtbody.test( elem ) ? + tmp : + 0; + + j = elem && elem.childNodes.length; + while ( j-- ) { + if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { + elem.removeChild( tbody ); + } + } + } + + jQuery.merge( nodes, tmp.childNodes ); + + // Fix #12392 for WebKit and IE > 9 + tmp.textContent = ""; + + // Fix #12392 for oldIE + while ( tmp.firstChild ) { + tmp.removeChild( tmp.firstChild ); + } + + // Remember the top-level container for proper cleanup + tmp = safe.lastChild; + } + } + } + + // Fix #11356: Clear elements from fragment + if ( tmp ) { + safe.removeChild( tmp ); + } + + // Reset defaultChecked for any radios and checkboxes + // about to be appended to the DOM in IE 6/7 (#8060) + if ( !support.appendChecked ) { + jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); + } + + i = 0; + while ( (elem = nodes[ i++ ]) ) { + + // #4087 - If origin and destination elements are the same, and this is + // that element, do not do anything + if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { + continue; + } + + contains = jQuery.contains( elem.ownerDocument, elem ); + + // Append to fragment + tmp = getAll( safe.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( contains ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( (elem = tmp[ j++ ]) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + tmp = null; + + return safe; + }, + + cleanData: function( elems, /* internal */ acceptData ) { + var elem, type, id, data, + i = 0, + internalKey = jQuery.expando, + cache = jQuery.cache, + deleteExpando = support.deleteExpando, + special = jQuery.event.special; + + for ( ; (elem = elems[i]) != null; i++ ) { + if ( acceptData || jQuery.acceptData( elem ) ) { + + id = elem[ internalKey ]; + data = id && cache[ id ]; + + if ( data ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Remove cache only if it was not already removed by jQuery.event.remove + if ( cache[ id ] ) { + + delete cache[ id ]; + + // IE does not allow us to delete expando properties from nodes, + // nor does it have a removeAttribute function on Document nodes; + // we must handle all of these cases + if ( deleteExpando ) { + delete elem[ internalKey ]; + + } else if ( typeof elem.removeAttribute !== strundefined ) { + elem.removeAttribute( internalKey ); + + } else { + elem[ internalKey ] = null; + } + + deletedIds.push( id ); + } + } + } + } + } +}); + +jQuery.fn.extend({ + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); + }, null, value, arguments.length ); + }, + + append: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + }); + }, + + prepend: function() { + return this.domManip( arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + }); + }, + + before: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + }); + }, + + after: function() { + return this.domManip( arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + }); + }, + + remove: function( selector, keepData /* Internal Use Only */ ) { + var elem, + elems = selector ? jQuery.filter( selector, this ) : this, + i = 0; + + for ( ; (elem = elems[i]) != null; i++ ) { + + if ( !keepData && elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem ) ); + } + + if ( elem.parentNode ) { + if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { + setGlobalEval( getAll( elem, "script" ) ); + } + elem.parentNode.removeChild( elem ); + } + } + + return this; + }, + + empty: function() { + var elem, + i = 0; + + for ( ; (elem = this[i]) != null; i++ ) { + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + } + + // Remove any remaining nodes + while ( elem.firstChild ) { + elem.removeChild( elem.firstChild ); + } + + // If this is a select, ensure that it displays empty (#12336) + // Support: IE<9 + if ( elem.options && jQuery.nodeName( elem, "select" ) ) { + elem.options.length = 0; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map(function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + }); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined ) { + return elem.nodeType === 1 ? + elem.innerHTML.replace( rinlinejQuery, "" ) : + undefined; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + ( support.htmlSerialize || !rnoshimcache.test( value ) ) && + ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && + !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) { + + value = value.replace( rxhtmlTag, "<$1>" ); + + try { + for (; i < l; i++ ) { + // Remove element nodes and prevent memory leaks + elem = this[i] || {}; + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch(e) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var arg = arguments[ 0 ]; + + // Make the changes, replacing each context element with the new content + this.domManip( arguments, function( elem ) { + arg = this.parentNode; + + jQuery.cleanData( getAll( this ) ); + + if ( arg ) { + arg.replaceChild( elem, this ); + } + }); + + // Force removal if there was no new content (e.g., from empty arguments) + return arg && (arg.length || arg.nodeType) ? this : this.remove(); + }, + + detach: function( selector ) { + return this.remove( selector, true ); + }, + + domManip: function( args, callback ) { + + // Flatten any nested arrays + args = concat.apply( [], args ); + + var first, node, hasScripts, + scripts, doc, fragment, + i = 0, + l = this.length, + set = this, + iNoClone = l - 1, + value = args[0], + isFunction = jQuery.isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( isFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return this.each(function( index ) { + var self = set.eq( index ); + if ( isFunction ) { + args[0] = value.call( this, index, self.html() ); + } + self.domManip( args, callback ); + }); + } + + if ( l ) { + fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + if ( first ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( this[i], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { + + if ( node.src ) { + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl ) { + jQuery._evalUrl( node.src ); + } + } else { + jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); + } + } + } + } + + // Fix #11809: Avoid leaking memory + fragment = first = null; + } + } + + return this; + } +}); + +jQuery.each({ + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + i = 0, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone(true); + jQuery( insert[i] )[ original ]( elems ); + + // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +}); + + +var iframe, + elemdisplay = {}; + +/** + * Retrieve the actual display of a element + * @param {String} name nodeName of the element + * @param {Object} doc Document object + */ +// Called only from within defaultDisplay +function actualDisplay( name, doc ) { + var style, + elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), + + // getDefaultComputedStyle might be reliably used only on attached element + display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ? + + // Use of this method is a temporary fix (more like optmization) until something better comes along, + // since it was removed from specification and supported only in FF + style.display : jQuery.css( elem[ 0 ], "display" ); + + // We don't have any data stored on the element, + // so use "detach" method as fast way to get rid of the element + elem.detach(); + + return display; +} + +/** + * Try to determine the default display value of an element + * @param {String} nodeName + */ +function defaultDisplay( nodeName ) { + var doc = document, + display = elemdisplay[ nodeName ]; + + if ( !display ) { + display = actualDisplay( nodeName, doc ); + + // If the simple way fails, read from inside an iframe + if ( display === "none" || !display ) { + + // Use the already-created iframe if possible + iframe = (iframe || jQuery( "