class MagentoXMLRPCConnection:
    """
    Holds an XML-RPC connection to a remote Magento XML-RPC server.
  """
    def __init__(self, url, user_name=None, password=None):
        self.url = url
        self._user_name = user_name
        self._password = password

    def connect(self):
        """Get a handle to a remote connection."""
        url = self.url
        self.server = Server(url)
        if self._user_name is not None and self._password is not None:
            self.session = self.server.login(self._user_name, self._password)
        return self

    def __getattr__(self, name):
        """ Allow to call mehod on connection """
        if not name.startswith("_"):
            return MethodWrapper(name, self)
Example #2
0
class MagentoXMLRPCConnection:
  """
    Holds an XML-RPC connection to a remote Magento XML-RPC server.
  """

  def __init__(self, url, user_name = None, password = None):
    self.url = url
    self._user_name = user_name
    self._password = password

  def connect(self):
    """Get a handle to a remote connection."""
    url = self.url
    self.server = Server(url)
    if self._user_name is not None and self._password is not None:
      self.session = self.server.login(self._user_name, self._password)
    return self

  def __getattr__(self, name):
    """ Allow to call mehod on connection """
    if not name.startswith("_"):
      return MethodWrapper(name, self)
Example #3
0
class ConfluenceInstance(object):
    def __init__(self):
        self.settings = ConfluenceSettings()
        self.server = Server(self.settings.uri).confluence2
        self.db = DatabaseWrapper()
        self.page = None

    def get_token(self):
        LOGGER.info('Logging in to Confluence as %s' % self.settings.login)
        token = self.server.login(self.settings.login, self.settings.password)
        return token

    def get_page(self):
        if self.page is None:
            LOGGER.info('Fetching page contents from Confluence')
            data = self.server.getPage(
                self.get_token(),
                self.settings.namespace,
                self.settings.pagename
            )
            self.page = ConfluencePage(data)
        return self.page

    def save_page(self, page):
        page = self.__attach_statistics(page)
        self.server.storePage(self.get_token(), page.data)

    def __attach_statistics(self, page):
        stats = Stats(self.db.get_dc_issues()).get_result()
        content = page.data['content']
        message = structured_macro_info(
            'Warning',
            paragraph(update_message(self.settings.login, strftime("%Y-%m-%d %H:%M:%S %z", gmtime())))
        )
        to_go_count = stats['total']['count'] - stats['ready']['count'] - stats['passed']['count'] - stats['failed'][
            'count']
        stat_info = paragraph(
            structured_macro_status('Grey', '%s total' % len(DatabaseWrapper.get_all_issues())) +
            structured_macro_status('Grey', '%s desk check' % stats['total']['count']) +
            structured_macro_status('Blue', '%s ready' % stats['ready']['count']) +
            structured_macro_status('Green', '%s pass' % stats['passed']['count']) +
            structured_macro_status('Red', '%s fail' % stats['failed']['count']) +
            structured_macro_status_subtle('%s to go' % to_go_count)
        )

        content = message + stat_info + content
        page.data.update({'content': str(content)})
        return page

    def __outdated_issues_block(self):
        items_for_list = []
        for issue in self.db.get_outdated_issues():
            items_for_list.append({
                'link': JiraSettings().browse + issue.key,
                'title': issue.key,
                'comment': ' (%s)' % issue.est_date,
            })

        if len(items_for_list) > 0:
            outdated = paragraph(
                structured_macro_expand('%s outdated issues' % len(items_for_list),
                                        unordered_list_with_hrefs(items_for_list))
            )
        else:
            outdated = ''
        return outdated
