def _returnFile(self, fileName, mime): serverMessageXml = MiniXml("servermessage", "Trying %s" % (fileName)) webInputQueue.put(serverMessageXml.getXmlString()) if (os.path.isfile(os.path.normpath(fileName))): fileHandle = open(fileName, 'rb') self.send_response(200) self.send_header('Content-type', mime) self.end_headers() self.wfile.write(fileHandle.read()) fileHandle.close() self._debugCounter += 1 if (self._debugLastFileName != fileName): self._debugUniqueCounter += 1 self._debugLastFileName = fileName timeStampId = int(time.time() / 100) if (timeStampId != self._debugTimeStamp): serverMessageXml = MiniXml( "servermessage", "DEBUG pcn: Delivered %d images. %d unique." % (self._debugCounter, self._debugUniqueCounter)) self._debugTimeStamp = timeStampId self._debugCounter = 0 self._debugUniqueCounter = 0 else: serverMessageXml = MiniXml( "servermessage", "File not found sending 404: %s" % (fileName)) self.send_error(404, "Returnfile: File not found: %s" % (fileName)) webInputQueue.put(serverMessageXml.getXmlString())
def requestUrl(httpConnection, hostPort, urlArgs, useChacheTrick, saveFileName): excpectedMimeType = "image/jpg" try: if(useChacheTrick == True): urlArgs += "#" + time.time() httpConnection.request("GET", urlArgs) serverResponse = httpConnection.getresponse() if(serverResponse.status == 200): resposeType = serverResponse.getheader("Content-type") if(resposeType == excpectedMimeType): pathDir = os.path.dirname(saveFileName) if(os.path.exists(pathDir) == False): os.makedirs(pathDir) if(os.path.isdir(pathDir) == False): serverMessageXml = MiniXml("servermessage", "Error! Cannot save image. Directory does not exist: %s for file: %s" % (pathDir, saveFileName)) return serverMessageXml.getXmlString() tmpFile = saveFileName + ".tmp" fileHandle=open(tmpFile, 'wb') fileHandle.write(serverResponse.read()) fileHandle.close() shutil.move(tmpFile, saveFileName) return None else: clientMessageXml = MiniXml("servermessage", "Bad file type from server! Got: %s Expected: %s. URL: %s Heaers: %s" % (resposeType, excpectedMimeType, (hostPort + "?" + urlArgs), str(serverResponse.getheaders()) )) return clientMessageXml.getXmlString() else: clientMessageXml = MiniXml("servermessage", "Server trouble. Server returned status: %d Reason: %s" %(serverResponse.status, serverResponse.reason)) return clientMessageXml.getXmlString() except socket.timeout: clientMessageXml = MiniXml("servermessage", "Got timeout exception while requesting URL: " + urlArgs) clientMessageXml.addAttribute("exception", "timeout") return clientMessageXml.getXmlString() except socket.error as (errno, strerror): exception = "" description = "" if(errno == 10060): exception = "timeout" elif((errno == 10061) or (errno == 61)): exception = "connectionRefused" elif((errno == 10065) or (errno == 65)): exception = "noRouteToHost" elif((errno == 11004) or (errno == 8)): exception = "resolvError" else: exception = str(errno) description = str(strerror) clientMessageXml = MiniXml("servermessage", "Got " + exception + " exception while requesting URL: " + hostPort + "?" + urlArgs) clientMessageXml.addAttribute("exception", exception) if(description != ""): clientMessageXml.addAttribute("description", description) return clientMessageXml.getXmlString()
def postXMLFile(urlSignaturer, hostPort, fileType, fileName, xmlString, xmlErrorResponseName="servermessage"): try: files = [(fileType, fileName, xmlString)] fields = urlSignaturer.getSigantureFieldsForFile( fileType, fileName, xmlString) content_type, body = encode_multipart_formdata(fields, files) headers = {"Content-type": content_type} httpConnection = httplib.HTTPConnection(hostPort, timeout=10) httpConnection.request("POST", "", body, headers) serverResponse = httpConnection.getresponse() if (serverResponse.status == 200): resposeType = serverResponse.getheader("Content-type") if (resposeType == "text/xml"): serverResponseData = serverResponse.read() return serverResponseData else: clientMessageXml = MiniXml( xmlErrorResponseName, "Bad file type from server! Got: %s Expected: %s" % (resposeType, "text/xml")) return clientMessageXml.getXmlString() else: clientMessageXml = MiniXml( xmlErrorResponseName, "Server trouble. Server returned status: %d Reason: %s" % (serverResponse.status, serverResponse.reason)) return clientMessageXml.getXmlString() httpConnection.close() except socket.error as (errno, strerror): clientMessageXml = MiniXml( xmlErrorResponseName, "Got exception while posting file: " + fileName) if (errno == 10060): clientMessageXml.addAttribute("exception", "timeout") elif ((errno == 10061) or (errno == 61)): clientMessageXml.addAttribute("exception", "connectionRefused") elif ((errno == 10065) or (errno == 65)): clientMessageXml.addAttribute("exception", "noRouteToHost") elif ((errno == 11004) or (errno == 8)): clientMessageXml.addAttribute("exception", "resolvError") else: clientMessageXml.addAttribute("exception", str(errno)) clientMessageXml.addAttribute("description", str(strerror)) return clientMessageXml.getXmlString()
def sendPlayerConfiguration(self, xmlString): # print "DEBUG " * 20 # print xmlString # print "DEBUG " * 20 commandXml = MiniXml("playerConfigurationSend") commandXml.addAttribute("string", xmlString) self._commandQueue.put(commandXml.getXmlString())
def handle_error(self, request, client_address): """Handle socket errors. """ import traceback cla, exc, trbk = sys.exc_info() if (cla == socket.error): cla, exc, trbk = sys.exc_info() try: excArgs = exc.args except KeyError: excArgs = "<no args>" excTb = traceback.format_tb(trbk, 5) if (webOutputQueue != None): serverExceptionXml = MiniXml("serverException") serverExceptionXml.addAttribute("client", str(client_address)) serverExceptionXml.addAttribute("type", "socket.error") serverExceptionXml.addAttribute("id", str(excArgs[0])) serverExceptionXml.addAttribute("description", str(excArgs[1])) serverExceptionXml.addAttribute("traceback", excTb) webInputQueue.put(serverExceptionXml.getXmlString()) else: print '-' * 40 print 'Exception happened during processing of request from' + str( client_address) print traceback.format_exc() # XXX But this goes to stderr! print '-' * 40
def requestImage(self, noteId, videoPos=0.0, forceUpdate=False): commandXml = MiniXml("thumbnailRequest") commandXml.addAttribute("note", str(noteId)) commandXml.addAttribute("time", "%.2f" % videoPos) if (forceUpdate == True): commandXml.addAttribute("forceUpdate", "True") else: commandXml.addAttribute("forceUpdate", "False") self._commandQueue.put(commandXml.getXmlString())
def log_message(self, formatString, *args): """Log an arbitrary message. This is used by all other logging functions. Override it if you have specific logging wishes. """ serverLogXml = MiniXml("serverLog") serverLogXml.addAttribute("server", self.address_string()) serverLogXml.addAttribute("timeStamp", self.log_date_time_string()) serverLogXml.addAttribute("message", formatString % args) webInputQueue.put(serverLogXml.getXmlString())
def _returnFile(self, fileName, mime): if (os.path.isfile(fileName)): fileHandle = open(fileName, 'rb') self.send_response(200) self.send_header('Content-type', mime) self.end_headers() self.wfile.write(fileHandle.read()) fileHandle.close() else: serverMessageXml = MiniXml( "servermessage", "File not found sending 404: %s" % fileName) self.send_error(404) webInputQueue.put(serverMessageXml.getXmlString())
def guiWebServerProcess(host, port, passwd, appDataDir, serverMessageQueue, serverCommandQueue, webIQ, webOQ): global webInputQueue global webOutputQueue global urlSignaturer global taktPlayerAppDataDirectory import traceback webInputQueue = webIQ webOutputQueue = webOQ urlSignaturer = UrlSignature(passwd) taktPlayerAppDataDirectory = appDataDir server = ErrorHandelingHTTPServer((host, port), PcnWebHandler) server.timeout = 10.0 serverMessageXml = MiniXml( "servermessage", "Started Web server. Address: %s Port: %d" % (host, port)) serverMessageQueue.put(serverMessageXml.getXmlString()) run = True while run: try: server.handle_request() except: serverMessageXml = MiniXml( "servermessage", "Handle request exception! " + traceback.format_exc()) serverMessageQueue.put(serverMessageXml.getXmlString()) pass try: result = serverCommandQueue.get_nowait() if (result == "QUIT"): serverMessageXml = MiniXml("servermessage", "Got QUIT command!") serverMessageQueue.put(serverMessageXml.getXmlString()) run = False except Empty: pass
def guiWebServerProcess(host, port, serverMessageQueue, serverCommandQueue, webIQ, webOQ): global webInputQueue global webOutputQueue webInputQueue = webIQ webOutputQueue = webOQ server = ErrorHandelingHTTPServer((host, port), PcnWebHandler) server.timeout = 10.0 serverMessageXml = MiniXml( "servermessage", "Started Web server. Address: %s Port: %d %s" % (host, port, os.path.abspath(os.path.curdir))) serverMessageQueue.put(serverMessageXml.getXmlString()) timingInfo = None configName = None streamNameList = None run = True while run: try: server.handle_request() except: pass empty = False while not empty: try: result = serverCommandQueue.get_nowait() if (result != None): if (result == "QUIT"): serverMessageXml = MiniXml( "servermessage", "CueServer got QUIT command!") serverMessageQueue.put(serverMessageXml.getXmlString()) run = False else: if (result[0] == "taktInfo_timingInfo"): timingInfo = result[1] elif (result[0] == "taktInfo_configName"): configName = result[1] else: streamNameList = result except Empty: empty = True empty = False while not empty: try: webServerMessage = webInputQueue.get_nowait() if (webServerMessage[0] == "streamName"): if (len(streamNameList) < 1): webOutputQueue.put(None) else: streamId = 0 for i in range(len(streamNameList)): if (streamNameList[i] == webServerMessage[1]): streamId = i streamName = streamNameList[streamId] webOutputQueue.put([ timingInfo, configName, streamNameList, streamName, streamId ]) else: serverMessageQueue.put(webServerMessage) except Empty: empty = True
def requestConfiguration(self, path=None): commandXml = MiniXml("configurationRequest") if (path == None): path = "root" commandXml.addAttribute("path", path) self._commandQueue.put(commandXml.getXmlString())
def do_POST(self): # Parse the form data posted form = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) serverMessageXml = MiniXml("servermessage", "Sending header for post message...") webInputQueue.put(serverMessageXml.getXmlString()) fileCount = 0 fileType = "" fileName = "" sigTime = 0.0 sig = "" fileData = None for field in form.keys(): field_item = form[field] if field_item.filename: fileCount += 1 if (fileCount < 2): fileData = field_item.file.read() fileType = field fileName = field_item.filename else: if (field == "sigTime"): sigTime = float(form[field].value) if (field == "sig"): sig = form[field].value if (fileCount == 1): signatureOk = urlSignaturer.verifySignatureFields( fileType, fileName, fileData, sigTime, sig) if (signatureOk == True): if (fileType == "configuration"): if (fileName == "active configuration"): configTransferRequestXML = MiniXml( "configFileTransfer", "File activated OK!") configTransferRequestXML.addAttribute("type", fileType) configTransferRequestXML.addAttribute( "fileName", fileName) self._returnXmlRespose( configTransferRequestXML.getXmlString()) webInputQueue.put(fileData) else: fileHandle = open( os.path.normpath("config/" + fileName), 'wb') fileHandle.write(fileData) fileHandle.close() configTransferRequestXML = MiniXml( "configFileTransfer", "File saved OK!") configTransferRequestXML.addAttribute("type", fileType) configTransferRequestXML.addAttribute( "fileName", fileName) self._returnXmlRespose( configTransferRequestXML.getXmlString()) elif (fileType == "playerConfiguration"): if (fileName == "player configuration"): configTransferRequestXML = MiniXml( "playerConfigFileTransfer", "File transfered OK!") self._returnXmlRespose( configTransferRequestXML.getXmlString()) playerConfigWrapperXml = MiniXml( "playerConfigFileTransfer", "Player configuration.") playerConfigWrapperXml.addAttribute( "xmlString", fileData) webInputQueue.put( playerConfigWrapperXml.getXmlString()) else: serverMessageXml = MiniXml( "servermessage", "Unknown file type transfered: %s for %s" % (fileType, fileName)) self.send_error(404) webInputQueue.put(serverMessageXml.getXmlString()) else: serverMessageXml = MiniXml("unauthorizedAccess") serverMessageXml.addAttribute( "client", "%s:%d" % (self.client_address[0], self.client_address[1])) serverMessageXml.addAttribute("timeStamp", str(time.time())) self._returnXmlRespose(serverMessageXml.getXmlString()) webInputQueue.put(serverMessageXml.getXmlString()) del fileData else: serverMessageXml = MiniXml( "servermessage", "Bad number of files posted: %d" % (fileCount)) self.send_error(404) webInputQueue.put(serverMessageXml.getXmlString()) return
def requestUrl(hostPort, urlArgs, excpectedMimeType, appDataDirectory=None, xmlErrorResponseName="servermessage"): try: httpConnection = httplib.HTTPConnection(hostPort, timeout=5) httpConnection.request("GET", urlArgs) serverResponse = httpConnection.getresponse() if (serverResponse.status == 200): resposeType = serverResponse.getheader("Content-type") if (resposeType == excpectedMimeType): if (excpectedMimeType == "image/jpg"): pathDir = os.path.dirname(urlArgs) pathFile = os.path.basename(urlArgs) playerFilePath = "" if ((pathDir == "/thumbs") or (pathDir == "thumbs")): playerFilePath = "thumbs/%s" % pathFile else: serverMessageXml = MiniXml( xmlErrorResponseName, "Bad directory in response: %s" % pathDir) return serverMessageXml.getXmlString() thumbsDirPath = os.path.normpath( os.path.join(appDataDirectory, "guiThumbs")) if (os.path.exists(thumbsDirPath) == False): os.makedirs(thumbsDirPath) if (os.path.isdir(thumbsDirPath) == False): serverMessageXml = MiniXml( xmlErrorResponseName, "Error! Cannot save thumbnail. \"guiThumbs\" directory is not in: %s" % appDataDirectory) return serverMessageXml.getXmlString() fullFilePath = os.path.join(thumbsDirPath, pathFile) fileHandle = open(fullFilePath, 'wb') fileHandle.write(serverResponse.read()) fileHandle.close() downloadMessageXml = MiniXml("fileDownloaded") downloadMessageXml.addAttribute("fileName", fullFilePath) downloadMessageXml.addAttribute("playerFileName", playerFilePath) return downloadMessageXml.getXmlString() else: serverResponseData = serverResponse.read() return serverResponseData else: clientMessageXml = MiniXml( xmlErrorResponseName, "Bad file type from server! Got: %s Expected: %s" % (resposeType, excpectedMimeType)) return clientMessageXml.getXmlString() else: clientMessageXml = MiniXml( xmlErrorResponseName, "Server trouble. Server returned status: %d Reason: %s" % (serverResponse.status, serverResponse.reason)) return clientMessageXml.getXmlString() httpConnection.close() except socket.timeout: clientMessageXml = MiniXml( xmlErrorResponseName, "Got timeout exception while requesting URL: " + urlArgs.split("&sigTime=")[0]) clientMessageXml.addAttribute("exception", "timeout") return clientMessageXml.getXmlString() except socket.error as (errno, strerror): exception = "" description = "" if (errno == 10060): exception = "timeout" elif ((errno == 10061) or (errno == 61)): exception = "connectionRefused" elif ((errno == 10065) or (errno == 65)): exception = "noRouteToHost" elif ((errno == 11004) or (errno == 8)): exception = "resolvError" else: exception = str(errno) description = str(strerror) clientMessageXml = MiniXml( xmlErrorResponseName, "Got " + exception + " exception while requesting URL: " + urlArgs.split("&sigTime=")[0]) clientMessageXml.addAttribute("exception", exception) if (description != ""): clientMessageXml.addAttribute("description", description) return clientMessageXml.getXmlString()
def requestConfigNew(self, configName): commandXml = MiniXml("configFileRequest") commandXml.addAttribute("type", "new") commandXml.addAttribute("name", configName) self._commandQueue.put(commandXml.getXmlString())
def requestActiveNoteList(self): commandXml = MiniXml("noteListRequest") self._commandQueue.put(commandXml.getXmlString())
def requestImageFile(self, fileName): commandXml = MiniXml("thumbnailFileRequest") commandXml.addAttribute("fileName", fileName) self._commandQueue.put(commandXml.getXmlString())
def requestConfigList(self): commandXml = MiniXml("configFileRequest") commandXml.addAttribute("type", "list") self._commandQueue.put(commandXml.getXmlString())
def requestTrackState(self): commandXml = MiniXml("trackStateRequest") self._commandQueue.put(commandXml.getXmlString())
clientMessageXml = MiniXml("servermessage", "Server trouble. Server returned status: %d Reason: %s" %(serverResponse.status, serverResponse.reason)) return clientMessageXml.getXmlString() except socket.timeout: clientMessageXml = MiniXml("servermessage", "Got timeout exception while requesting URL: " + urlArgs) clientMessageXml.addAttribute("exception", "timeout") return clientMessageXml.getXmlString() except socket.error as (errno, strerror): exception = "" description = "" if(errno == 10060): exception = "timeout" elif((errno == 10061) or (errno == 61)): exception = "connectionRefused" elif((errno == 10065) or (errno == 65)): exception = "noRouteToHost" elif((errno == 11004) or (errno == 8)): exception = "resolvError" else: exception = str(errno) description = str(strerror) clientMessageXml = MiniXml("servermessage", "Got " + exception + " exception while requesting URL: " + hostPort + "?" + urlArgs) clientMessageXml.addAttribute("exception", exception) if(description != ""): clientMessageXml.addAttribute("description", description) return clientMessageXml.getXmlString() except Exception, e: clientMessageXml = MiniXml("servermessage", "Got exception while requesting URL: " + urlArgs) clientMessageXml.addAttribute("exception", str(e)) return clientMessageXml.getXmlString()
def processGuiRequests(self): try: serverMessage = self._serverMessageQueue.get_nowait() serverMessageXml = stringToXml(serverMessage) if (serverMessageXml != None): if (serverMessageXml.tag == "servermessage"): print "GuiServer Message: " + serverMessageXml.get( "message") except Empty: pass try: webCommand = self._webInputQueue.get_nowait() webCommandXml = stringToXml(webCommand) if (webCommandXml != None): # queueSize = self._webInputQueue.qsize() # if(queueSize > 1): # print "DEBUG pcn: rest web queue size: " + str(queueSize) if (webCommandXml.tag == "servermessage"): print "GuiServer Message: " + webCommandXml.get("message") elif (webCommandXml.tag == "serverLog"): pass # print "%s - - [%s] %s" % (webCommandXml.get("server"), webCommandXml.get("timeStamp"), webCommandXml.get("message")) elif (webCommandXml.tag == "serverException"): print "GuiServer Socket Exception caught when communicationg with: %s [%s] %s" % ( webCommandXml.get("client"), webCommandXml.get("id"), webCommandXml.get("description")) elif (webCommandXml.tag == "thumbRequest"): noteText = getFromXml(webCommandXml, "note", "24") imageTime = float(getFromXml(webCommandXml, "time", "0.0")) forceText = getFromXml(webCommandXml, "forceUpdate", "False") forceUpdate = False if (forceText == "True"): forceUpdate = True # print "GuiServer client request for note: %s at %f (force update: %s)" % (noteText, imageTime, forceText) noteId = max(min(int(noteText), 127), 0) thumbnailFileName = self._mediaPool.requestVideoThumbnail( noteId, imageTime, forceUpdate) resposeXml = MiniXml("thumbRequest") resposeXml.addAttribute("note", str(noteId)) resposeXml.addAttribute("time", "%.2F" % imageTime) resposeXml.addAttribute("fileName", str(thumbnailFileName)) self._webOutputQueue.put(resposeXml.getXmlString()) elif (webCommandXml.tag == "noteListRequest"): # print "GuiServer client request for note list." noteListString = self._mediaPool.requestNoteList() resposeXml = MiniXml("noteListRequest") resposeXml.addAttribute("list", noteListString) self._webOutputQueue.put(resposeXml.getXmlString()) elif (webCommandXml.tag == "trackStateRequest"): # print "GuiServer client request for track state list." trackStateString = self._mediaPool.requestTrackState( time.time()) resposeXml = MiniXml("trackStateRequest") resposeXml.addAttribute("list", trackStateString) self._webOutputQueue.put(resposeXml.getXmlString()) elif (webCommandXml.tag == "effectStateRequest"): noteText = getFromXml(webCommandXml, "note", "None") midiText = getFromXml(webCommandXml, "channel", "None") # print "GuiServer client request for effect state. Note: " + noteText + " MIDI channel: " + midiText try: noteId = max(min(int(noteText), 127), 0) except: noteId = None try: midiId = max(min(int(midiText), 15), 0) except: midiId = None effectStateString, guiStateString = self._mediaPool.requestEffectState( midiId, noteId) resposeXml = MiniXml("effectStateRequest") resposeXml.addAttribute("state", effectStateString) resposeXml.addAttribute("gui", guiStateString) self._webOutputQueue.put(resposeXml.getXmlString()) elif (webCommandXml.tag == "configStateRequest"): configStateString = self._configurationTree.getConfigId() resposeXml = MiniXml("configStateRequest") resposeXml.addAttribute("id", configStateString) # print "GuiServer client request for config state. Current configId: " + str(configStateString) self._webOutputQueue.put(resposeXml.getXmlString()) elif (webCommandXml.tag == "latestMidiControllersRequest"): latestMidiControllers = self._midiStateHolder.getLatestMidiControllersString( ) resposeXml = MiniXml("latestMidiControllersRequest") resposeXml.addAttribute("controllers", latestMidiControllers) # print "GuiServer client request for latest MIDI controllers. List: " + latestMidiControllers self._webOutputQueue.put(resposeXml.getXmlString()) elif (webCommandXml.tag == "configRequest"): path = webCommandXml.get("path") if (path == "root"): path = "musicalvideoplayer" xmlTree = self._configurationTree.getPath(path) if (xmlTree != None): self._webOutputQueue.put( xmlTree.getConfigurationXMLString()) else: resposeXml = MiniXml("configRequest", "Could not find path: %s" % path) self._webOutputQueue.put(resposeXml.getXmlString()) # print "XML: " + xmlTree.getConfigurationXMLString() elif (webCommandXml.tag == "configuration"): print "Updating configuration from GUI..." self._configurationTree.setFromXml(webCommandXml) timeStampString = str(time.time()) self._addEventToSaveLog(timeStampString + "|ConfigSet|Start\n" + webCommand + "\n" + timeStampString + "|ConfigSet|Done") return True elif (webCommandXml.tag == "playerConfigFileTransfer"): # print "Updating player configuration..." xmlString = getFromXml(webCommandXml, "xmlString", "") if (xmlString != ""): innerXml = stringToXml(xmlString) innerXmlString = getFromXml(innerXml, "string", "") if (innerXmlString != ""): self._playerConfiguration.setFromXmlString( innerXmlString) self._playerConfiguration.saveConfig() return True elif (webCommandXml.tag == "configFileRequest"): retVal = False reqType = getFromXml(webCommandXml, "type", "list") fileName = getFromXml(webCommandXml, "fileName", "None") if ((reqType == "load") and (fileName != "None")): filePath = os.path.join(self._configDir, fileName) self._configurationTree.loadConfig(filePath) retVal = True timeStampString = str(time.time()) self._addEventToSaveLog(timeStampString + "|ConfigLoad|Start|" + str(filePath) + "\n" + self._configurationTree. getConfigurationXMLString() + "\n" + timeStampString + "|ConfigLoad|Done") elif ((reqType == "save") and (fileName != "None")): filePath = os.path.join(self._configDir, fileName) self._configurationTree.saveConfigFile(filePath) elif ((reqType == "new") and (fileName != "None")): filePath = os.path.join(self._configDir, fileName) self._configurationTree.newConfigFileName(filePath) configFileList = self._configurationTree.getConfigFileList( self._configDir) currentConfigFile = self._configurationTree.getCurrentFileName( ) currentConfigIsUnsaved = self._configurationTree.isConfigNotSaved( ) resposeXml = MiniXml("configFileRequest") resposeXml.addAttribute("configFiles", configFileList) resposeXml.addAttribute("activeConfig", currentConfigFile) if (currentConfigIsUnsaved == True): resposeXml.addAttribute("configIsSaved", "False") else: resposeXml.addAttribute("configIsSaved", "True") # print "GuiServer client request for configuration file names. List: " + configFileList self._webOutputQueue.put(resposeXml.getXmlString()) return retVal elif (webCommandXml.tag == "playerConfigurationRequest"): resposeXml = MiniXml("playerConfiguration") xmlString = self._playerConfiguration.getXmlString() resposeXml.addAttribute("xmlString", xmlString) # print "GuiServer client request for configuration file names. List: " + configFileList self._webOutputQueue.put(resposeXml.getXmlString()) elif (webCommandXml.tag == "unauthorizedAccess"): print "Unauthorized access from client: %s at %s" % ( webCommandXml.get("client"), webCommandXml.get("timeStamp")) else: print "ERROR! Unknown command from web server: " + str( webCommand) else: print "ERROR! Web server command is not a valid XML: " + str( webCommand) except Empty: pass return False
def requestConfigState(self, oldState): commandXml = MiniXml("configStateRequest") commandXml.addAttribute("oldState", oldState) self._commandQueue.put(commandXml.getXmlString())
def requestEffectState(self, channel, note): commandXml = MiniXml("effectStateRequest") commandXml.addAttribute("channel", channel) commandXml.addAttribute("note", note) self._commandQueue.put(commandXml.getXmlString())
def do_GET(self): parsed_path = urlparse.urlparse(self.path) if (parsed_path.path.endswith(".jpg")): pathDir = os.path.dirname(parsed_path.path) pathFile = os.path.basename(parsed_path.path) filePath = "" dirOk = False if ((pathDir == "/thumbs") or (pathDir == "thumbs")): dirOk = True filePath = os.path.join(taktPlayerAppDataDirectory, "thumbs", pathFile) else: serverMessageXml = MiniXml( "servermessage", "Bad directory request sending 404: %s" % pathDir) webInputQueue.put(serverMessageXml.getXmlString()) if (dirOk == True): self._returnFile(filePath, "image/jpg") else: serverMessageXml = MiniXml( "servermessage", "Bad file request sending 404: %s" % parsed_path.path) self.send_error(404) webInputQueue.put(serverMessageXml.getXmlString()) else: verifiedQuery = urlSignaturer.verifySignature(parsed_path.query) if (verifiedQuery == None): serverMessageXml = MiniXml("unauthorizedAccess") serverMessageXml.addAttribute( "client", "%s:%d" % (self.client_address[0], self.client_address[1])) serverMessageXml.addAttribute("timeStamp", str(time.time())) self._returnXmlRespose(serverMessageXml.getXmlString()) webInputQueue.put(serverMessageXml.getXmlString()) else: queryDict = urlparse.parse_qsl(verifiedQuery) imageThumbNote = self._getKeyValueFromList( queryDict, 'imageThumb', None) configRequestPath = self._getKeyValueFromList( queryDict, 'configPath', None) noteListString = self._getKeyValueFromList( queryDict, 'noteList', None) trackStateString = self._getKeyValueFromList( queryDict, 'trackState', None) effectStateString = self._getKeyValueFromList( queryDict, 'effectState', None) configStateString = self._getKeyValueFromList( queryDict, 'configState', None) latestMidiControllersString = self._getKeyValueFromList( queryDict, 'latestMidiContollers', None) configFileRequestType = self._getKeyValueFromList( queryDict, 'configFileRequest', None) playerConfigurationRequestType = self._getKeyValueFromList( queryDict, 'playerConfigurationRequest', None) if (imageThumbNote != None): thumbTime = float( self._getKeyValueFromList(queryDict, 'time', 0.0)) thumbForceUpdate = self._getKeyValueFromList( queryDict, 'forceUpdate', "False") thumbRequestXml = MiniXml("thumbRequest") thumbRequestXml.addAttribute("note", imageThumbNote) thumbRequestXml.addAttribute("time", "%.2f" % thumbTime) thumbRequestXml.addAttribute("forceUpdate", thumbForceUpdate) webInputQueue.put(thumbRequestXml.getXmlString()) try: thumbnailAnswerXmlString = webOutputQueue.get( True, 5.0) self._returnXmlRespose(thumbnailAnswerXmlString) except: serverMessageXml = MiniXml( "servermessage", "Timeout waiting for thumbnail answer XML: %s" % configRequestPath) self.send_error(500) webInputQueue.put(serverMessageXml.getXmlString()) elif (configRequestPath != None): configRequestXml = MiniXml("configRequest") configRequestXml.addAttribute("path", configRequestPath) webInputQueue.put(configRequestXml.getXmlString()) try: configXmlString = webOutputQueue.get(True, 5.0) self._returnXmlRespose(configXmlString) except: serverMessageXml = MiniXml( "servermessage", "Timeout waiting for configuration XML: %s" % configRequestPath) self.send_error(500) webInputQueue.put(serverMessageXml.getXmlString()) elif (noteListString != None): noteListRequestXml = MiniXml("noteListRequest") webInputQueue.put(noteListRequestXml.getXmlString()) try: noteListXmlString = webOutputQueue.get(True, 5.0) self._returnXmlRespose(noteListXmlString) except: serverMessageXml = MiniXml( "servermessage", "Timeout waiting for note list XML: %s" % configRequestPath) self.send_error(500) webInputQueue.put(serverMessageXml.getXmlString()) elif (trackStateString != None): trackStateRequestXml = MiniXml("trackStateRequest") webInputQueue.put(trackStateRequestXml.getXmlString()) try: trackStateXmlString = webOutputQueue.get(True, 5.0) self._returnXmlRespose(trackStateXmlString) except: serverMessageXml = MiniXml( "servermessage", "Timeout waiting for track state XML: %s" % configRequestPath) self.send_error(500) webInputQueue.put(serverMessageXml.getXmlString()) elif (effectStateString != None): channelString = self._getKeyValueFromList( queryDict, 'channel', "None") noteString = self._getKeyValueFromList( queryDict, 'note', "None") effectStateRequestXml = MiniXml("effectStateRequest") effectStateRequestXml.addAttribute("channel", channelString) effectStateRequestXml.addAttribute("note", noteString) webInputQueue.put(effectStateRequestXml.getXmlString()) try: effectStateXmlString = webOutputQueue.get(True, 5.0) self._returnXmlRespose(effectStateXmlString) except: serverMessageXml = MiniXml( "servermessage", "Timeout waiting for track state XML: %s" % configRequestPath) self.send_error(500) webInputQueue.put(serverMessageXml.getXmlString()) elif (configStateString != None): configStateRequestXml = MiniXml("configStateRequest") webInputQueue.put(configStateRequestXml.getXmlString()) try: configStateXmlString = webOutputQueue.get(True, 5.0) self._returnXmlRespose(configStateXmlString) except: serverMessageXml = MiniXml( "servermessage", "Timeout waiting for config state XML: %s" % configRequestPath) self.send_error(500) webInputQueue.put(serverMessageXml.getXmlString()) elif (latestMidiControllersString != None): latestControllersRequestXml = MiniXml( "latestMidiControllersRequest") webInputQueue.put( latestControllersRequestXml.getXmlString()) try: latestControllersXmlString = webOutputQueue.get( True, 5.0) self._returnXmlRespose(latestControllersXmlString) except: serverMessageXml = MiniXml( "servermessage", "Timeout waiting for latest MIDI controllers XML: %s" % configRequestPath) self.send_error(500) webInputQueue.put(serverMessageXml.getXmlString()) elif (configFileRequestType != None): fileName = self._getKeyValueFromList( queryDict, 'name', "None") configFileRequestXML = MiniXml("configFileRequest") configFileRequestXML.addAttribute("type", configFileRequestType) configFileRequestXML.addAttribute("fileName", fileName) webInputQueue.put(configFileRequestXML.getXmlString()) try: latestControllersXmlString = webOutputQueue.get( True, 5.0) self._returnXmlRespose(latestControllersXmlString) except: serverMessageXml = MiniXml( "servermessage", "Timeout waiting for config file XML: %s" % configRequestPath) self.send_error(500) webInputQueue.put(serverMessageXml.getXmlString()) elif (playerConfigurationRequestType != None): configFileRequestXML = MiniXml( "playerConfigurationRequest") webInputQueue.put(configFileRequestXML.getXmlString()) try: latestControllersXmlString = webOutputQueue.get( True, 5.0) self._returnXmlRespose(latestControllersXmlString) except: serverMessageXml = MiniXml( "servermessage", "Timeout waiting for player config file XML: %s" % configRequestPath) self.send_error(500) webInputQueue.put(serverMessageXml.getXmlString()) else: serverMessageXml = MiniXml( "servermessage", "Bad request from client. Query: %s Client: %s:%d" % (verifiedQuery, self.client_address[0], self.client_address[1])) self.send_error(404) webInputQueue.put(serverMessageXml.getXmlString()) return
def requestPlayerConfiguration(self): commandXml = MiniXml("playerConfigurationRequest") self._commandQueue.put(commandXml.getXmlString())
def requestLatestControllers(self): commandXml = MiniXml("latestMidiContollersRequest") self._commandQueue.put(commandXml.getXmlString())
def do_GET(self): global oldStreamName parsed_path = urlparse.urlparse(self.path) queryDict = urlparse.parse_qsl(parsed_path.query) streamNameString = self._getKeyValueFromList(queryDict, 'streamName', None) cueIdString = self._getKeyValueFromList(queryDict, 'cueId', None) statusString = self._getKeyValueFromList(queryDict, 'status', None) streamId = None if ((statusString != None) or (streamNameString != None)): if (streamNameString == None): streamNameString = oldStreamName else: oldStreamName = streamNameString try: webInputQueue.put(["streamName", streamNameString]) resultValues = webOutputQueue.get(True, 5) if (resultValues != None): (timingInfo, configName, streamNameList, streamName, streamId) = resultValues else: self.send_error( 404, "List error! Please wait until server is done initializing..." ) return except Empty: self.send_error(404, "Server error! Please try again later!") return if (statusString != None): statusJson = "{\n" statusJson += " \"configName\": \"" + str(configName) + "\",\n" statusJson += " \"timingInfo\": \"" + str(timingInfo) + "\"\n" statusJson += "}\n" self.send_response(200) self.send_header("Content-type", "application/json") self.send_header("Content-length", str(len(statusJson))) self.end_headers() self.wfile.write(statusJson) elif (streamId != None): try: fileName = streamName except: serverMessageXml = MiniXml( "servermessage", "FileName not found for streamID: %d" % (streamId)) self.send_error( 404, "FileName not found for id: %s!" % (streamNameString)) webInputQueue.put(serverMessageXml.getXmlString()) finally: self._returnFile("thumbs/preview.jpg", "image/jpg") else: isMobile = False for agentLines in self.headers.getheaders("User-Agent"): if (agentLines.count("Mobile") > 0): isMobile = True webPage = "<html><head>\n" webPage += "<script type=\"text/JavaScript\">\n" webPage += "<!--\n" webPage += "var configName = \"\";\n" webPage += "var streamName = \"\";\n" webPage += "var cueId = 0;\n" if (isMobile): webPage += "var chacheRequest = \"&chacheDummy=\";\n" else: webPage += "var chacheRequest = \"#\";\n" webPage += "var refreshInterval = 100;\n" webPage += "var chacheImage = new Image();\n" webPage += "function updateImage() {\n" webPage += " if(chacheImage.complete) {\n" webPage += " document.getElementById(\"taktImage\").src = chacheImage.src;\n" webPage += " chacheImage = new Image();\n" webPage += " chacheImage.src = configName + \"?streamName=\" + streamName + \"&cueId=\" + cueId;\n" webPage += " }\n" webPage += "}\n" webPage += "function getStatus() {\n" webPage += " var xmlhttp = new XMLHttpRequest();\n" webPage += " var url = \"?streamName=\" + streamName + \"&status=true\";\n" webPage += " xmlhttp.onreadystatechange = function() {\n" webPage += " if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {\n" webPage += " var jsonData = JSON.parse(xmlhttp.responseText);\n" webPage += " configName = jsonData.configName;\n" webPage += " cueId = jsonData.cueId;\n" webPage += " (document.getElementById(\"timingInfo\")).innerHTML = jsonData.timingInfo;\n" webPage += " }\n" webPage += " }\n" webPage += " xmlhttp.open(\"GET\", url, true);\n" webPage += " xmlhttp.send();\n" webPage += "}\n" webPage += "function updateStatus() {\n" webPage += " getStatus();\n" webPage += " updateImage();\n" webPage += " setTimeout(updateStatus, refreshInterval);\n" webPage += "}\n" webPage += "function startStatusUpdate(seconds) {\n" webPage += " refreshInterval = seconds * 1000;\n" webPage += " updateStatus();\n" webPage += "}\n" webPage += "function changeCueStream(newId) {\n" webPage += " streamName = newId;\n" webPage += "}\n" webPage += "// -->\n" webPage += "</script>\n" webPage += "</head>\n" webPage += "<body onload=\"JavaScript:startStatusUpdate(0,5);\">\n" webPage += "<div id=\"timingInfo\">dummy</div>\n" webPage += "<img src=\"\" id=\"taktImage\" alt=\"Cue stream: UNKNOWN\"><br>\n" # numCues = len(streamNameList) # if(numCues > 1): # for i in range(len(streamNameList)): # webPage += "<input id=\"" + streamNameList[i] + "\" type=\"button\" value=\"" + streamNameList[i] + "\" onclick=\"changeCueStream(" + streamNameList[i] + ");\"/>\n" webPage += "</body></html>\n" self._returnHtmlRespose(webPage) # serverMessageXml = MiniXml("servermessage", "DEBUG pcn: %s %s ***%s***" % (parsed_path.query, str(self.headers), str(self.headers.getheaders("User-Agent")))) # webInputQueue.put(serverMessageXml.getXmlString()) return