Beispiel #1
0
def checked_voice(name):
    """
    语音合成,传入签到者姓名
    """
    client = AipSpeech(
        getConfig('baidu-aip', 'app_id'),
        getConfig('baidu-aip', 'api_key'),
        getConfig('baidu-aip', 'secret_key'),
    )

    result = client.synthesis(f'{name}同学,签到成功', 'zh', 1, {
        'vol': 15,
    })

    if not isinstance(result, dict):
        tempFile = tempfile.NamedTemporaryFile('wb', delete=False)
        tempFile.write(result)
        tempFile.close()

        pygame.mixer.init()
        clock = pygame.time.Clock()
        # 加载音乐
        track = pygame.mixer.music.load(tempFile.name)
        # 播放音乐
        pygame.mixer.music.play()

        while pygame.mixer.music.get_busy():
            clock.tick(30)
        else:
            pygame.mixer.quit()
            try:
                os.remove(tempFile.name)
            except PermissionError:
                pass
Beispiel #2
0
def getNextEvent():
    with open(getConfig().getLastEventsFilePath(), 'rb') as myFile:
        csvReader = csv.reader(myFile, delimiter='|', quotechar='"')
        last = 0
        for row in csvReader:
            last = int(row[0])
        return last
Beispiel #3
0
def updateFakeObsDistributions():
    """
    Update distributions.xml. Add new projects, remove no longer
    existing projects.
    """
    conf = getConfig()
    # File where are described the default target distributions.
    # Probably /srv/www/obs/api/files/distributions.xml
    distributionsFile = conf.getPath(
        "obs_distributions_file", "/srv/www/obs/api/files/distributions.xml")

    doc1 = xml.dom.minidom.parse(distributionsFile)

    localProjectSet = ProjectManager.getProjectTargetTuples()
    fileProjectSet = listFakeObsDistribs(doc1)

    toBeRemoved = fileProjectSet.difference(localProjectSet)
    toBeAdded = localProjectSet.difference(fileProjectSet)

    for project, target in toBeRemoved:
        removeDistrib(doc1, project, target)

    for project, target in toBeAdded:
        addDistrib(doc1, project, target)

    saveDocument(doc1, distributionsFile)
    copyFakeObsLogo()
Beispiel #4
0
def expandgangasystemvars(c, v):
    """Expands vars with the syntax '@{VAR}' from the System config item."""
    system = getConfig('System')
    for key in system.options.iterkeys():
        option = '@{%s}' % key
        if option in v:
            v = v.replace(option,system[key])
    return v
            
Beispiel #5
0
def main():
    # TODO: use an option parser and add quiet/verbose modes
    if len(sys.argv) > 1:
        loadConfig(sys.argv[1])
    else:
        loadConfig()
    conf = getConfig()

    httpd = XFSPWebServer(("0.0.0.0", conf.getPort("webui_port", 8000)),
                          FakeObsWebUiRequestHandler)
    httpd.serve_forever()
Beispiel #6
0
 def getProjectConfigOrMeta(self, project, what="config"):
     readableWhat = {
         "config": "project configuration",
         "meta": "project meta informations"
     }
     url = "%s/source/%s/_%s" % (getConfig().getFakeObsApiUrl(), project,
                                 what)
     fileContent = urllib2.urlopen(url).read()
     fileContent = fileContent.replace("<", "&lt").replace(">", "&gt")
     title = "%s %s" % (project, readableWhat[what])
     content = TEXT_FILE_TEMPLATE % {"title": title, "content": fileContent}
     return content, HTML_CONTENTTYPE, 200
Beispiel #7
0
def copyFakeObsLogo():
    conf = getConfig()
    themeDir = conf.getPath("theme_dir", "/srv/obslight-fakeobs/theme")
    logoDir = "/srv/www/obs/webui/public/images/distributions/"
    src = os.path.join(themeDir, "fakeobs.png")
    dst = os.path.join(logoDir, "fakeobs.png")
    if not os.path.exists(dst):
        try:
            shutil.copy(src, dst)
        except IOError as myError:
            # It's not a real problem if logo is not copied
            pass
Beispiel #8
0
def main():
    # TODO: use an option parser and add quiet/verbose modes
    if len(sys.argv) > 1:
        loadConfig(sys.argv[1])
    else:
        loadConfig()
    conf = getConfig()
    Backend.updateLiveRepositories()

    httpd = XFSPWebServer(("0.0.0.0", conf.getPort("api_port", 8001)),
                          SimpleHTTPRequestHandler)
    httpd.serve_forever()
Beispiel #9
0
        def getProjectDependency(projectName, targetName):
            result = []
            result.append((projectName, targetName))
            localProjectNamePath = getConfig().getProjectDir(projectName)
            metaPath = localProjectNamePath + "/_meta"
            projects = BuildInfoManager.getProjectDependency(
                metaPath, targetName)

            for (project, target) in projects:
                res = getProjectDependency(project, target)
                result.extend(res)

            return result