Example #4
0
class ConfluenceServer():
    """This class is is used to create an object for interacting with a Confluence Wiki instance.
    
    Attributes:
        URL         Full URL for Confluence instance
        session     Shorthand for XML-RPC methods that start with confluence2
        token       Authentication token; mandatory for all operations.
        PDFsession  Shorthand for XML-RPC methods that start with pdfexport
    """
    def __init__(self,ConfluenceURL,login='',password=''):
        self.URL = ConfluenceURL
        logger.info("Establishing Connection to confluence at %s" % ConfluenceURL)
        self.session = Server(ConfluenceURL+'/rpc/xmlrpc').confluence2
        logger.info("Connection established. Logging in as %s" % login)
        self.token = self.session.login(login,password)
        logger.info("Successfully logged in as %s" % login)
        self.PDFsession = Server(ConfluenceURL+'/rpc/xmlrpc').pdfexport
        
    def GetLabelPages(self,label):
        """Get all pages associated with label"""
        return self.session.search(self.token,'labelText:%s and type:page' % label, 10000)
        
    def GetSpace(self,spacekey):
        """Get all page summaries (visible to current user) in spacekey"""
        return self.session.getSpace(self.token,spacekey)
        
    def AddPage(self,page):
        """Store a page. See https://developer.atlassian.com/display/CONFDEV/Remote+Confluence+Data+Objects#RemoteConfluenceDataObjects-pagePage for details."""
        return self.session.storePage(page)

    def DeletePage(self,pageId):
        """Delete a page"""
        return self.session.removePage(self.token,pageId)
        
    def ContentArray(self,articles):
        """Accepts the results of a search (such as GetLabelPages) and returns an array with the result of GetPage for each search result."""
        return [self.session.getPage(self.token,page['id']) for page in articles]

    def AddSpace(self,name,key,description):
        """Create a space"""
        space = {'key': key.rstrip(), 'name': name.rstrip(), 'description': description}
        return self.session.addSpace(self.token,space)

    def RemoveSpace(self,spacekey):
        """Delete a space"""
        return self.session.removeSpace(self.token,spacekey)
        
    def ExportSpace(self,space):
        """Perform a PDF Export of a space and return the download URL"""
        return self.PDFsession.exportSpace(self.token,space)
        
    def ListPageAttachments(self,pageId):
        """List all page attachments"""
        return self.session.getAttachments(self.token,pageId)
        
    def GetAttachment(self,pageId,fileName):
        """Get attachment Data"""
        return self.session.getAttachmentData(self.token,pageId,fileName,'0')
        
    def AddAttachment(self,pageId,attachmentDict,attachmentData):
        """Add Attachment -- attachmentDict info: https://developer.atlassian.com/display/CONFDEV/Remote+Confluence+Data+Objects#RemoteConfluenceDataObjects-attachmentAttachment """
        return self.session.addAttachment(self.token,pageId,attachmentDict,attachmentData)

    def CreateDuplicate(self,content,newSpace):
        """Duplicate a page (including attachments)"""
        copy = content.copy()
        [copy.pop(key) for key in ['id', 'parentId', 'title', 'space', 'version', 'modified']]
        formatAttributes = {'space': content['space'], 'id': content['id'], 'title': content['title']}
        copy['space'] = newSpace
        copy['title'] = "%s - %s - %s" % (content['space'].upper(), content['title'], content['id'])
        storedCopy = self.session.storePage(self.token,copy)
        for a in self.ListPageAttachments(content['id']):
            try:
                attachment = self.GetAttachment(content['id'],a['fileName'])
                self.AddAttachment(storedCopy['id'],{'fileName':a['fileName'],'contentType':a['contentType']},attachment)
            except:
                logger.error("Attachment %s from %s is missing from the content store" % (a['fileName'],content['title']))
                
    def GetSpacePages(self, spacekey):
        """Return summaries of all pages visible by the current user in a given space"""
        return self.session.getPages(self.token,spacekey)
            
    def GetRestrictions(self, pageId):
        """Return a list of permissions applied to the current page"""
        return self.session.getPagePermissions(self.token, str(pageId))
        
