def load(self, cdr_id): """ Check out the CDR Term document, parse it, and update it with the current concept information. Pass: cdr_id - unique identified of the existing CDR Term document Return: cdr.Doc object with updated terms and/or definitions """ try: self.cdr_id, self.doc_id, frag_id = cdr.exNormalize(cdr_id) if cdr.lastVersions(self.session, self.cdr_id)[1] != -1: self.published = True except: Concept.fail("invalid CDR ID %r" % cdr_id) self.concept.logger.info("updating %s", self.cdr_id) try: doc = cdr.getDoc(self.session, self.cdr_id, "Y", getObject=True) except Exception as e: Concept.fail("failure retrieving %s: %s" % (self.cdr_id, e)) try: self.root = self.parse(doc.xml) doc.xml = self.update() return doc except Exception: cdr.unlock(self.session, self.cdr_id) raise
def idpair(self): """CDR Media document ID pair - returning a list [EN, ES].""" # Find Spanish document when using the English version if not hasattr(self, "_idpair"): cdrId = self.fields.getvalue("DocId") _id = exNormalize(cdrId)[1] query = self.Query("query_term", "doc_id", "int_val") query.where(query.Condition("path", self.TRANSLATION_OF)) query.where(query.Condition("int_val", _id)) rows = query.execute(self.cursor).fetchall() # Find English document when using the Spanish version if not rows: queryES = self.Query("query_term", "doc_id", "int_val") queryES.where(query.Condition("path", self.TRANSLATION_OF)) queryES.where(query.Condition("doc_id", _id)) rowsES = queryES.execute(self.cursor).fetchall() if not rowsES: self.bail("No Spanish translation found for image document") self._idpair = [rowsES[0][1], rowsES[0][0]] or None return self._idpair self._idpair = [rows[0][1], rows[0][0]] or None return self._idpair
def get_int_cdr_id(self, value): """ Convert CDR ID to integer. Exit with an error message on failure. """ if value: try: return exNormalize(value)[1] except: self.bail("Invalid format for CDR ID") return None
def __parseBoardMembershipDetails(self, node): boardId = None frequency = None for child in node.childNodes: if child.nodeName == "BoardName": attr = child.getAttribute("cdr:ref") if attr: id = cdr.exNormalize(attr) boardId = id[1] if boardId != self.board.id: return elif child.nodeName == "TermRenewalFrequency": frequency = cdr.getTextContent(child) if boardId and frequency: self.renewalFrequency = frequency
def _find_locker(self, id): """ Find out who (if anyone) has a specified document checked out. """ self._cursor.execute( """\ SELECT u.name FROM usr u JOIN checkout c ON c.usr = u.id WHERE c.id = ? AND c.dt_in IS NULL ORDER BY dt_out DESC""", cdr.exNormalize(id)[1]) rows = self._cursor.fetchall() return rows and rows[0][0] or None
return None return int(round(width * (120.0 / height))) else: cdrcgi.bail("invalid res value '%s'" % res) # If the docId comes in in the format 'CDR99999-111.jpg' it is coming # from the PublishPreview with a size postfix. # We capture the size instructions. # -------------------------------------------------------------------- cdrId = cdrId.split('.')[0] if cdrId.find('-') > 0: docId, width = cdrId.split('-') else: docId = cdrId intId = cdr.exNormalize(docId)[1] # If the docId comes in the format 'CDR000999999' it is coming # from the QC report. If it's coming in the format 'CDR999999' it is # coming from the PublishPreview report. We're selecting the # last publishable version for the PP report. # ------------------------------------------------------------------ ppQuery = "" if pp == 'Y': ppQuery = "AND publishable = 'Y'" elif pp == 'N': ppQuery = "" elif cdrId.find('CDR0') < 0: ppQuery= "AND publishable = 'Y'" query = """\
def __parseBoardDoc(self, id): today = str(self.today) docId = "CDR%d" % id versions = cdr.lastVersions('guest', docId) ver = str(versions[0]) doc = cdr.getDoc('guest', docId, version=ver, getObject=True) errors = cdr.getErrors(doc, errorsExpected=False, asSequence=True) if errors: raise Exception("loading doc for board %d: %s" % (id, "; ".join(errors))) dom = xml.dom.minidom.parseString(doc.xml) for node in dom.documentElement.childNodes: if node.nodeName == "OrganizationNameInformation": for child in node.childNodes: if child.nodeName == "OfficialName": for grandchild in child.childNodes: if grandchild.nodeName == "Name": self.name = cdr.getTextContent(grandchild) elif node.nodeName == "OrganizationType": self.boardType = cdr.getTextContent(node) elif node.nodeName == "PDQBoardInformation": managerNode = None phoneNode = None emailNode = None for child in node.childNodes: if child.nodeName == "BoardManager": managerNode = child elif child.nodeName == "BoardManagerPhone": phoneNode = child elif child.nodeName == "BoardManagerEmail": emailNode = child elif child.nodeName == "BoardMeetings": for grandchild in child.childNodes: if grandchild.nodeName == 'BoardMeeting': md = self.MeetingDate(grandchild) if md.date >= today: self.meetingDates.append(md) elif child.nodeName == "AdvisoryBoardFor": edBoardId = child.getAttribute("cdr:ref") self.edBoardId = cdr.exNormalize(edBoardId)[1] self.manager = self.Manager(managerNode, phoneNode, emailNode) if not self.name or not self.name.strip(): raise Exception("no name found for board in document %d" % id) if not self.manager: raise Exception("no board manager found in document %d" % id) self.boardValues = BoardValues.findBoardValues(self.name) self.summaryType = self.boardValues.summaryType self.workingGroups = self.boardValues.workingGroupBlock self.invitePara = self.boardValues.invitationParagraph self.meetingDates.sort(key=lambda a: a.date) self.name = self.name.strip() if self.boardType.upper() == 'PDQ ADVISORY BOARD': self.advBoardId = self.id self.advBoardName = self.name self.edBoardName = self.__getBoardName(self.edBoardId) elif self.boardType.upper() == 'PDQ EDITORIAL BOARD': self.edBoardId = self.id self.edBoardName = self.name self.advBoardId = self.__findAdvBoardFor(self.id) self.advBoardName = self.__getBoardName(self.advBoardId) else: raise Exception('Board type: %s' % self.boardType)
def __init__(self, cursor, docId, docVer = None): self.docId = cdr.exNormalize(docId)[1] self.docVer = docVer self.mimeType = self.filename = None if docVer: cursor.execute("""\ SELECT xml FROM doc_version WHERE id = ? AND num = ?""", (self.docId, self.docVer)) else: cursor.execute("""\ SELECT xml FROM document WHERE id = ?""", self.docId) rows = cursor.fetchall() if not rows: if docVer: raise Exception("Cannot find version %s of CDR%s" % (docVer, docId)) else: raise Exception("Cannot find CDR%s" % docId) try: tree = etree.XML(rows[0][0]) except Exception as e: try: tree = etree.XML(rows[0][0].encode("utf-8")) except Exception as e: raise Exception("parsing CDR%s: %s" % (docId, e)) if tree.tag == 'Media': for medium in ('Image', 'Sound', 'Video'): xpath = 'PhysicalMedia/%sData/%sEncoding' % (medium, medium) for e in tree.findall(xpath): encoding = e.text self.mimeType = { 'GIF': 'image/gif', 'JPEG': 'image/jpeg', 'PNG': 'image/png', 'MP3': 'audio/mpeg', 'RAM': 'audio/x-pn-realaudio', 'WAV': 'audio/x-wav', 'WMA': 'audio/x-ms-wma', 'AVI': 'video/x-msvideo', 'MPEG2': 'video/mpeg2', 'MJPG': 'video/x-motion-jpeg' }.get(encoding) suffix = { 'GIF': 'gif', 'JPEG': 'jpg', 'PNG': 'png', 'MP3': 'mp3', 'RAM': 'ram', 'WAV': 'wav', 'AVI': 'avi', 'MPEG2': 'mpeg', 'MJPG': 'mjpg' }.get(encoding, 'bin') self.filename = DocInfo.makeFilename(self.docId, docVer, suffix) elif tree.tag == 'SupplementaryInfo': for e in tree.findall('MimeType'): self.mimeType = e.text for e in tree.findall('OriginalFilename'): self.filename = e.text if not self.filename: suffix = { 'application/pdf': 'pdf', 'application/msword': 'doc', 'application/vnd.ms-excel': 'xls', "application/vnd.openxlmformats-officedocument." "spreadsheetml.sheet": "xlsx", 'application/vnd.wordperfect': 'wpd', 'application/vnd.ms-powerpoint': 'ppt', 'application/zip': 'zip', 'text/html': 'html', 'text/plain': 'txt', 'text/rtf': 'rtf', 'message/rfc822': 'eml', 'image/jpeg': 'jpg' }.get(self.mimeType, 'bin') self.filename = DocInfo.makeFilename(self.docId, docVer, suffix) else: raise Exception("don't know about '%s' documents" % tree.tag) if not self.mimeType: if docVer: raise Exception("unable to determine mime type for " "version %s of CDR%d" % (docVer, self.docId)) else: raise Exception("unable to determine mime type for " "CDR%d" % self.docId)
#!/usr/bin/env python #---------------------------------------------------------------------- # # Unlock a document by its doc id. # #---------------------------------------------------------------------- import cdr, sys if len(sys.argv) != 4: sys.stderr.write("usage: UnlockCdrDoc userId pw docId\n") sys.exit(1) session = cdr.login(sys.argv[1], sys.argv[2]) if session.find("<Err") != -1: sys.stderr.write("Failure logging in to CDR: %s" % session) sys.exit(1) # Accept doc id in any form, normalize to CDR000... form docId = cdr.exNormalize(sys.argv[3])[0] err = cdr.unlock(session, docId) if err: sys.stderr.write("Failure unlocking %s: %s" % (docId, err)) else: print("unlocked " + docId)
def main(): #------------------------------------------------------------------ # 1. Parse the command-line options and arguments. #------------------------------------------------------------------ op = createOptionParser() (options, args) = op.parse_args() if len(args) != 4: op.error("incorrect number of arguments") uid, pwd, idArg, filename = args if not options.publishable: options.publishable = 'N' elif options.publishable == 'Y': options.version = 'Y' fullId, intId, fragId = cdr.exNormalize(idArg) # If no comment is specified the last comment used (from the # all_docs table) would be stored. # Setting the comment to something to overwrite the last comment # ----------------------------------------------------------------- if not options.comment: options.comment = "Filter title changed" #------------------------------------------------------------------ # 2. Load the new version of the filter from the file system. #------------------------------------------------------------------ fp = open(filename, 'r') docXml = fp.read() fp.close() if ']]>' in docXml: op.error("CdrDoc wrapper must be stripped from the file") #------------------------------------------------------------------ # 3. Log into the CDR on the target server. #------------------------------------------------------------------ session = cdr.login(uid, pwd) checkForProblems(session, op) #------------------------------------------------------------------ # 4. Check out the document from the target CDR server. #------------------------------------------------------------------ docObj = cdr.getDoc(session, fullId, checkout='Y', getObject=True) checkForProblems(docObj, op) #------------------------------------------------------------------ # 5. Plug in the new title for the filter. #------------------------------------------------------------------ docObj.ctrl['DocTitle'] = getNewTitle(docXml) #------------------------------------------------------------------ # 6. Store the new version on the target CDR server. #------------------------------------------------------------------ doc = str(docObj) print('Versioned: %s, Publishable: %s' % (options.version, options.publishable)) cdrId = cdr.repDoc(session, doc=doc, checkIn="Y", setLinks="N", reason=options.comment, comment=options.comment, ver=options.version, verPublishable=options.publishable) checkForProblems(cdrId, op) #------------------------------------------------------------------ # 7. Report the number of the latest version. #------------------------------------------------------------------ versions = cdr.lastVersions(session, cdrId) if options.version == "N": print("CWD for %s updated" % cdrId) else: print("Latest version of %s is %d" % (cdrId, versions[0])) print("") print("DON'T FORGET TO CHANGE THE TITLE OF THIS FILTER ON ALL TIERS!")