Beispiel #10
0
 def getPrettyPackageList(self, project):
     """call /source/<project>, parse the result, format to HTML code"""
     url = "%s/source/%s" % (getConfig().getFakeObsApiUrl(), project)
     xmlRes = urllib2.urlopen(url).read()
     packageList = getEntryNameList(xmlRes)
     formattedList = PACKAGE_LIST_HEADER % {"project": project}
     for package in packageList:
         packageFilesUrl = "/package/files?package=%s&project=%s" % (
             package, project)
         formattedList += PACKAGE_ENTRY_TEMPLATE % {
             "packageFilesUrl": packageFilesUrl,
             "package": package
         }
     formattedList += PACKAGE_LIST_FOOTER
     return formattedList, HTML_CONTENTTYPE, 200
Beispiel #11
0
 def getPrettyFilesList(self, project, package):
     """call /source/<project>/<package>, parse the result, format to HTML code"""
     url = "%s/source/%s/%s" % (getConfig().getFakeObsApiUrl(), project,
                                package)
     xmlRes = urllib2.urlopen(url).read()
     files = getEntriesAsDicts(xmlRes)
     content = PACKAGE_FILES_HEADER % {
         "project": project,
         "package": package
     }
     fakeObsApiUrl = getConfig().getFakeObsApiUrl()
     localIp = getLocalHostIpAddress()
     if localIp != "127.0.0.1" and "/localhost:" in fakeObsApiUrl:
         fakeObsApiUrl = fakeObsApiUrl.replace("/localhost:",
                                               "/%s:" % localIp)
     for fileDict in files:
         fileUrl = "%s/source/%s/%s/%s" % (fakeObsApiUrl, project, package,
                                           fileDict["name"])
         fileDict["fileUrl"] = fileUrl
         readableTime = time.ctime(float(fileDict["mtime"]))
         fileDict["readableTime"] = readableTime
         content += PACKAGE_FILE_TEMPLATE % fileDict
     content += PACKAGE_FILES_FOOTER
     return content, HTML_CONTENTTYPE, 200
Beispiel #12
0
 def getPrettyProjectList(self):
     """call /source, parse the result, format to HTML code"""
     url = "%s/source" % (getConfig().getFakeObsApiUrl())
     xmlRes = urllib2.urlopen(url).read()
     projectList = getEntryNameList(xmlRes)
     formattedList = PROJECT_LIST_HEADER
     for project in projectList:
         projectDict = {
             "project": project,
             "packageListUrl": "/project/packages?project=%s" % project,
             "prjconfUrl": "/project/prjconf?project=%s" % project,
             "metaUrl": "/project/meta?project=%s" % project
         }
         formattedList += PROJECT_ENTRY_TEMPLATE % projectDict
     formattedList += PROJECT_LIST_FOOTER
     return formattedList, HTML_CONTENTTYPE, 200
Beispiel #13
0
def convertProject(project, release, newName=None):
    if newName is None:
        newName = project
    ProjectManager.failIfProjectExists(newName)

    conf = getConfig()
    port = 7999
    delay = 8
    api = "http://localhost:%s/public" % port
    fRoot = conf.getFakeObsRootDir()
    cmd = [os.path.join(fRoot, "tools", "legacy_fakeobs.py"), str(port)]
    msg = "Running '%s' and waiting %d seconds" % (" ".join(cmd), delay)
    print Utils.colorize(msg, "green")
    oldFakeObs = subprocess.Popen(cmd, cwd="/srv/fakeobs")
    time.sleep(delay)

    projectDir = conf.getProjectDir(newName)
    fullDir = conf.getProjectFullDir(newName)
    packagesDir = conf.getProjectPackagesDir(newName)
    repoDir = conf.getProjectRepositoryDir(newName)

    try:
        msg = "Getting _config and _meta"
        print Utils.colorize(msg, "green")
        ProjectManager.downloadConfAndMeta(api, project, projectDir)
        ProjectManager.fixProjectMeta(newName)
        msg = "Copying packages"
        print Utils.colorize(msg, "green")
        ProjectManager.downloadPackages(api, project, packagesDir)
        ProjectManager.fixProjectPackagesMeta(newName)
        msg = "Copying :full"
        print Utils.colorize(msg, "green")
        copyFull(project, fullDir)
        msg = "Copying repositories"
        print Utils.colorize(msg, "green")
        for target in ProjectManager.getTargetList(newName):
            copyRepository(project, release, target, repoDir)
        ProjectManager.updateLiveRepository(newName)
        return newName
    except:
        print Utils.colorize("Failed", "red")
        raise
    finally:
        oldFakeObs.terminate()