#    def SetRestrictons(self, pageId, permissionType, permissions=[]):
#        """ 
#        Replace restrictions on a page (blank=none)
#        WARNING! This will replace all permissions of the chosen type with the ones provided in the list!
#        Permission format is [{'userName':username1},{'userName':username2}] and so on.
#        """
#        return self.session.setPagePermissions(self.token, pageId, permissionType, permissions)
#        
#    def AddRestrictions(self, pageId, permissionType, entity):
#        perms = [p['lockedBy'] for p in self.GetRestrictions(pageId) if p['lockType'] == permissionType]
#        perms.append(entity)
#        
#        return [{'userName': e} for e in perms]
        #return self.session.setPagePermissions(self.token, pageId, permissionType, permissions = [{'userName': e} for e in perms]) 
        
    def GetSpaces(self):
        """Return summaries of all spaces visible to the current user"""
        return self.session.getSpaces(self.token)
        
    def GetSpacePermissionSets(self,spacekey):
        """Return permissions for a space"""
        return self.session.getSpacePermissionSets(self.token, spacekey)
    
    def GetSpacePermissionsForUser(self,spacekey,userName):
        """Return User's Permissions for a space"""
        return self.session.getPermissionsForUser(self.token, spacekey, userName)
        
    def GetSpacePermissionsForGroup(self,spacekey,group):
        """Return Group's Permissions for a space"""
        permissions = self.GetSpacePermissionSets(spacekey)
        groupPermissions = []
        for p in permissions:
            for q in p['spacePermissions']:
                if q.has_key('groupName'):
                    if q['groupName'] == group:
                        groupPermissions.append(q['type'])
        return groupPermissions
        
    def GrantPermissionsForSpace(self,entity,spacekey,permissions):
        """
        Grant a list of permissions to the user or group.
        Examples: https://developer.atlassian.com/confdev/confluence-rest-api/confluence-xml-rpc-and-soap-apis/remote-confluence-methods#RemoteConfluenceMethods-Permissions.1
        OR see the next method.
        """
        return self.session.addPermissionsToSpace(self.token,permissions,entity,spacekey)
        
    def RemovePermissionsForSpace(self,entity,spacekey,permissions=["VIEWPAGE","VIEWSPACE","EDITSPACE",
        "EXPORTPAGE","SETPAGEPERMISSIONS","REMOVEPAGE","EDITBLOG","REMOVEBLOG","COMMENT",   
        "REMOVECOMMENT","CREATEATTACHMENT","REMOVEATTACHMENT","REMOVEMAIL","EXPORTSPACE",
        "SETSPACEPERMISSIONS"]):
        """
        Remove a list of permissions for a user or group from a space (default is all)
        """
        results = {}
        for permission in permissions:
            results[permission] = self.session.removePermissionFromSpace(self.token,permission,entity,spacekey)
        return results
#!/usr/bin/python
import sys
from xmlrpclib import Server

sys.path.append('/usr/share/rhn')
try:
   from common import initCFG, CFG
except:
   print "Couldn't load needed libs, Are you sure you are running this on a satellite?"
   sys.exit(1)

initCFG()
user = '******'
passw = CFG.SESSION_SECRET_1

c = Server('http://localhost/rpc/api')
print("Satellite auth.checkAuthToken (should be 1): ")
print( c.auth.checkAuthToken(user, passw))

print("Trying cobbler login (should be a random token): ")
c = Server('http://localhost/cobbler_api')
print(c.login(user, passw))
    _file = """\
#!%s/node
var sys = require('sys'),
    http = require('http');

http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World');
}).listen(%s, "127.0.0.1");

sys.puts('Server listening on port %s');
    """ % (bin_dir, app['port'], app['port'])
    server.write_file(session_id, filename, _file)

    # change script to executable
    cmd = 'chmod 711 %s' % filename
    server.system(session_id, cmd)

    print "node app: %s created listening on port: %s " % (app['id'], app['port'])

def delete(app_name, server, session_id):
    server.delete_app(session_id, app_name)

if __name__ == '__main__':
    action, username, password, machine, app_name, autostart, extra_info = argv[1:]
    server = Server('https://api.webfaction.com/')
    session_id, account = server.login(username, password, machine)

    locals()[action](app_name, server, session_id)
-----END WEBFACTION INSTALL SCRIPT-----