Beispiel #1
0
	def upload(self):
		self.getDuration()
		try:
			subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 2)/10), "-vframes", "1", "-i", self.path , "-y", "-sameq", "-f", "image2", tempdir()+"screen1.png" ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).wait()
			subprocess.Popen([r"ffmpeg","-ss",str((self.duration * 8)/10), "-vframes", "1", "-i", self.path , "-y", "-sameq", "-f", "image2", tempdir()+"screen2.png" ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).wait()
		except OSError:
			sys.stderr.write("Error: Ffmpeg not installed, refer to http://www.ffmpeg.org/download.html for installation")
			exit(1)
		opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
		params1 = ({'key' : self.key.decode('utf-8').encode('utf-8'), 'image' : open(tempdir()+'screen1.png', "rb")})
		params2 = ({'key' : self.key.decode('utf-8').encode('utf-8'), 'image' : open(tempdir()+'screen2.png', "rb")})
		try:
			socket = opener.open("http://api.imgur.com/2/upload.json", params1)
			read = json.loads(socket.read())
			self.imageurl[0] = read['upload']['links']['original']
			socket.close()
			socket = opener.open("http://api.imgur.com/2/upload.json", params2)
			read = json.loads(socket.read())
			self.imageurl[1] = read['upload']['links']['original']
			socket.close()
			return True
		except urllib2.URLError as s:
			if self.tries < 3:
				self.tries += 1
				sys.stderr.write('Connection timed out, retrying to upload screenshots to imgur. This is try: ')
				sys.stderr.write(str(self.tries))
				sys.stderr.write('\n')
				self.upload()
			return True
    def start(self, gui_listener=None):
        if gui_listener is None:
            write_thread = threading.Thread(target=self.write_handler)
            write_thread.start()

        try:
            while True:
                events = self.sel.select(timeout=1)

                for key, mask in events:
                    socket = key.data
                    try:
                        if mask & selectors.EVENT_READ:
                            socket.read()
                            if socket.response is not None:
                                if gui_listener is None:
                                    self.evaluate_response(socket)
                                else:
                                    gui_listener(socket)
                                socket.response = None
                    except Exception:
                        print(
                            "main: error: exception for",
                            f"{socket.addr}:\n{traceback.format_exc()}",
                        )
                        socket.close()
                # Check for a socket being monitored to continue.
                if not self.sel.get_map():
                    break
        except KeyboardInterrupt:
            print("caught keyboard interrupt, exiting")
        finally:
            self.sel.close()
Beispiel #3
0
def main():
    socket = tcp_connect('testdrs.my-domain-registry.nl')
    socket.write("""<?xml version="1.0" encoding="UTF-8" standalone="no"?><epp xmlns="urn:ietf:params:xml:ns:epp-1.0"><hello/></epp>""")
    data = socket.read()
    print data
    data = socket.read()
    socket.close()
    print data
Beispiel #4
0
    def download(self, tuple):
        # print("download")
        socket = tuple[0]
        path = tuple[1]
        percent = tuple[2]
        dataList = []
        packetLength = len(path) + 10
        msg = struct.pack('<3sIHHHI', b'KDS', packetLength, 6, 0, 0, percent)
        msg += path
        socket.write(QByteArray(msg))
        socket.waitForBytesWritten(1000)
        socket.waitForReadyRead(5000)
        respond = b''
        respond += socket.read(11)
        # print(respond)
        while len(respond) < 11:
            socket.waitForReadyRead(100)
            respond += socket.read(36 - len(respond))
        str, length, packetSize, = struct.unpack('<3sII', respond)
        # print(length)
        # print(packetSize)

        if str == b'KDS':
            while packetSize > 0:
                packetSize -= 1
                packet = b''
                packet += socket.read(36)
                while len(packet) < 36:
                    socket.waitForReadyRead(100)
                    packet += socket.read(36 - len(packet))
                datatuple = struct.unpack('<9f', packet)
                # print(datatuple)
                yaw = math.radians(datatuple[6])
                pitch = math.radians(datatuple[7])
                roll = math.radians(datatuple[8])
                Rx = np.mat([[1, 0, 0], [0, math.cos(roll), -math.sin(roll)],
                             [0, math.sin(roll),
                              math.cos(roll)]])
                Ry = np.mat([[math.cos(pitch), 0,
                              math.sin(pitch)], [0, 1, 0],
                             [-math.sin(pitch), 0,
                              math.cos(pitch)]])
                Rz = np.mat([[math.cos(yaw), -math.sin(yaw), 0],
                             [math.sin(yaw), math.cos(yaw), 0], [0, 0, 1]])
                Vx = np.mat([[1], [0], [0]])
                Vy = np.mat([[0], [1], [0]])
                Vz = np.mat([[0], [0], [1]])
                Vxx = Rx * Ry * Rz * Vx
                Vyy = Rx * Ry * Rz * Vy
                Vzz = Rx * Ry * Rz * Vz
                dataList.append(
                    [datatuple[0:6],
                     Vxx.tolist(),
                     Vyy.tolist(),
                     Vzz.tolist()])

            self.addDataSignal.emit(dataList)
Beispiel #5
0
    def parse(self, socket, game):
        if not self.parse_type(socket.peek(1)) == 'S' :
            return False

        # socket.read(2)
        socket.read(1)

        game.stopped = True

        return True
Beispiel #6
0
    def parse(self, socket, game):
        if not self.parse_type(socket.peek(1)) == 'S' :
            return False

        # socket.read(2)
        socket.read(1)

        game.stopped = True

        return True
Beispiel #7
0
 def dataReceived(self, socket, fd, events):
     #_logger.info("AsyncModbusSerialClient.dataReceived(%s, %s, %s)", str(socket), str(fd), str(events))
     if events & self.ioloop.ERROR:
         _logger.critical("Serial ERROR")
         self.framer.processError(AsyncErrorResponse.SerialConnectionError,
                                  self._handleResponse)
         return
     try:
         data = socket.read(65535)
     except serial.serialutil.SerialException as msg:
         _logger.critical("SerialException: %s", str(msg))
         self.framer.processError(AsyncErrorResponse.SerialReadError,
                                  self._handleResponse)
         return
     #_logger.debug("DATA: %s", str(data))
     #print "RECVSIZE: %d" % self.transaction.recvsize
     self.framer.addToFrame(data)
     if self.framer.isExceptionFrame():
         self.framer.processIncomingPacket(data, self._handleResponse)
         return
     #print "RECVSIZE: %d" % self.transaction.recvsize
     if self.transaction.recvsize:
         if self.framer.getFrameLen() < self.transaction.recvsize:
             _logger.debug("  not enough data yet")
             return
     self.framer.processIncomingPacket(data, self._handleResponse)
Beispiel #8
0
 def loop(self):
     while not self.stop or self.clientManager.clients:            
         read = []
         write = []
         error = []
         
         for client in self.clientManager.clients:
             if client.shouldSelectForRead:
                 read.append(client)
             
             if client.shouldSelectForWrite:
                 write.append(client)
             
             if client.shouldSelectForError:
                 error.append(client)
         
         if not self.stop:
             # Add the server only if we're not stopping it
             read.append(self.ssocket)
         
         readable, writable, errored = select(read, write, error)
         
         for socket in readable:
             if socket is self.ssocket:
                 self.clientManager.clientJoined(*socket.accept())
             else:
                 if not socket.read():
                     # Client left
                     self.clientManager.clientLeft(socket)
Beispiel #9
0
	def upload(self):
		self.getDuration()
                # Take screenshots at even increments between 20% and 80% of the duration
                stops = range(20,81,60/(self.shots-1))
		try:
                        count=0
                        imgs = []
                        for stop in stops:
                                imgs.append(tempdir()+"screen%d.png" % count)
    			        subprocess.Popen([r"ffmpeg","-ss",str((self.duration * stop)/100), "-vframes", "1", "-i", self.path , "-y", "-sameq", "-f", "image2", imgs[-1] ], stdout=subprocess.PIPE, stderr=subprocess.STDOUT).wait()
                                count+=1
		except OSError:
			sys.stderr.write("Error: Ffmpeg not installed, refer to http://www.ffmpeg.org/download.html for installation")
			exit(1)
		opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
		try:
                        for img in imgs:
		                params = ({'key' : self.key.decode('utf-8').encode('utf-8'), 'image' : open(img, "rb")})
			        socket = opener.open("http://api.imgur.com/2/upload.json", params)
			        read = json.loads(socket.read())
			        self.imageurl.append(read['upload']['links']['original'])
			        socket.close()
			        os.remove(img)
			return True
		except urllib2.URLError as s:
			if self.tries < 3:
				self.tries += 1
				sys.stderr.write('Connection timed out, retrying to upload screenshots to imgur. This is try: ')
				sys.stderr.write(str(self.tries))
				sys.stderr.write('\n')
				self.upload()
			return True
Beispiel #10
0
    def parse(self, socket, game):
        if not self.parse_type(socket.peek(1)) == 'A' :
            return False

        socket.read(1)

        data = socket.read(1)

        packet = AckPacket.parse(data)

        self.id = packet.id

        print("Game ID {}".format(self.id))

        game.gameid = self.id

        return True
Beispiel #11
0
    def parse(self, socket, game):
        if not self.parse_type(socket.peek(1)) == 'A' :
            return False

        socket.read(1)

        data = socket.read(1)

        packet = AckPacket.parse(data)

        self.id = packet.id

        print("Game ID {}".format(self.id))

        game.gameid = self.id

        return True
Beispiel #12
0
 def handle_data(self, socket, address):
     msg = ""
     while True:
         msg += str(socket.read())
         if msg[-1] == "\0":
             socket.close()
             break
     return self.handle_message(msg[:-1], socket, address)
Beispiel #13
0
 def handle_data(self, socket, address):
     msg = ""
     while True:
         msg += str( socket.read() )
         if msg[-1] == "\0":
             socket.close()
             break
     return self.handle_message(msg[:-1], socket, address)
def main(socket):
    while (True):
        input_length = _read_int(socket)
        data = socket.read(input_length)
        result = transform(data)
        resultBytes = result.encode()
        _write_int(len(resultBytes), socket)
        socket.write(resultBytes)
        socket.flush()
Beispiel #15
0
def read_socket_w_progress (socket, progress, message):
    """Read piecemeal reporting progress as we go."""
    if not progress: data = socket.read()
    else:
        bs = 1024 * 8
        if hasattr(socket,'headers'):
            fs = int(socket.headers.get('content-length',-1))
        else: fs = -1
        block = socket.read(bs)
        data = block
        sofar = bs
        while block:
            if fs>0: progress(float(sofar)/fs, message)
            else: progress(-1, message)
            sofar += bs
            block = socket.read(bs)
            data += block
    socket.close()
    return data
Beispiel #16
0
def read_socket_w_progress (socket, progress, message):
    """Read piecemeal reporting progress as we go."""
    if not progress: data = socket.read()
    else:
        bs = 1024 * 8
        if hasattr(socket,'headers'):
            fs = int(socket.headers.get('content-length',-1))
        else: fs = -1
        block = socket.read(bs)
        data = block
        sofar = bs
        while block:
            if fs>0: progress(float(sofar)/fs, message)
            else: progress(-1, message)
            sofar += bs
            block = socket.read(bs)
            data += block
    socket.close()
    return data
    def download(self):
        strinfo = "Begin to download slices of " + self.imagename + "..."
        print(strinfo)
        #construct map slide url
        urlpre = "http://ids.lib.harvard.edu/ids/view/Converter?id=" + self.imageid + "&c=jpgnocap&s=1.0000&r=0&"

        for Yindex in range(0, 4):
            for Xindex in range(0, 4):

                imagename = self.imagename + "_" + str(Yindex) + "_" + str(
                    Xindex) + ".jpg"
                #check if exists
                if os.path.isfile(imagename):
                    strinfo = imagename + " already exits"
                    print strinfo
                else:
                    X = Xindex * 2400
                    Y = Yindex * 1835
                    urllast = "&w=2400&h=1835"
                    #the last column or last row
                    if Xindex == 3:
                        if Yindex == 3:
                            w = 1646
                            h = 1231
                            urllast = "&w=" + str(w) + "&h=" + str(h)
                        else:
                            w = 1646
                            urllast = "&w=" + str(w) + "&h=1835"
                    else:
                        if Yindex == 3:
                            h = 1231
                            urllast = "&w=2400&h=" + str(h)

                    urlmid = "x=" + str(X) + "&y=" + str(Y)
                    url = urlpre + urlmid + urllast

                    imagedata = None
                    while not imagedata:
                        time.sleep(3)
                        socket = urllib2.urlopen(url)
                        time.sleep(5)
                        imagedata = socket.read()

                    try:
                        with open(imagename, "wb") as jpg:
                            jpg.write(imagedata)
                            socket.close()
                            jpg.close()

                            strinfo = imagename + ' download successfully'
                            print(strinfo)
                    except:
                        strinfo = imagename + ' download error'
                        print(strinfo)
        self.stop()
 def download(self):
     strinfo = "Begin to download slices of "+self.imagename+"..."
     print(strinfo)
     #construct map slide url
     urlpre = "http://ids.lib.harvard.edu/ids/view/Converter?id="+self.imageid+"&c=jpgnocap&s=1.0000&r=0&"
     
     for Yindex in range(0,4):
         for Xindex in range(0,4):
             
             imagename = self.imagename + "_"+str(Yindex)+"_"+str(Xindex)+".jpg"
             #check if exists
             if os.path.isfile(imagename):
                 strinfo = imagename+" already exits"
                 print strinfo
             else:                 
                 X = Xindex*2400
                 Y = Yindex*1835
                 urllast ="&w=2400&h=1835"
                 #the last column or last row
                 if Xindex==3:
                     if Yindex==3:
                         w=1646 
                         h=1231
                         urllast ="&w="+str(w)+"&h="+str(h) 
                     else:
                         w =1646                 
                         urllast ="&w="+str(w)+"&h=1835"                    
                 else:
                     if Yindex==3:
                         h=1231
                         urllast ="&w=2400&h="+str(h)                
                     
                 urlmid = "x="+str(X)+"&y="+str(Y)
                 url = urlpre+urlmid+urllast
             
                 imagedata = None
                 while not imagedata:
                     time.sleep(3)
                     socket = urllib2.urlopen(url)
                     time.sleep(5)
                     imagedata = socket.read()
                     
                 try:
                     with open(imagename, "wb") as jpg:
                         jpg.write(imagedata)
                         socket.close()
                         jpg.close()
                         
                         strinfo = imagename+' download successfully' 
                         print(strinfo)
                 except:
                     strinfo = imagename+' download error' 
                     print(strinfo)
     self.stop()
Beispiel #19
0
def execute(read_socket, write_socket):
    run = True
    while (run):
        print "running in main loop"
        ready = select.select([read_socket], [], [], None)
        read_sockets = ready[0]
        if read_sockets:
            socket = read_sockets[0]
            data = socket.read()
            if not data:
                break
            print data
            write_socket.write(data)
Beispiel #20
0
 def _retrieveImage(self, imageUrl, path):
     """
     Urlretrieve doesn't handle 404 Errors - we need to do this ourselves
     """
     success = False
     try:
         socket = urllib2.urlopen(imageUrl)
         local_file = open(path, "w")
         local_file.write(socket.read())
         local_file.close()
         success = True
     except urllib2.HTTPError, e:
         recognosco.logger.warning("HTTP Error %d: %s", e.code , imageUrl)
         success = False
	def parse(self):
		try:
			socket = urllib2.urlopen(self.url) 
			content = socket.read()
			socket.close()
			#解析漫画名
			self.name = Fetch.fetch_name(content)
			#解析章节
			chapter_parser = ParserChapter()
			chapter_parser.feed(content)
			self.chapter_url = chapter_parser.get_chapter_url()
		except Exception, e:
			print "Manga.parse", e
			return False
Beispiel #22
0
    def parse(self, socket, game):
        # print("Try to parse PlayerKey")
        if not self.parse_type(socket.peek(1)) == 'I' :
            return False

        # print("Parsed PlayerKey")

        socket.read(1)

        data = socket.read(2)

        packet = PlayerKeyPacket.parse(data)

        self.player1 = packet.player1
        self.player2 = packet.player2

        # print("Player {} key {}".format(self.player, self.key))
        # print("Player 1 {}".format(self.player1))
        # print("Player 2 {}".format(self.player2))

        game.player1_keys = self.player1
        game.player2_keys = self.player2

        return True
Beispiel #23
0
    def parse(self, socket, game):
        # print("Try to parse PlayerKey")
        if not self.parse_type(socket.peek(1)) == 'I' :
            return False

        # print("Parsed PlayerKey")

        socket.read(1)

        data = socket.read(2)

        packet = PlayerKeyPacket.parse(data)

        self.player1 = packet.player1
        self.player2 = packet.player2

        # print("Player {} key {}".format(self.player, self.key))
        # print("Player 1 {}".format(self.player1))
        # print("Player 2 {}".format(self.player2))

        game.player1_keys = self.player1
        game.player2_keys = self.player2

        return True
Beispiel #24
0
 def start(self):
     try:
         while True:
             events = self.sel.select(timeout=None)
             for key, mask in events:
                 if key.data is None:
                     self.accept_wrapper(key.fileobj)
                 else:
                     socket = key.data
                     try:
                         if mask & selectors.EVENT_READ:
                             socket.read()
                         if mask & selectors.EVENT_WRITE:
                             self.evaluate_request(socket)
                     except Exception:
                         print(
                             "main: error: exception for",
                             f"{socket.addr}:\n{traceback.format_exc()}",
                         )
                         socket.close()
     except KeyboardInterrupt:
         print("caught keyboard interrupt, exiting")
     finally:
         self.sel.close()
Beispiel #25
0
    def handle(self):
        socket = self.nextPendingConnection()
        requestheader = socket.read(1)

        def respond_with(tty_device_file):
            self.tty_device_file = tty_device_file
            response = tty_device_file

            responseheader = chr(len(response))

            socket.write(responseheader)
            socket.write(response)
            socket.close()

        if (self.tty_device_file == None):
            outputterm = TargetTerminalWidget(self.termHolder, respond_with)
        else:
            respond_with(self.tty_device_file)
	def parse(self):
		path_manga = os.path.join(path_cur, self.manga.name).decode("utf-8")
		if not os.path.exists(path_manga):
			os.mkdir(path_manga)
		else:
			return False
		for chapter, url in self.selection:
			path_chapter = os.path.join(path_manga.encode("utf-8"), chapter).decode("utf-8")
			if not os.path.exists(path_chapter):
				os.mkdir(path_chapter)
			socket = urllib2.urlopen(url)
			content = socket.read()
			socket.close()
			img_urls = Fetch.fetch_img(content)
			self.page_num += len(img_urls)
			for i, img_url in enumerate(img_urls):
				pic_name = ".".join([str(i + 1), Fetch.fetch_type(img_url)]) 
				location = os.path.join(path_chapter, pic_name)
				self.blocks.append(Block(self, img_url, location))

		return True
Beispiel #27
0
 def dataReceived(self, socket, fd, events):
     _logger.info("AsyncModbusSerialClient.dataReceived(%s, %s, %s)", str(socket), str(fd), str(events))
     if events & self.ioloop.ERROR:
         _logger.critical("Serial ERROR")
         self.framer.processError(AsyncErrorResponse.SerialConnectionError, self._handleResponse)
         return
     try:
         data = socket.read(65535)
     except serial.serialutil.SerialException as msg:
         _logger.critical("SerialException: %s", str(msg))
         self.framer.processError(AsyncErrorResponse.SerialReadError, self._handleResponse)
         return
     _logger.debug("DATA: %s", str(data))
     self.framer.addToFrame(data)
     if self.framer.isExceptionFrame():
         self.framer.processIncomingPacket(data, self._handleResponse)
         return
     if self.transaction.recvsize:
         if self.framer.getFrameLen() < self.transaction.recvsize:
             _logger.debug("  not enough data yet")
             return
     self.framer.processIncomingPacket(data, self._handleResponse)
Beispiel #28
0
					   socket.
		'''

        # Read from the connected socket until the packet length is reached or
        # the maximum size is reached. When the entire message is recovered
        # string it together and return it. If at any point nothing is received
        # it is assumed that the connection was broken or the transmission
        # finished and what is in the buffer will be returned.
        chunks = []
        total_recieved = 0
        while total_recieved < 2048:
            chunk = self.sock.recv(min(2048 - total_recieved, 2048))
            if chunk == '':
                break
                raise RuntimeError('Connection Broken')
            chunks.append(chunk)
            total_recieved = total_recieved + len(chunk)
        return ''.join(chunks)

    def close(self):
        self.sock.close()


if __name__ == '__main__':
    socket = TCPSocket('hello')
    socket.connect('104.131.44.2', 3000)
    socket.write('GET / HTTP/1.1\rHost: www.batphone.co\r\n\r\n')
    sleep(2)
    response = socket.read()
    print response
Beispiel #29
0
import socket
import urllib

__author__="uli"
__date__ ="$12.01.2009 16:48:52$"

if __name__ == "__main__":
    url = raw_input("URL: ")
    count = int(raw_input("Count: "))
    traffic = 0 #Traffic in bytes
    for i in xrange(count):
        print "Starting %ith download" % (i+1)
        socket = urllib.urlopen(url)
        d = socket.read()
        traffic += len(d)
        print "Finished %ith download" % (i+1)
        print "Traffic: %i bytes" % traffic
    print "Overall traffic: %i bytes" % traffic
Beispiel #30
0
 def searchsubtitlesbyname_pod( self, name, lang1,lang2,lang3,year ):
     
             self.subtitles_name_list = []
             year = str(year)
             search_url = ""
             season = ""
             episode = ""
             title1 = xbmc.getInfoLabel("VideoPlayer.TVshowtitle")
             title = title1.replace(" ","+")
             if year == "0" : year = ""
             tbsl = "1"
             lang_num1 = twotoone(lang1)
             lang_num2 = None
             lang_num3 = None
             if lang2!=lang1:
                     lang_num2 = twotoone(lang2)
             if lang3!=lang1 and lang3!=lang2:
                     lang_num3 = twotoone(lang3)
     
             if len(title) > 1:
                     name = title
                     season = xbmc.getInfoLabel("VideoPlayer.Season")
                     episode = xbmc.getInfoLabel("VideoPlayer.Episode")
                     
             search_url = "http://www.podnapisi.net/ppodnapisi/search?tbsl=1&sK=" + name + "&sJ=" +lang_num1+ "&sY=" + str(year)+ "&sTS=" + str(season) + "&sTE=" + str(episode) + "&sXML=1"
             search_url1 = None
             search_url2 = None
     
             if lang_num2 is not None:
                     search_url1 = "http://www.podnapisi.net/ppodnapisi/search?tbsl=1&sK=" + name + "&sJ=" +lang_num2+ "&sY=" + str(year)+ "&sTS=" + str(season) + "&sTE=" + str(episode) + "&sXML=1"
     
             if lang_num3 is not None:
                     search_url2 = "http://www.podnapisi.net/ppodnapisi/search?tbsl=1&sK=" + name + "&sJ=" +lang_num3+ "&sY=" + str(year)+ "&sTS=" + str(season) + "&sTE=" + str(episode) + "&sXML=1"
     
             try:
                     
     
                     search_url.replace( " ", "+" )
                     if self.debug : 
                             LOG( LOG_INFO, search_url )
                             LOG( LOG_INFO, "Searching subtitles by name_pod [" + name + "]" )
     
                     socket = urllib.urlopen( search_url )
                     result = socket.read()
                     socket.close()
                     xmldoc = minidom.parseString(result)
                     
                     subtitles = xmldoc.getElementsByTagName("subtitle")
                     
                     if search_url1 is not None: 
                             socket = urllib.urlopen( search_url1 )
                             result = socket.read()
                             socket.close()
                             xmldoc = minidom.parseString(result)
                             subtitles1 = xmldoc.getElementsByTagName("subtitle")
                             subtitles = subtitles + subtitles1              
                     
                     if search_url2 is not None: 
                             socket = urllib.urlopen( search_url2 )
                             result = socket.read()
                             socket.close()
                             xmldoc = minidom.parseString(result)
                             subtitles1 = xmldoc.getElementsByTagName("subtitle")
                             subtitles = subtitles + subtitles1
                     
                     if subtitles:
                             url_base = "http://www.podnapisi.net/ppodnapisi/download/i/"
     
                             for subtitle in subtitles:
                                     filename = ""
                                     movie = ""
                                     lang_name = ""
                                     subtitle_id = 0
                                     lang_id = ""
                                     flag_image = ""
                                     link = ""
                                     format = "srt"
                                     no_files = ""
                                     if subtitle.getElementsByTagName("title")[0].firstChild:
                                             movie = subtitle.getElementsByTagName("title")[0].firstChild.data
     
                                     if subtitle.getElementsByTagName("release")[0].firstChild:
                                             filename = subtitle.getElementsByTagName("release")[0].firstChild.data
                                             if len(filename) < 2 :
                                                     filename = movie + " (" + year +")"
                                     else:
                                             filename = movie + " (" + year +")"
     
                                     filename = filename + "." +  format
                                     rating = 0
                                     if subtitle.getElementsByTagName("rating")[0].firstChild:
                                             rating = subtitle.getElementsByTagName("rating")[0].firstChild.data
                                             rating = int(rating)*2                  
                                     
     
                                     if subtitle.getElementsByTagName("languageName")[0].firstChild:
                                             lang_name = subtitle.getElementsByTagName("languageName")[0].firstChild.data
                                     if subtitle.getElementsByTagName("id")[0].firstChild:
                                             subtitle_id = subtitle.getElementsByTagName("id")[0].firstChild.data
     
                                     flag_image = "flags/" + toOpenSubtitles_two(lang_name) + ".gif"
     
                                     link = url_base + str(subtitle_id)
     
                                     if subtitle.getElementsByTagName("cds")[0].firstChild:
                                             no_files = int(subtitle.getElementsByTagName("cds")[0].firstChild.data)
                                     
                                             
                                     self.subtitles_name_list.append({'filename':filename,'link':link,'language_name':lang_name,'language_id':lang_id,'language_flag':flag_image,'movie':movie,"ID":subtitle_id,"rating":str(rating),"format":format,"sync":False, "no_files":no_files})
     
                             message =  str( len ( self.subtitles_name_list )  ) + " subtitles found"
                             if self.debug : LOG( LOG_INFO, message )
                             return True, message
                     else: 
                             message = "No subtitles found"
                             if self.debug : LOG( LOG_INFO, message )
                             return True, message
     
             except Exception, e:
                     error = _( 743 ) % ( search_url, str ( e ) ) 
                     if self.debug : LOG( LOG_ERROR, error )
                     return False, error
Beispiel #31
0
 def _get_doc(url):
     req = urllib2.Request(url, headers=headers)
     socket = urllib2.urlopen(req)
     ret = socket.read()
     return BeautifulSoup(ret, 'html.parser')
Beispiel #32
0
    "hostname": getHostname(),
    "interfaces": getInterfaces(),
    "ps": getPS(),
    "who": getWho(),
    "uplo": getUptime(),
    "ram": getRAM(),
    "ips": getIPs(),
    "disk": getDisk(),
    "key": ssconf.key,
    "uid": ssconf.uid,
}
dump = json.dumps(dic)

put(s, "POST %s HTTP/1.1" % ssconf.page)
put(s, "Host: %s" % ssconf.remote[0])
put(s, "Content-Type: application/x-www-form-urlencoded")
put(s, "Content-Length: %d" % len(dump))
put(s, "User-Agent: SS/%.1f" % ver)
put(s, "Connection: close")
put(s, "")
put(s, dump)
put(s, "")

print socket.read(30)

try:
    s.shutdown(socket.SHUT_RDWR)
    s.close()
except socket.error, err:
    pass
Beispiel #33
0
print "sending ..."
socket.write(msg)

payloadType = 0 #0=string
data = "{\"type\":\"GET_STATUS\",\"requestId\":46479000}"
lnData = getLenOf(data)
namespace = "urn:x-cast:com.google.cast.receiver"
msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len(source_id),len(destination_id),len(namespace),len(lnData),len(data)),getType(1,TYPE_ENUM),protocolVersion,getType(2,TYPE_STRING),len(source_id),source_id,getType(3,TYPE_STRING),len(destination_id),destination_id,getType(4,TYPE_STRING),len(namespace),namespace,getType(5,TYPE_ENUM),payloadType,getType(6,TYPE_BYTES),lnData,data)
msg = pack(">I%ds" % (len(msg)),len(msg),msg)
print "sending ..."
socket.write(msg)

m=None
result=""
while m==None:
	lastresult = socket.read(2048)
	result += lastresult
	print "#"+lastresult.encode("hex")
	print clean("!"+lastresult)
	m = re.search('"sessionId":"(?P<session>[^"]+)"', result)
	print "#%i" % (m==None)

print "session:",m.group("session")
session = m.group("session")


payloadType = 0 #0=string
data = "{\"type\":\"LAUNCH\",\"requestId\":46479001,\"appId\":\"CC1AD845\"}"
lnData = getLenOf(data)
namespace = "urn:x-cast:com.google.cast.receiver"
msg = pack(">BBBB%dsBB%dsBB%dsBBB%ds%ds" % (len(source_id),len(destination_id),len(namespace),len(lnData),len(data)),getType(1,TYPE_ENUM),protocolVersion,getType(2,TYPE_STRING),len(source_id),source_id,getType(3,TYPE_STRING),len(destination_id),destination_id,getType(4,TYPE_STRING),len(namespace),namespace,getType(5,TYPE_ENUM),payloadType,getType(6,TYPE_BYTES),lnData,data)
Beispiel #34
0
import socket
import urllib

__author__ = "uli"
__date__ = "$12.01.2009 16:48:52$"

if __name__ == "__main__":
    url = raw_input("URL: ")
    count = int(raw_input("Count: "))
    traffic = 0  #Traffic in bytes
    for i in xrange(count):
        print "Starting %ith download" % (i + 1)
        socket = urllib.urlopen(url)
        d = socket.read()
        traffic += len(d)
        print "Finished %ith download" % (i + 1)
        print "Traffic: %i bytes" % traffic
    print "Overall traffic: %i bytes" % traffic
		None

		RETURNS:
		@message 	-- The message received from the currently connected
					   socket.
		'''

		# Read from the connected socket until the packet length is reached or
		# the maximum size is reached. When the entire message is recovered
		# string it together and return it. If at any point nothing is received
		# it is assumed that the connection was broken or the transmission
		# finished and what is in the buffer will be returned.
		chunks = []
		total_recieved = 0
		while total_recieved < 2048:
			chunk = self.sock.recv(min(2048 - total_recieved, 2048))
			if chunk == '':
				break
				raise RuntimeError('Connection Broken')
			chunks.append(chunk)
			total_recieved = total_recieved + len(chunk)
		return ''.join(chunks)	

if __name__ == '__main__':
	socket = TCPSocket('hello')
	socket.connect('104.131.44.2', 3000)
	socket.write('GET / HTTP/1.1\rHost: www.batphone.co\r\n\r\n')
	sleep(2)
	response = socket.read()
	print response