Beispiel #14
0
def createFakeObsLink(oscConfigPath=None):
    """
    Create the link to the fakeobs API on the OBS running on localhost.
    `oscConfigPath` may be the path to the osc configuration of
    an administrator of the OBS server.
    """
    conf = getConfig()
    tempFileUsed = False
    try:
        if oscConfigPath is None:
            webUiConfigPath = conf.getPath(
                "obs_webui_configuration_file",
                "/srv/www/obs/webui/config/environments/production.rb")
            protocol, host, port = readObsApiConfig(webUiConfigPath)
            tempFileUsed = True
            oscConfigPath = makeOscConfigFile(protocol, host, port)

        res = Utils.callSubprocess(["osc", "-c", oscConfigPath, "ls"],
                                   stdout=subprocess.PIPE)
        if res != 0:
            msg = "Could not contact OBS API"
            raise IOError(msg)

        res = Utils.callSubprocess(["osc", "-c", oscConfigPath,
                                    "meta", "prj", FAKEOBS_LINK_NAME],
                                   stdout=subprocess.PIPE)
        if res == 0:
            return "'%s' remote link already exists!" % FAKEOBS_LINK_NAME

        apiPort = conf.getPort("api_port", 8001)
        meta = FAKEOBS_META.replace("__PORT__", str(apiPort))
        meta = meta.replace("__FAKEOBS_LINK_NAME__", FAKEOBS_LINK_NAME)
        myProc = subprocess.Popen(["osc", "-c", oscConfigPath,
                                   "meta", "prj", "-F", "-", FAKEOBS_LINK_NAME],
                                  stdin=subprocess.PIPE)
        myProc.communicate(meta)
        res = myProc.wait()
        if res != 0:
            msg = "Failed to create '%s' project link!" % FAKEOBS_LINK_NAME
            raise IOError(msg)

    finally:
        if tempFileUsed:
            os.remove(oscConfigPath)
Beispiel #15
0
def find_face_owner(face_code):
    """
    从数据库查找人脸
    """
    results = list(mongo.find(getConfig('mongodb', 'user_collection'), {}))
    know_face_codes = [result['face'] for result in results]
    face_compare_result = face_recognition.face_distance(
        know_face_codes, face_code)
    # 设置阈值, 大于0.5的不考虑
    face_compare_result = list(
        map(lambda i: i if i < 0.5 else 10, face_compare_result))

    # 这里可能会出现非常相似的人脸(双胞胎) 不考虑
    user_index = list(face_compare_result).index(min(face_compare_result))
    if min(face_compare_result) == 10:
        # 不是本人
        return None
    else:
        return results[user_index].get('uid', None)
Beispiel #16
0
def getEventsFiltered(start, filters):
    impl = xml.dom.minidom.getDOMImplementation()
    indexdoc = impl.createDocument(None, "events", None)

    def appendTextElement(parent, tag, text):
        node = indexdoc.createElement(tag)
        node.appendChild(indexdoc.createTextNode(text))
        parent.appendChild(node)

    with open(getConfig().getLastEventsFilePath(), 'rb') as myFile:
        indexdoc.childNodes[0].setAttribute("next", str(getNextEvent()))

        csvReader = csv.reader(myFile, delimiter='|', quotechar='"')
        for row in csvReader:
            num = int(row[0])
            if num <= start:
                continue
            is_ok = False
            for filt in filters:
                if filt[2] is None:
                    if filt[0] == row[2] and filt[1] == row[3]:
                        is_ok = True
                elif filt[0] == row[2] and filt[1] == row[3] and filt[
                        2] == row[4]:
                    is_ok = True
            if is_ok:
                eventelm = indexdoc.createElement("event")
                eventelm.setAttribute("type", row[2])
                if row[2] == "package":
                    appendTextElement(eventelm, "project", row[3])
                    appendTextElement(eventelm, "package", row[4])
                if row[2] == "repository":
                    appendTextElement(eventelm, "project", row[3])
                    appendTextElement(eventelm, "repository", row[4])
                    appendTextElement(eventelm, "arch", row[5])
                if row[2] == "project":
                    appendTextElement(eventelm, "project", row[3])
                indexdoc.childNodes[0].appendChild(eventelm)

    return indexdoc.childNodes[0].toxml(encoding="us-ascii")
Beispiel #17
0
def send_message_to_email(receiver, email_header, **kwargs):
    """
    发送邮件给收件人
    :param receiver: 收件人
    :param email_header: 邮件头
    :param kwargs: 内容
    """
    subject = '[FaceR Client]: ' + kwargs.get('content')[:20]
    email_content = """<!DOCTYPE html>
                        <html lang="en">
                        <head>
                            <meta charset="UTF-8">
                        </head>
                        <body>
                            <h2>{email_header}</h2>
                            <p>{email_content}</p>
                        
                            <span>Sender Name: <b>{sender_name}</b></span> <br>
                            <span>Date: <b>{current_date}</b></span> <br>
                        </body>
                        </html>""".format(
        email_header=email_header,
        email_content=kwargs.get('content'),
        sender_name=kwargs.get('sender_name'),
        current_date=kwargs.get('current_date'))
    message = MIMEText(email_content, 'html', 'utf-8')
    message['From'] = getConfig('qmail', 'default_sender')
    message['To'] = receiver
    message['Subject'] = subject

    try:
        smtpObj = smtplib.SMTP(getConfig('qmail', 'server'),
                               getConfig('qmail', 'port'))
        smtpObj.starttls()
        smtpObj.login(getConfig('qmail', 'username'),
                      getConfig('qmail', 'password'))
        smtpObj.sendmail(getConfig('qmail', 'default_sender'), receiver,
                         message.as_string())
        return True
    except smtplib.SMTPException as e:
        print(e)
        return False
Beispiel #18
0
# -*- coding: utf-8 -*-

from Tool.mongo import MongoTools
from redis import Redis
from Config import getConfig
import pymysql

mongo = MongoTools(getConfig('mongodb', 'db'))
xtredis = Redis(getConfig('redis', 'server'),
                port=getConfig('redis', 'port'),
                password=getConfig('redis', 'password'),
                decode_responses=True)
db = pymysql.connect(host=getConfig('mysql', 'host'),
                     port=int(getConfig('mysql', 'port')),
                     user=getConfig('mysql', 'user'),
                     password=getConfig('mysql', 'pwd'),
                     database=getConfig('mysql', 'db'),
                     cursorclass=pymysql.cursors.DictCursor)
Beispiel #19
0
    def send_head(self, action):
        def string2stream(thestr):
            content = StringIO()
            content.write(thestr)
            content.seek(0, os.SEEK_END)
            contentsize = content.tell()
            content.seek(0, os.SEEK_SET)
            return contentsize, content

        def file2stream(path):
            f = open(path, 'rb')
            fs = os.fstat(f.fileno())
            # return contentsize, contentmtime, content
            return fs[6], fs.st_mtime, f

        def getCleanPathParts(path):
            pathparts = path.split("/")
            for x in range(0, len(pathparts)):
                pathparts[x] = urllib.unquote(pathparts[x])

            if len(pathparts[0]) == 0:
                pathparts = pathparts[1:]
            if len(pathparts[-1]) == 0:
                pathparts = pathparts[:-1]

            return pathparts

        def getProjectDependency(projectName, targetName):
            result = []
            result.append((projectName, targetName))
            localProjectNamePath = getConfig().getProjectDir(projectName)
            metaPath = localProjectNamePath + "/_meta"
            projects = BuildInfoManager.getProjectDependency(
                metaPath, targetName)

            for (project, target) in projects:
                res = getProjectDependency(project, target)
                result.extend(res)

            return result

        content = None
        contentsize = 0
        contentmtime = 0
        contenttype = None
        response = None
        conf = getConfig()

        pathparsed = urlparse.urlparse(self.path)
        path = pathparsed[2]
        if path.startswith("/public"):
            path = path[len("/public"):]

        if self.headers.getheader('Content-Length') is not None:
            data = self.rfile.read(
                int(self.headers.getheader('Content-Length')))
            query = urlparse.parse_qs(data)
        elif pathparsed[4] is not None:
            query = urlparse.parse_qs(pathparsed[4])
        else:
            query = {}

        #GET /about
        if path.startswith("/about"):
            contentsize, content = string2stream("Fake OBS\n")
            contenttype = "text/html"
            contentmtime = time.time()
        # GET /lastevents
        # TODO: Write lastevents Query.
        # GET /lastevents?filter=XXX&start=YYY
        if path.startswith("/lastevents"):
            if query.has_key("start"):
                if int(query["start"][0]) == Backend.getNextEvent():
                    # Normally OBS would block here, but we just 503 and claim we're busy,
                    # hoping it comes back
                    self.send_response(503)
                    self.end_headers()
                    return None

                filters = []
                # GET /lastevents?filter=XXX
                if query.has_key("filter"):
                    for x in query["filter"]:
                        spl = x.split('/')
                        if len(spl) == 2:
                            filters.append((urllib.unquote(spl[0]),
                                            urllib.unquote(spl[1]), None))
                        else:
                            filters.append((urllib.unquote(spl[0]),
                                            urllib.unquote(spl[1]),
                                            urllib.unquote(spl[2])))
                start = int(query["start"][0])
                contentsize, content = string2stream(
                    Backend.getEventsFiltered(start, filters))
                contenttype = "text/html"
                contentmtime = time.time()
            else:
                # GET /lastevents
                output = '<events next="' + str(
                    Backend.getNextEvent()) + '" sync="lost" />\n'

                contentsize, content = string2stream(output)
                contenttype = "text/html"
                contentmtime = time.time()

        #Search
        #
        #    GET /search/project
        #    GET /search/project/id
        #    GET /search/package
        #    GET /search/package/id
        #    GET /search/published/binary/id
        #    GET /search/published/pattern/id
        #    GET /search/request
        #    GET /search/issue
        elif path.startswith("/search"):
            pathparts = getCleanPathParts(path)
            #GET /search/project
            #GET /search/package
            #GET /search/request
            #GET /search/issue
            if len(pathparts) == 2:
                #GET /search/project
                if pathparts[1] == "project":
                    # Only used by OBS Light
                    contentsize, content = string2stream(
                        Backend.buildSearchIndex())
                    contenttype = "text/xml"
                    contentmtime = time.time()
                #GET /search/package
                elif pathparts[1] in {"package", "request", "issue"}:
                    content = None  # 404
            #GET /search/project/id
            #GET /search/package/id
            elif len(pathparts) == 3:
                id = pathparts[2]
                #GET /search/project/id
                if pathparts[1] == "project":
                    content = None  # 404 it
                #GET /search/package/id
                elif pathparts[1] == "package":
                    content = None  # 404
            #GET /search/published/binary/id
            #GET /search/published/pattern/id
            elif len(pathparts) == 4:
                id = pathparts[3]
                #GET /search/published/binary/id
                if pathparts[2] == "binary":
                    content = None  # 404 it
                #GET /search/published/pattern/id
                elif pathparts[2] == "pattern":
                    content = None  # 404

        #Sources
        #    Projects
        #        GET /source/
        #        GET /source/<project>/_meta
        #        GET /source/<project>/_attribute/<attribute>
        #        GET /source/<project>/_config
        #        GET /source/<project>/_pattern
        #        GET /source/<project>/_pattern/<patternfile>
        #        GET /source/<project>/_pubkey
        #    Packages
        #        GET /source/<project>
        #        GET /source/<project>/<package>
        #        GET /source/<project>/<package>/_meta
        #        GET /source/<project>/<package>/_attribute/<attribute>
        #        GET /source/<project>/<package>/_history
        #    Source files
        #        GET /source/<project>/<package>/<filename>
        #        GET /source/<project>/<package>/<binary>/_attribute/<attribute>
        elif path.startswith("/source"):

            pathparts = getCleanPathParts(path)
            realproject = None

            # GET /source/
            if len(pathparts) == 1:
                contentsize, content = string2stream(
                    Backend.buildProjectIndex())
                contenttype = "text/xml"
                contentmtime = time.time()

            elif len(pathparts) >= 2:
                # find <project>
                realproject = pathparts[1]
                realprojectPath = conf.getProjectDir(realproject)

                if realprojectPath is None:
                    realprojectPath = "--UNKNOWNPROJECT"

                # GET /source/<project>
                if len(pathparts) == 2:
                    if Backend.projectExists(realproject):
                        contentsize, content = string2stream(
                            Backend.buildPackageIndex(realproject))
                        contenttype = "text/xml"
                        contentmtime = time.time()
                # package or metadata for project
                #GET /source/<project>/_meta
                #GET /source/<project>/_config
                #GET /source/<project>/_pattern
                #GET /source/<project>/_pubkey
                #GET /source/<project>/<package>
                elif len(pathparts) == 3:
                    # GET /source/<project>/_meta
                    if pathparts[2] == "_meta":
                        contentsize, content = string2stream(
                            Backend.getProjectMeta(realproject))
                        contenttype = "text/xml"
                        contentmtime = time.time()
                    # GET /source/<project>/_config
                    elif pathparts[2] == "_config":
                        contentsize, contentmtime, content = file2stream(
                            realprojectPath + "/_config")
                        contenttype = "text/plain"
                    # GET /source/<project>/_pubkey
                    # GET /source/<project>/_pattern
                    #elif pathparts[2] in {"_pubkey", "_pattern"}:
                    elif pathparts[2] in {"_pubkey"}:
                        content = None  # 404 it
                    # GET /source/<project>/<package>
                    else:
                        packageName = pathparts[2]
                        expand = 0
                        rev = None
                        # GET /source/<project>/<package>?expand=[0 1]
                        if query.has_key("expand"):
                            expand = int(query["expand"][0])
                        # GET /source/<project>/<package>?rev=XX
                        if query.has_key("rev"):
                            rev = query["rev"][0]

                        contentsize, content = string2stream(
                            Backend.buildFileIndex(realproject, packageName))
                        contenttype = "text/xml"
                        contentmtime = time.time()
                # GET /source/<project>/_attribute/<attribute>
                # GET /source/<project>/_pattern/<patternfile>
                # GET /source/<project>/<package>/_meta
                # GET /source/<project>/<package>/_history
                # GET /source/<project>/<package>/<filename>
                elif len(pathparts) == 4:
                    # GET /source/<project>/_attribute/<attribute>
                    # GET /source/<project>/_pattern/<patternfile>
                    if pathparts[2] in {"_attribute", "_pattern"}:
                        attribute = pathparts[3]
                        content = None  # 404 it

                    # GET /source/<project>/<package>/_meta
                    # GET /source/<project>/<package>/_history
                    # GET /source/<project>/<package>/<filename>
                    else:
                        packageName = pathparts[2]

                        # GET /source/<project>/<package>/_history
                        if pathparts[3] == "_history":
                            content = None  # 404 it
                        # GET /source/<project>/<package>/<filename>
                        else:
                            filename = pathparts[3]
                            rev = None
                            expand = 0
                            #GET /source/<project>/<package>/<filename>?expand=[0 1]
                            if query.has_key("expand"):
                                expand = int(query["expand"][0])
                            #GET /source/<project>/<package>/<filename>?rev=XX
                            if query.has_key("rev"):
                                rev = query["rev"][0]

                            filePath = Backend.getPackageFilePath(
                                realproject, packageName, filename)
                            if os.path.isfile(filePath):
                                contentsize, contentmtime, content = file2stream(
                                    filePath)
                            else:
                                content = None

                            if filename == "_meta":
                                contenttype = "text/xml"
                                # XXX: do we need to update contentmtime ?
                                contentmtime = time.time()

                # GET /source/<project>/<package>/_attribute/<attribute>
                elif len(pathparts) == 5:
                    content = None  # 404 it
                # GET /source/<project>/<package>/<binary>/_attribute/<attribute>
                elif len(pathparts) == 6:
                    content = None  # 404 it

        #Build Results
        #    GET /build/
        #    GET /build/_workerstatus
        #    GET /build/<project>
        #    GET /build/<project>/<repository>
        #    GET /build/<project>/<repository/<arch>
        #    Binaries
        #        GET /build/<project>/<repository>/<arch>/<package>
        #        GET /build/<project>/<repository>/<arch>/<package>/<binaryname>
        #        GET /build/<project>/<repository>/<arch>/<package>/<binaryname>?view=fileinfo
        #        GET /build/<project>/<repository>/<arch>/<package>/<binaryname>?view=fileinfo_ext
        #        GET /build/<project>/<repository>/<arch>/_builddepinfo?package=<package>
        #        GET /build/<project>/<repository>/<arch>/_jobhistory?package=<package>&code=succeeded&limit=10
        #        GET /build/<project>/<repository>/<arch>/_repository
        #        GET /build/<project>/<repository>/<arch>/_repository/<binaryname>
        #    Status
        #        GET /build/<project>/_result
        #        GET /build/<project>/<repository>/<arch>/<package>/_history
        #        GET /build/<project>/<repository>/<arch>/<package>/_reason
        #        GET /build/<project>/<repository>/<arch>/<package>/_status
        #        GET /build/<project>/<repository>/<arch>/<package>/_log
        #    Local Build
        #        GET /build/<project>/<repository>/<arch>/<package>/_buildinfo
        #        POST /build/<project>/<repository>/<arch>/<package>/_buildinfo
        #    Repository Information
        #        GET /build/<project>/<repository>/<arch>/_repository/<binaryname>
        #        GET /build/<project>/<repository>/<arch>/_builddepinfo
        elif path.startswith("/build"):
            pathparts = getCleanPathParts(path)
            #/public/build/Mer:Trunk:Base/standard/i586/_repository?view=cache
            # GET /build/
            if len(pathparts) == 1:
                content = None  # 404 it
            # GET /build/_workerstatus
            # GET /build/<project>
            if len(pathparts) == 2:
                # GET /build/_workerstatus
                if pathparts[1] == "_workerstatus":
                    content = None  # 404 it
                # GET /build/<project>
                else:
                    projectName = pathparts[1]
                    contentsize, content = string2stream(
                        Backend.buildTargetIndex(projectName))
                    contenttype = "text/xml"
                    contentmtime = time.time()

            if len(pathparts) >= 3:
                projectName = pathparts[1]
                projectNamePath = conf.getProjectFullDir(projectName)
                localProjectNamePath = conf.getProjectDir(projectName)

                if projectNamePath is None:
                    projectNamePath = "--UNKNOWNPROJECT"

                # GET /build/<project>/_result
                # GET /build/<project>/<repository>
                if len(pathparts) == 3:
                    # GET /build/<project>/_result
                    if pathparts[2] == "_result":
                        content = None  # 404 it
                    # GET /build/<project>/<repository>
                    else:
                        repository = pathparts[2]
                        contentsize, content = string2stream(
                            Backend.buildArchIndex(projectName, repository))
                        contenttype = "text/xml"
                        contentmtime = time.time()

                if len(pathparts) >= 4:
                    repository = pathparts[2]
                    # GET /build/<project>/<repository>/<arch>
                    # GET /build/<project>/<repository>/_buildconfig
                    if len(pathparts) == 4:
                        if pathparts[3] == "_buildconfig":
                            buildconfig = Backend.getRecursiveProjectConfig(
                                projectName, repository)
                            contentsize, content = string2stream(buildconfig)
                            contenttype = "text/plain"
                            contentmtime = time.time()
                        else:
                            arch = pathparts[3]
                            content = None  # 404 it

                    # GET /build/<project>/<repository>/<arch>/_repository
                    # GET /build/<project>/<repository>/<arch>/_builddepinfo
                    # GET /build/<project>/<repository>/<arch>/_builddepinfo?package=<package>
                    # GET /build/<project>/<repository>/<arch>/_jobhistory?package=<package>&code=succeeded&limit=10
                    # GET /build/<project>/<repository>/<arch>/<package>
                    elif len(pathparts) == 5:
                        arch = pathparts[3]
                        # GET /build/<project>/<repository>/<arch>/_repository
                        if pathparts[4] == "_repository":
                            arch = pathparts[3]
                            emptyrepositorycache = "tools/emptyrepositorycache.cpio"
                            # GET /build/<project>/<repository>/<arch>/_repository?view=cache
                            if query.has_key(
                                    "view") and query["view"][0] == "cache":
                                filePath = os.path.join(
                                    projectNamePath, repository, arch,
                                    "_repository?view=cache")

                                if os.path.isfile(filePath):
                                    contentsize, contentmtime, content = file2stream(
                                        filePath)
                                    contenttype = "application/octet-stream"
                                else:
                                    contentsize, contentmtime, content = file2stream(
                                        emptyrepositorycache)
                                    contenttype = "application/octet-stream"
                            # GET /build/<project>/<repository>/<arch>/_repository?view=solvstate
                            elif query.has_key("view") and query["view"][
                                    0] == "solvstate":
                                filePath = os.path.join(
                                    projectNamePath, repository, arch,
                                    "_repository?view=solvstate")
                                if os.path.isfile(filePath):
                                    contentsize, contentmtime, content = file2stream(
                                        filePath)
                                    contenttype = "application/octet-stream"
                                else:
                                    contentsize, contentmtime, content = file2stream(
                                        emptyrepositorycache)
                                    contenttype = "application/octet-stream"
                            # GET /build/<project>/<repository>/<arch>/_repository?view=cpio&binary=XXX
                            elif query.has_key("binary") and query.has_key(
                                    "view") and query["view"][0] == "cpio":
                                binaries = ""
                                for x in query["binary"]:
                                    filePath = os.path.join(
                                        projectNamePath, repository, arch,
                                        os.path.basename(x) + ".rpm")
                                    if os.path.isfile(filePath):
                                        assert filePath + " was not found"
                                    binaries = binaries + os.path.basename(
                                        x) + ".rpm\n"

                                path = os.path.join(projectNamePath,
                                                    repository, arch)
                                with tempfile.NamedTemporaryFile(
                                        "w", suffix=".cpio") as cpioFile:
                                    res = createCpio(cpioFile, binaries, path)
                                    # cpioFile is deleted after this block but it is still open
                                    # and readable ('content' is a file-object)
                                    contentsize, contentmtime, content = file2stream(
                                        cpioFile.name)
                                contentmtime = time.time()
                                contenttype = "application/x-cpio"
                                ##
                            # GET /build/<project>/<repository>/<arch>/_repository?view=names&binary=XXX
                            elif (query.has_key("binary")
                                  and query.has_key("view")
                                  and query["view"][0] == "names"):
                                filePath = os.path.join(
                                    projectNamePath, repository, arch,
                                    "_repository?view=names")
                                if os.path.isfile(filePath):
                                    #Too slow sould be rewrite
                                    doc = xml.dom.minidom.parse(filePath)
                                    removables = []
                                    for x in doc.getElementsByTagName(
                                            "binary"):
                                        if not os.path.splitext(
                                                x.attributes["filename"].value
                                        )[0] in query["binary"]:
                                            removables.append(x)
                                    for x in removables:
                                        doc.childNodes[0].removeChild(x)
                                    contentsize, content = string2stream(
                                        doc.childNodes[0].toxml())
                                    contentmtime = time.time()
                                    contenttype = "text/html"
                                else:
                                    contentsize, content = string2stream(
                                        "<binarylist />")
                                    contenttype = "text/html"
                                    contentmtime = time.time()
                            # GET /build/<project>/<repository>/<arch>/_repository?view=binaryversions&binary=XXX
                            elif query.has_key("binary") and\
                                 query.has_key("view") and\
                                 query["view"][0] == "binaryversions":
                                filePathCache = os.path.join(
                                    projectNamePath, repository, arch,
                                    "_repository?view=cache")
                                filePathBin = os.path.join(
                                    projectNamePath, repository, arch,
                                    "_repository?view=binaryversions")
                                if os.path.isfile(filePathCache):
                                    doc = xml.dom.minidom.parse(filePathBin)
                                    removables = []
                                    for x in doc.getElementsByTagName(
                                            "binary"):
                                        if not os.path.splitext(
                                                x.attributes["name"].value
                                        )[0] in query["binary"]:
                                            removables.append(x)
                                    for x in removables:
                                        doc.childNodes[0].removeChild(x)
                                    contentsize, content = string2stream(
                                        doc.childNodes[0].toxml())
                                    contentmtime = time.time()
                                    contenttype = "text/html"
                                else:
                                    contentsize, content = string2stream(
                                        "<binaryversionlist />")
                                    contenttype = "text/html"
                                    contentmtime = time.time()
                            else:
                                filePath = os.path.join(
                                    projectNamePath, repository, arch,
                                    "_repository?view=names")
                                if os.path.isfile(filePath):
                                    contentsize, contentmtime, content = file2stream(
                                        filePath)
                                    contenttype = "application/octet-stream"
                                else:
                                    contentsize, contentmtime, content = file2stream(
                                        emptyrepositorycache)
                                    contenttype = "application/octet-stream"
                        # GET /build/<project>/<repository>/<arch>/_builddepinfo
                        # GET /build/<project>/<repository>/<arch>/_builddepinfo?package=<package>
                        elif pathparts[4] == "_builddepinfo":
                            content = None  # 404 it
                        # GET /build/<project>/<repository>/<arch>/_jobhistory?package=<package>&code=succeeded&limit=10
                        elif pathparts[4] == "_jobhistory":
                            content = None  # 404 it
                        # GET /build/<project>/<repository>/<arch>/<package>
                        else:
                            package = pathparts[4]
                            content = None  # 404 it
                    # GET /build/<project>/<repository>/<arch>/_repository/<binaryname>
                    # GET /build/<project>/<repository>/<arch>/<package>/_history
                    # GET /build/<project>/<repository>/<arch>/<package>/_reason
                    # GET /build/<project>/<repository>/<arch>/<package>/_status
                    # GET /build/<project>/<repository>/<arch>/<package>/_log
                    # GET /build/<project>/<repository>/<arch>/<package>/_buildinfo
                    # POST /build/<project>/<repository>/<arch>/<package>/_buildinfo
                    # GET /build/<project>/<repository>/<arch>/<package>/<binaryname>
                    # GET /build/<project>/<repository>/<arch>/<package>/<binaryname>?view=fileinfo
                    # GET /build/<project>/<repository>/<arch>/<package>/<binaryname>?view=fileinfo_ext
                    elif len(pathparts) == 6:
                        arch = pathparts[3]
                        # GET /build/<project>/<repository>/<arch>/_repository/<binaryname>
                        if pathparts[4] == "_repository" and pathparts[
                                5] != "_buildinfo":
                            binaryname = pathparts[5]
                            content = None  # 404 it
                        else:
                            packageName = pathparts[4]
                            # GET /build/<project>/<repository>/<arch>/<package>/_history
                            if pathparts[5] == "_history":
                                content = None  # 404 it
                            # GET /build/<project>/<repository>/<arch>/<package>/_reason
                            elif pathparts[5] == "_reason":
                                content = None  # 404 it
                            # GET /build/<project>/<repository>/<arch>/<package>/_status
                            elif pathparts[5] == "_status":
                                msg = '<status package="%s" code="Unknown"><details></details></status>'
                                contentsize, content = string2stream(
                                    msg % projectName)
                                contentmtime = time.time()
                                contenttype = "text/html"

                            # GET /build/<project>/<repository>/<arch>/<package>/_log
                            elif pathparts[5] == "_log":
                                content = None  # 404 it
                            # GET /build/<project>/<repository>/<arch>/<package>/_buildinfo
                            # GET /build/<project>/<repository>/<arch>/<package>/_buildinfo?add=package
                            # POST /build/<project>/<repository>/<arch>/<package>/_buildinfo
                            # POST /build/<project>/<repository>/<arch>/<package>/_buildinfo?add=package
                            elif pathparts[5] == "_buildinfo":
                                if action == POST:
                                    specFileContent = data
                                    #TODO:Find Spec file Name.
                                    specFileName = None
                                    rev = None
                                    srcmd5 = None
                                else:
                                    specFileName = Backend.getProjectSpecFile(
                                        projectName, packageName)
                                    specFilePath = Backend.getPackageFilePath(
                                        projectName, packageName, specFileName)
                                    specFileContent = ""
                                    with open(specFilePath, "r") as f:
                                        specFileContent = f.read()

                                    rev, srcmd5 = Backend.getPackageLastRevSrcmd5(
                                        projectName, packageName)

                                with tempfile.NamedTemporaryFile(
                                        "w", delete=False,
                                        suffix=".spec") as tmpSpecFile:
                                    tmpSpecFile.write(specFileContent)

                                repo = BuildInfoManager.getLocalRepositoryUrl()

                                repositoryList = []
                                with tempfile.NamedTemporaryFile(
                                        "w", delete=False,
                                        suffix=".config") as tmpConfFile:
                                    configStr = Backend.getRecursiveProjectConfig(
                                        projectName, repository)
                                    tmpConfFile.write(configStr)

                                for (prj,
                                     target) in Backend.getProjectDependencies(
                                         projectName, repository):
                                    extPrj = prj.replace(":", ":/")
                                    repositoryList.append(repo + "/" + extPrj +
                                                          "/" + target)

                                if query.has_key("add"):
                                    addPackages = query["add"]
                                else:
                                    addPackages = []
                                xmlRes = BuildInfoManager.getbuildInfo(
                                    rev, srcmd5, specFileName, repositoryList,
                                    tmpConfFile.name,
                                    localProjectNamePath + "/_rpmcache", arch,
                                    projectName, packageName, repository,
                                    tmpSpecFile.name, addPackages)
                                os.unlink(tmpSpecFile.name)
                                os.unlink(tmpConfFile.name)

                                contentsize, content = string2stream(xmlRes)
                                contentmtime = time.time()
                                contenttype = "text/html"

                            # GET /build/<project>/<repository>/<arch>/<package>/<binaryname>
                            # GET /build/<project>/<repository>/<arch>/<package>/<binaryname>?view=fileinfo
                            # GET /build/<project>/<repository>/<arch>/<package>/<binaryname>?view=fileinfo_ext
                            else:
                                binaryname = pathparts[5]
                                content = None  # 404 it

        if content is None:
            print "404: path"
            self.send_error(404, "File not found")
            return None

        if response is None:
            self.send_response(200)
        else:
            self.send_response(response)
        self.send_header("Content-type", contenttype)
        self.send_header("Content-Length", contentsize)
        self.send_header("Last-Modified", self.date_time_string(contentmtime))
        self.end_headers()
        return content
Beispiel #20
0
def buildFileIndex(project, package):
    packagesDir = getConfig().getProjectPackagesDir(project)
    packagePath = os.path.join(packagesDir, package)
    indexPath = os.path.join(packagePath, getConfig().PackageDescriptionFile)
    with open(indexPath, "r") as myFile:
        return myFile.read()
Beispiel #21
0
def getPackageFilePath(project, package, fileName):
    packagesDir = getConfig().getProjectPackagesDir(project)
    filePath = os.path.join(packagesDir, package, fileName)
    return filePath
Beispiel #22
0
 def handleFaviconRequest(self, *args):
     path = getConfig().getPath("theme_dir", "/srv/fakeobs/theme")
     return self.sendFile(os.path.join(path, "favicon.ico"))
Beispiel #23
0
 def handleThemeRequest(self, pathParts, queryDict):
     path = getConfig().getPath("theme_dir", "/srv/fakeobs/theme")
     return self.sendFile(os.path.join(path, *pathParts))