Exemplo n.º 1
0
    def tryGetAsxURL(self):
        """ give this the stream you want to play and this 
         will give you the
         url for the asx, play that url
         if it failes with an AuthError try Sirius.auth() and try again
         or use getAsxUrl
      """

        self.validateStream()

        postdict = { 'channelKey': self.__stream['channelKey'],
                     'genreKey': self.__stream['genreKey'],
                     'categoryKey': self.__stream['categoryKey'],
                     'selectedStream': self.__stream['selectedStream'],
                     'stopped': 'no',
                   }
        data = self.__getURL(
            'http://www.sirius.com/player/listen/play.action',
            postdict).read()

        data = self.sanitize(data)
        soup = BeautifulSoup(data)
        try:
            firstURL = soup.find('param', {'name': 'FileName'})['value']
        except TypeError:
             logfile("getasuxurl-ERROR.html",data) #DEBUG
             log("\nAuth Error:, see getasuxurl-ERROR.html\n") #DEBUG
             raise AuthError
        if not firstURL.startswith('http://'):
            firstURL = 'http://%s%s' % (self.host, firstURL)
        asxURL = self.__getURL(firstURL).read()
        self.asxURL = asxURL
        log('asxURL = %s' % asxURL)
        return asxURL
Exemplo n.º 2
0
    def play(self, stream):
        """Plays the given stream

        stream: the station name"""
        try:
            log('Play %s' % stream)
            self.sirius.setStreamByLongName(stream)
        except:
            print "Invalid station name. Type 'list' to see available station names"
            return
        else:
            if self.options.record:
                print "Recording %s. Please use Ctrl+C to stop." % stream
            else:
                print "Now playing %s. Please use Ctrl+C to stop." % stream

        while True: #playing loop
            if not self.player.playing():
                url = self.sirius.getAsxURL()
                self.player.play(url, stream)

            playing = self.sirius.nowPlaying()
            if playing['new'] :
                if not self.options.quiet:
                    print time.strftime('%H:%M' ) + ' - ' + playing['longName'] + ": " + playing['playing']
                if self.notification:
                    import pynotify
                    if pynotify.init("Pyxis"):
                        icon = os.path.dirname(__file__) + '/data/dog_white_outline.svg'
                        n = pynotify.Notification("Sirius", playing['longName'] + ": " + playing['playing'], icon)
                        n.show()
            try:
                time.sleep(30)
            except KeyboardInterrupt:
                break
Exemplo n.º 3
0
	def ClearSession(self,name, verbose=True):
		import os
		if os.path.exists(self.SessionName(name)):
			if verbose:
				print >>sys.stderr, "Warning: Open session %s exists. Overwriting."%name
			log("removing session %s"%name)
			os.remove(self.SessionName(name))
def throughAllCombinationsRecursive(elementsToCombineList,byAmount):
    reList=[]
    
    if byAmount==0:
        return []
    
    for i in range(len(elementsToCombineList)):
        item=elementsToCombineList[i]
    
    
        elementsToCombineListWithoutItemS=delElementsLessOrEqualThanValue(elementsToCombineList,item)
        
        
        if len(elementsToCombineListWithoutItemS) < byAmount-1 and byAmount>1:
            
            return reList
        
        recursiveList=throughAllCombinationsRecursive(elementsToCombineListWithoutItemS,byAmount-1)
        log("recursiveList"+ str(recursiveList))
    
    
        if len(recursiveList)==0:
            reList+=[[item]]
        
        for j in range(len(recursiveList)):
            recursiveItem=recursiveList[j]
            reList+=[[item]+recursiveItem]
        
    
    
    return reList
Exemplo n.º 5
0
	def __init__(self, shell, session_dir, main_dir):
		super(env_manager, self).__init__()
		self.shell = shell
		import os
		self.session_dir = os.path.normpath(session_dir)+os.sep
		self.main_dir = os.path.normpath(main_dir)+os.sep
		log("initialized the EnvManager")
Exemplo n.º 6
0
    def getURL(self, url, postdict=None, poststring=None):
        """ get a url, the second arg could be dictionary of 
         options for a post 
         If there is no second option use get
         This will use the cookies and tokens for this instance 
         of Sirius
         returns a file handle
      """

        if postdict:
            postdata = urllib.urlencode(postdict)
        else:
            postdata = None
        if poststring:
            postdata = poststring

        log("url=%s" % url)  #DEBUG
        log("POST=%s" % postdata)  #DEBUG

        req = urllib2.Request(url, postdata, self.__headers)
        handle = None
        while handle is None:
            try:
                handle = urllib2.urlopen(req)
            except urllib2.URLError:
                print(
                    "Error while fetching %s\nTrying again in 30 seconds..." %
                    url)
                time.sleep(30)
                handle = None
        self.__cookie_jar.save(ignore_discard=True, ignore_expires=True)
        return handle
Exemplo n.º 7
0
    def tryGetAsxURL(self, stream):
        """ give this the stream you want to play and this 
         will give you the
         url for the asx, play that url
         if it failes with an AuthError try Sirius.auth() and try again
         or use getAsxUrl
      """

        self.sirius.validateStream()

        postdict = {
            'channelKey': stream['channelKey'],
            'genreKey': stream['genreKey'],
            'categoryKey': stream['categoryKey'],
            'selectedStream': stream['selectedStream'],
            'stopped': 'no',
        }
        data = self.sirius.getURL(
            'http://www.sirius.com/player/listen/play.action',
            postdict).read()

        data = self.sirius.sanitize(data)
        soup = BeautifulSoup(data)
        try:
            firstURL = soup.find('param', {'name': 'FileName'})['value']
        except TypeError:
            logfile("getasuxurl-ERROR.html", data)  #DEBUG
            log("\nAuth Error:, see getasuxurl-ERROR.html\n")  #DEBUG
            raise AuthError
        if not firstURL.startswith('http://'):
            firstURL = 'http://%s%s' % (self.host, firstURL)
        asxURL = self.sirius.getURL(firstURL).read()
        log('asxURL = %s' % asxURL)
        return asxURL
Exemplo n.º 8
0
    def tryGetAsxURL(self, stream):
        """ give this the stream you want to play and this 
         will give you the
         url for the asx, play that url
         if it failes with an AuthError try Sirius.auth() and try again
         or use getAsxUrl
      """

        self.sirius.validateStream()

        postdict = {
            "channelKey": stream["channelKey"],
            "genreKey": stream["genreKey"],
            "categoryKey": stream["categoryKey"],
            "selectedStream": stream["selectedStream"],
            "stopped": "no",
        }
        data = self.sirius.getURL("http://www.sirius.com/player/listen/play.action", postdict).read()

        data = self.sirius.sanitize(data)
        soup = BeautifulSoup(data)
        try:
            firstURL = soup.find("param", {"name": "FileName"})["value"]
        except TypeError:
            logfile("getasuxurl-ERROR.html", data)  # DEBUG
            log("\nAuth Error:, see getasuxurl-ERROR.html\n")  # DEBUG
            raise AuthError
        if not firstURL.startswith("http://"):
            firstURL = "http://%s%s" % (self.host, firstURL)
        asxURL = self.sirius.getURL(firstURL).read()
        log("asxURL = %s" % asxURL)
        return asxURL
Exemplo n.º 9
0
 def ApplySwap(self,inv,li):
     if inv[0] not in li or inv[1] not in li:
         log("Couldn't apply swap",linversion=inv,list=li)
         return
     ind1 = li.index(inv[0])
     ind2 = li.index(inv[1])
     li[ind1],li[ind2] = li[ind2],li[ind1]
Exemplo n.º 10
0
    def getURL(self, url, postdict=None, poststring=None):
        """ get a url, the second arg could be dictionary of 
         options for a post 
         If there is no second option use get
         This will use the cookies and tokens for this instance 
         of Sirius
         returns a file handle
      """

        if postdict:
            postdata = urllib.urlencode(postdict)
        else:
            postdata = None
        if poststring:
            postdata = poststring

        log("POST=%s" % postdata)#DEBUG
        log("url=%s" % url) #DEBUG

        req = urllib2.Request(url, postdata, self.__headers)
        handle = None
        while handle is None:
            try:
                handle = urllib2.urlopen(req)
            except urllib2.URLError:
                print("Error while fetching %s\nTrying again in 30 seconds..." % url);
                time.sleep(30);
                handle = None
        self.__cookie_jar.save(ignore_discard=True, ignore_expires=True)
        return handle
Exemplo n.º 11
0
	def ClearState(self,name,verbose=True):
		import os
		if os.path.exists(self.StateName(name)):
			if verbose:
				print >>sys.stderr, "Warning: Saved state %s exists. Overwriting."%name
			log("removing state %s"%name)
			os.remove(self.StateName(name))
Exemplo n.º 12
0
def throughAllCombinationsRecursive(elementsToCombineList, byAmount):
    reList = []

    if byAmount == 0:
        return []

    for i in range(len(elementsToCombineList)):
        item = elementsToCombineList[i]

        elementsToCombineListWithoutItemS = delElementsLessOrEqualThanValue(
            elementsToCombineList, item)

        if len(elementsToCombineListWithoutItemS
               ) < byAmount - 1 and byAmount > 1:

            return reList

        recursiveList = throughAllCombinationsRecursive(
            elementsToCombineListWithoutItemS, byAmount - 1)
        log("recursiveList" + str(recursiveList))

        if len(recursiveList) == 0:
            reList += [[item]]

        for j in range(len(recursiveList)):
            recursiveItem = recursiveList[j]
            reList += [[item] + recursiveItem]

    return reList
Exemplo n.º 13
0
def addToAllBijections(basinIndex1, basinIndex2, basinLevelBijectionsList):

    if basinLevelBijectionsList == []:
        basinLevelBijectionsList.append({basinIndex1: basinIndex2})
        return

    for bijectionDict in basinLevelBijectionsList:
        if basinIndex1 in bijectionDict:
            log("Error, bijection for the current value has already been established")
        bijectionDict[basinIndex1] = basinIndex2
Exemplo n.º 14
0
def addToAllBijections(basinIndex1, basinIndex2, basinLevelBijectionsList):

    if basinLevelBijectionsList == []:
        basinLevelBijectionsList.append({basinIndex1: basinIndex2})
        return

    for bijectionDict in basinLevelBijectionsList:
        if basinIndex1 in bijectionDict:
            log("Error, bijection for the current value has already been established"
                )
        bijectionDict[basinIndex1] = basinIndex2
Exemplo n.º 15
0
    def validateStream(self, stream=None):
        '''checks if stream is valid if theres no agument then it checks 
        self.__stream'''
        if stream is None:
            stream = self.__stream

        log('Validationg stream %s' % stream)
        if len(self.allstreams) < 5:
            self.allstreams = self.getStreams()
        if stream not in self.allstreams:
            log('stream %s invalid' % stream)
            raise InvalidStream
Exemplo n.º 16
0
    def validateStream(self, stream=None):
        '''checks if stream is valid if theres no agument then it checks 
        self.__stream'''
        if stream is None: 
            stream = self.__stream

	log('Validationg stream %s' % stream)
        if len(self.allstreams) < 5:
            self.allstreams = self.getStreams()
        if stream not in self.allstreams:
            log('stream %s invalid' % stream)
            raise InvalidStream
Exemplo n.º 17
0
    def __init__(self, parent_window):
        self.parent_window = parent_window
        self.imageProcessor = None
        self.input_img = Image.open("etc/open.png")
        self.output_img = self.process_image(self.input_img)
        self.imagelabel_output_img = None
        self.imagelabel_input_img = None
        self.letter_name = None
        self.message = StringVar("")
        self.name_entry = Entry
        self.data = dict()

        log("launching learn controller")
Exemplo n.º 18
0
def unfollow_all(api, handleUser):
    fileName = time.strftime("%Y-%m-%d_%H_%M_%S")
    fileName = "Unfollow_Log_" + fileName + ".txt"
    un = open(fileName, "w", 1)
    un.write("UNFOLLOW LOG\n")
    print("Downloading List Of Followers...")
    me = api.me()
    myName = me.screen_name
    followers = api.followers_ids(myName)
    friends = api.friends_ids(myName)

    i = 0
    minu = 5
    for f in friends:
        if f not in followers:
            i = i + 1
            if i != 50:
                try:
                    api.destroy_friendship(f)
                    log("Unfollowing " + api.get_user(f).screen_name, un)
                    time.sleep(3)
                except Exception:
                    log("TweepError Raised. Stalling System.", un)
                    countdown(15, 0)
                    continue
            else:
                i = 0
                log("Stalling system for a few minutes", un)
                countdown(15, 0)
    log("All users unfollowed!", un)
    un.close()
Exemplo n.º 19
0
    def play(self, url, stream):
        """Plays the given url

        url: url to play using external command"""

        if self.options.record:
            stream = stream.replace(' ','') + '_'
            now = datetime.datetime.now()
            filename = stream + now.strftime("%Y-%m-%d_%H-%M-%S") + '.wav'
            mpc = "%s '%s'" % (self.command + filename, url)
        else:
            mpc = "%s '%s'" % (self.command, url)
        log('mpc = %s' % mpc)
        (self.processIn, self.processOut) = pipeopen(mpc)
        fcntl.fcntl(self.processOut, fcntl.F_SETFL, os.O_NONBLOCK)
Exemplo n.º 20
0
	def UserClearState(self,name):
		import os,sys,re
		if os.path.exists(self.StateName(name)):
			force = ("-f" in sys.argv or "--force" in sys.argv)
			if not force:
				print >>sys.stderr, "Saved state %s exists. Do you want to overwrite? "  % name,
				user=raw_input()
				log("Question:","Saved state %s exists. Do you want to overwrite? "  % name,"answer:",user)
				if re.match("""y(es?)?""",user):
					print >>sys.stderr," --> Overwriting."
					return self.ClearState(name,False)
				else:
					raise self.StateExists(name)
			else:
				self.ClearState(name)
Exemplo n.º 21
0
    def setStreamByLongName(self, longName):
        '''Sets the currently playing stream to the stream refered to by
        longname'''

	log('Set Stream to %s' % longName)
        #print 'setStreamByLongName:',longName #DEBUG
        if len(self.allstreams) < 5:
            self.allstreams = self.getStreams()
            
        for stream in self.allstreams:
          if stream['longName'].lower() == longName.lower():
            #print 'setStreamByLongName, stream:',stream #DEBUG
            self.__stream = stream
            log('Stream set to %s' % stream)
            return
        raise InvalidStream
Exemplo n.º 22
0
    def setStreamByLongName(self, longName):
        '''Sets the currently playing stream to the stream refered to by
        longname'''

        log('Setting Stream to %s' % longName)
        #print 'setStreamByLongName:',longName #DEBUG
        if len(self.allstreams) < 5:
            self.allstreams = self.getStreams()

        for stream in self.allstreams:
            if stream['longName'].lower().strip() == longName.lower():
                #print 'setStreamByLongName, stream:',stream #DEBUG
                self.__stream = stream
                log('Stream set to %s' % stream)
                return
        raise InvalidStream
Exemplo n.º 23
0
def isIsomorphic(graph1, graph2):
    # cycle/branches level isomporphism will be launched inside
    basinLevelBijectionsList = hasBasinLevelBijections(graph1, graph2)
    if basinLevelBijectionsList == []:
        log("basins do not match")
        return False

    for basinLevelBijection in basinLevelBijectionsList:
        isomporphismEstablished = True
        for proImageBasin in basinLevelBijection:
            imageBasin = basinLevelBijection[proImageBasin]
            if not isIsomorphicBasins(proImageBasin, imageBasin, graph1, graph2):
                isomporphismEstablished = False
                break
        if isomporphismEstablished:
            return True
Exemplo n.º 24
0
	def GetAllNames(self):
		import os, glob, re
		log("Session Dir",os.listdir(self.session_dir))
		
		session_files = glob.glob(self.SessionName("*",nocheck=True))
		session_match = re.compile(os.sep+os.path.basename(self.SessionName("(?P<name>.*?)",nocheck=True))+"$")
		session_names = []
		for filename in session_files:
			session_names.append(session_match.search(filename).group("name"))
		
		state_files = glob.glob(self.StateName("*",nocheck=True))
		state_match = re.compile(os.sep+os.path.basename(self.StateName("(?P<name>.*)",nocheck=True))+"$")
		state_names = []
		for filename in state_files:
			state_names.append(state_match.search(filename).group("name"))
		return session_names, state_names
Exemplo n.º 25
0
def isIsomorphic(graph1, graph2):
    #cycle/branches level isomporphism will be launched inside
    basinLevelBijectionsList = hasBasinLevelBijections(graph1, graph2)
    if basinLevelBijectionsList == []:
        log("basins do not match")
        return False

    for basinLevelBijection in basinLevelBijectionsList:
        isomporphismEstablished = True
        for proImageBasin in basinLevelBijection:
            imageBasin = basinLevelBijection[proImageBasin]
            if not isIsomorphicBasins(proImageBasin, imageBasin, graph1,
                                      graph2):
                isomporphismEstablished = False
                break
        if isomporphismEstablished:
            return True
Exemplo n.º 26
0
    def tryGetStreams(self):
        """ Returns a list of streams avalible, if it 
         failes with AuthError, try
          Sirius.auth() first, then try again
          Or use getStreams()
      """

        allstreams = []
        url = 'http://www.sirius.com/player/listen/play.action?resizeActivity=minimize'
        hd = self.__getURL(url)
        data = hd.read()
        hd.close()
        if data.find('name="selectedStream"') == -1:  #IF NOT FOUND
            post = {'activity': 'minimize', 'token': self.token}
            hd = self.__getURL(url, post)
            data = hd.read()
            hd.close()
        if data.find('unable to log you in') <> -1:  #IF FOUND
            logfile('login-error.html', data)  #DEBUG 0
            print 'LoginError, expired account?' #DEBUG 0
            raise LoginError
        if data.find('Sorry_Pg3.gif') <> -1:  #IF FOUND
            print '\nLoginError: to many logins today?'
            logfile('login-error.html', data)  #DEBUG 0
            raise LoginError
        data = self.sanitize(data)
        soup = BeautifulSoup(data)
        for catstrm in soup.findAll('option'):
            if catstrm['value'].find('|') <> -1:  # IF FOUND
                chunks = catstrm['value'].split('|')
                stream = {
                    'channelKey': chunks[2],
                    'genreKey':  chunks[1],
                    'categoryKey': chunks[0],
                    'selectedStream': catstrm['value'],
                    'longName': catstrm.contents[0].split(';')[-1].lower()
                    }
                allstreams.append(stream)
        if len(allstreams) < 5:
            log("ERROR getting streams, see streams-DEBUG.html") # DEBUG
            logfile('streams-DEBUG.html',data)  # DEBUG
            raise AuthError
        else:
            self.allstreams = allstreams
            return allstreams
Exemplo n.º 27
0
    def getNowPlaying(self):
        '''return a dictionary for current song/artist per channel'''
        nowplaying = {}
        url = 'http://www.siriusxm.com/padData/pad_provider.jsp?all_channels=y'
        try:
            sirius_xml = parse(urllib.urlopen(url))
        except Exception:
            log("ERROR getting now-playing list: %s" % url)
            return "FAILURE"

        for channels in sirius_xml.getElementsByTagName('event'):
            channel = channels.getElementsByTagName('channelname')[0].firstChild.data
            song = channels.getElementsByTagName('songtitle')[0].firstChild.data
            artist = channels.getElementsByTagName('artist')[0].firstChild.data
            nowplaying[str(channel).strip().lower()] = {'artist': artist, 'song': song}
        sirius_xml.unlink()

        return nowplaying
Exemplo n.º 28
0
	def GetStateOrSessionDiff(self,name):
		import os
		log("Session Dir",os.listdir(self.session_dir))
		"""If an existing saved state by this name is found, return that,if an open session by this name is found, construct the difference to the present."""
		session_file_name = self.SessionName(name)
		state_file_name = self.StateName(name)
		try:
			diff = self.GetState(name)
		except:
			log()
			log("session wans't available. making it.")
			try:
				diff = self.ConstructDifference(self.GetSession(name), self.shell.environment)
			except:
				log()
				log("that didn't work either")
				raise self.UnknownName(name)
		return diff
Exemplo n.º 29
0
	def undo(self,name):
		"""remove the changes associated with a state."""
		import os
		if not os.path.exists(self.StateName(name)) and os.path.exists(self.SessionName(name)):
			force = ("-f" in sys.argv or "--force" in sys.argv)
			if force:
				self.ClearState(name)
				self.CloseSession(name)
			else:
				print >>sys.stderr, "Session %s is open. Do you want to close it? "  % name,
				user=raw_input()
				log("Question:","Session %s is open. Do you want to close it? "  % name,"answer:",user)
				if re.match("""y(es?)?""",user):
					print >>sys.stderr," --> Closing."
					self.UserClearState(name)
					self.CloseSession(name)
				else:
					print >>sys.stderr," --> Using open session."
		
		return self.redo(name,Reverse=True) 
Exemplo n.º 30
0
    def play(self, url, stream):
        """Plays the given url

        url: url to play using external command"""

        if self.playing():
            print "Already playing!"
            return

        print "Starting mplayer..."
        if self.options.record:
	    if self.options.output:
		filename = self.options.output
	    else:
            	filename ="999990.wav"
            mpc = "%s '%s'" % (self.command + filename, url)
        else:
            mpc = "%s '%s'" % (self.command, url)
        log('mpc = %s' % mpc)
        self.pipeopen(mpc)
Exemplo n.º 31
0
    def auth(self):
        """run auth to setup all the cookies you need to get the stream
          self.__captchaCallback should be set to 
          a fuction that accepts a file name as an
          its only argument and returns text found in that image
          (as read by a huMan)

          if no function is passed it will Guess (and fail?)

        """
        #Am i authed, should be its own function really
        data = self.__getURL(
          'http://www.sirius.com/player/listen/play.action').read()
        if 'NOW PLAYING TITLE:START' in data:
          return True

        session = self.findSessionID()
        if not session:
          self.__getURL(
            'http://www.sirius.com/player/home/siriushome.action').read()
          session = self.findSessionID()
        if not session:
          raise LoginError

        authurl = 'http://www.sirius.com/player/login/siriuslogin.action;jsessionid=%s' % session

        postdict = { 'userName': self.account.username,
                     '__checkbox_remember': 'true',
                     'password': self.account.password,
                     'captchaEnabled': 'true',
                     'timeNow': 'null',
                     'captcha_response': 'rc3k',
                   }

        post = urllib.urlencode(postdict) + '&captchaID=%3E%3A0%08g%60n'
        data = self.__getURL(authurl, poststring=post).read()
        if '<title>SIRIUS Player' in data:
          log("got valid page at: " + authurl + "\n")
          return True
        else:
          raise LoginError
Exemplo n.º 32
0
    def play(self, stream):
        """Plays the given stream

        stream: the station name"""
        try:
            log('Play %s' % stream)
            self.sirius.setStreamByLongName(stream)
        except InvalidStream:
            print "Invalid station name. Type 'list' to see available station names"
            return
        else:
            if self.options.record:
                print "Recording %s. Please use Ctrl+C to stop." % stream
            else:
                print "Now playing %s. Please use Ctrl+C to stop." % stream

        while True:  #playing loop
            if not self.player.playing():
                url = self.sirius.getAsxURL()
                self.player.play(url, stream)

            playing = self.sirius.nowPlaying()
            if playing['new']:
                if not self.options.quiet:
                    print time.strftime('%H:%M') + ' - ' + playing[
                        'longName'] + ": " + playing['playing']
                if self.notification:
                    import pynotify
                    if pynotify.init("Pyxis"):
                        icon = os.path.dirname(
                            __file__) + '/data/dog_white_outline.svg'
                        n = pynotify.Notification(
                            "Sirius",
                            playing['longName'] + ": " + playing['playing'],
                            icon)
                        n.show()
            try:
                time.sleep(30)
            except KeyboardInterrupt:
                break
Exemplo n.º 33
0
    def play(self, url, stream):
        """Plays the given url

        url: url to play using external command"""

        if self.playing():
            print "Already playing!"
            return

        log("Starting mplayer...")
        if self.options.record:
            if self.options.output:
                filename = self.options.output
            else:
                stream = stream.replace(' ', '') + '_'
                now = datetime.datetime.now()
                filename = stream + now.strftime("%Y-%m-%d_%H-%M-%S") + '.wav'

            mpc = "%s '%s'" % (self.command + filename, url)
        else:
            mpc = "%s '%s'" % (self.command, url)
        log('mpc = %s' % mpc)
        self.pipeopen(mpc)
Exemplo n.º 34
0
    def getNowPlaying(self):
        '''return a dictionary for current song/artist per channel'''
        nowplaying = {}
        url = 'http://www.siriusxm.com/padData/pad_provider.jsp?all_channels=y'
        try:
            sirius_xml = parse(urllib.urlopen(url))
        except Exception:
            log("ERROR getting now-playing list: %s" % url)
            return "FAILURE"

        for channels in sirius_xml.getElementsByTagName('event'):
            channel = channels.getElementsByTagName(
                'channelname')[0].firstChild.data
            song = channels.getElementsByTagName(
                'songtitle')[0].firstChild.data
            artist = channels.getElementsByTagName('artist')[0].firstChild.data
            nowplaying[str(channel).strip().lower()] = {
                'artist': artist,
                'song': song
            }
        sirius_xml.unlink()

        return nowplaying
Exemplo n.º 35
0
    def __getURL(self, url, postdict=None, poststring=None):
        """ get a url, the second arg could be dictionary of 
         options for a post 
         If there is no second option use get
         This will use the cookies and tokens for this instance 
         of Sirius
         returns a file handle
      """

        if postdict:
            postdata = urllib.urlencode(postdict)
        else:
            postdata = None
        if poststring:
            postdata = poststring

        log("POST=%s" % postdata)#DEBUG
        log("url=%s" % url) #DEBUG

        req = urllib2.Request(url, postdata, self.__headers)
        handle = urllib2.urlopen(req)
        self.__cookie_jar.save(ignore_discard=True, ignore_expires=True)
        return handle
Exemplo n.º 36
0
    def play(self, url, stream):
        """Plays the given url

        url: url to play using external command"""

        if self.playing():
            print "Already playing!"
            return

        log("Starting mplayer...")
        if self.options.record:
            if self.options.output:
                filename = self.options.output
            else:
                stream = stream.replace(' ','') + '_'
                now = datetime.datetime.now()
                filename = stream + now.strftime("%Y-%m-%d_%H-%M-%S") + '.wav'
            
            mpc = "%s '%s'" % (self.command + filename, url)
        else:
            mpc = "%s '%s'" % (self.command, url)
        log('mpc = %s' % mpc)
        self.pipeopen(mpc)
Exemplo n.º 37
0
	def GetSession(self,name):
		import os
		log("Session Dir",os.listdir(self.session_dir))
		try:
			import pickle
			return pickle.load(open(self.SessionName(name)))
		except:
			log()
			log("raising unknown session now.")
			raise self.UnknownSession(name)
Exemplo n.º 38
0
    def auth(self):
        """run auth to setup all the cookies you need to get the stream
          self.__captchaCallback should be set to 
          a fuction that accepts a file name as an
          its only argument and returns text found in that image
          (as read by a huMan)

          if no function is passed it will Guess (and fail?)

        """
        log('Authenticating ...')
        #Am i authed, should be its own function really
        data = self.sirius.getURL(
            'http://www.sirius.com/player/listen/play.action').read()
        if 'NOW PLAYING TITLE:START' in data:
            log('Authenticated')
            return True

        session = self.sirius.findSessionID()
        log('SESSIONID= %s' % session)
        if not session:
            getURL(
                'http://www.sirius.com/player/home/siriushome.action').read()
            session = self.sirius.findSessionID()
        if not session:
            raise LoginError

        authurl = 'http://www.sirius.com/player/login/siriuslogin.action;jsessionid=%s' % session

        postdict = {
            'userName': self.account.username,
            '__checkbox_remember': 'true',
            'password': self.account.password,
            'captchaEnabled': 'true',
            'timeNow': 'null',
            'captcha_response': 'rc3k',
        }

        post = urllib.urlencode(postdict) + '&captchaID=%3E%3A0%08g%60n'
        data = self.sirius.getURL(authurl, poststring=post).read()
        if '<title>SIRIUS Player' in data:
            log("got valid page at: " + authurl + "\n")
            return True
        else:
            raise LoginError
Exemplo n.º 39
0
    def auth(self):
        """run auth to setup all the cookies you need to get the stream
          self.__captchaCallback should be set to 
          a fuction that accepts a file name as an
          its only argument and returns text found in that image
          (as read by a huMan)

          if no function is passed it will Guess (and fail?)

        """
        log("Authenticating ...")
        # Am i authed, should be its own function really
        data = self.sirius.getURL("http://www.sirius.com/player/listen/play.action").read()
        if "NOW PLAYING TITLE:START" in data:
            log("Authenticated")
            return True

        session = self.sirius.findSessionID()
        log("SESSIONID= %s" % session)
        if not session:
            getURL("http://www.sirius.com/player/home/siriushome.action").read()
            session = self.sirius.findSessionID()
        if not session:
            raise LoginError

        authurl = "http://www.sirius.com/player/login/siriuslogin.action;jsessionid=%s" % session

        postdict = {
            "userName": self.account.username,
            "__checkbox_remember": "true",
            "password": self.account.password,
            "captchaEnabled": "true",
            "timeNow": "null",
            "captcha_response": "rc3k",
        }

        post = urllib.urlencode(postdict) + "&captchaID=%3E%3A0%08g%60n"
        data = self.sirius.getURL(authurl, poststring=post).read()
        if "<title>SIRIUS Player" in data:
            log("got valid page at: " + authurl + "\n")
            return True
        else:
            raise LoginError
Exemplo n.º 40
0
	def WriteState(self,name,state):
		state_name = self.StateName(name)
		import os, sys, pickle
		if os.path.exists(state_name):
			print >>sys.stderr, "Warning: Recording '%s' exists. Overwriting." % name
			log("overwriting state %s"%name,state_name)
		try:
			state_file = open(state_name,"w")
			pickle.dump(state,state_file)
			state_file.close()
		except:
			log()
			raise self.WriteError(state_name)
		log("written",state_name)
Exemplo n.º 41
0
	def WriteSession(self,name,session):
		session_name = self.SessionName(name)
		import os, sys, pickle
		if os.path.exists(session_name):
			print >>sys.stderr, "Warning: Open session '%s' exists. Overwriting." % name
			log("overwriting session %s"%name,session_name)
		try:
			session_file = open(session_name,"w")
			pickle.dump(session,session_file)
			session_file.close()
		except:
			log()
			raise self.WriteError(session_name)
		log("written",session_name)
Exemplo n.º 42
0
 def tryGetStreams(self):
     """ Returns a list of streams avalible, if it 
      failes with AuthError, try
       Sirius.auth() first, then try again
       Or use getStreams()
   """
     log('Getting streams ...')
     allstreams = []
     url = 'http://www.sirius.com/player/listen/play.action?resizeActivity=minimize'
     hd = self.sirius.getURL(url)
     data = hd.read()
     hd.close()
     if data.find('name="selectedStream"') == -1:  #IF NOT FOUND
         post = {'activity': 'minimize', 'token': self.token}
         hd = self.sirius.getURL(url, post)
         data = hd.read()
         hd.close()
     if data.find('unable to log you in') <> -1:  #IF FOUND
         logfile('login-error.html', data)  #DEBUG 0
         print 'LoginError, expired account?'  #DEBUG 0
         raise LoginError
     if data.find('Sorry_Pg3.gif') <> -1:  #IF FOUND
         print '\nLoginError: to many logins today?'
         logfile('login-error.html', data)  #DEBUG 0
         raise LoginError
     data = self.sirius.sanitize(data)
     soup = BeautifulSoup(data)
     for catstrm in soup.findAll('option'):
         if catstrm['value'].find('|') <> -1:  # IF FOUND
             chunks = catstrm['value'].split('|')
             stream = {
                 'channelKey': chunks[2],
                 'genreKey': chunks[1],
                 'categoryKey': chunks[0],
                 'selectedStream': catstrm['value'],
                 'longName': catstrm.contents[0].split(';')[-1].lower()
             }
             allstreams.append(stream)
     if len(allstreams) < 5:
         log("ERROR getting streams, see streams-DEBUG.html")  # DEBUG
         logfile('streams-DEBUG.html', data)  # DEBUG
         raise AuthError
     else:
         logfile('streams.log', repr(allstreams))
         log('Streams retrieved, see streams.log')
         return allstreams
Exemplo n.º 43
0
 def tryGetStreams(self):
     """ Returns a list of streams avalible, if it 
      failes with AuthError, try
       Sirius.auth() first, then try again
       Or use getStreams()
   """
     log("Getting streams ...")
     allstreams = []
     url = "http://www.sirius.com/player/listen/play.action?resizeActivity=minimize"
     hd = self.sirius.getURL(url)
     data = hd.read()
     hd.close()
     if data.find('name="selectedStream"') == -1:  # IF NOT FOUND
         post = {"activity": "minimize", "token": self.token}
         hd = self.sirius.getURL(url, post)
         data = hd.read()
         hd.close()
     if data.find("unable to log you in") <> -1:  # IF FOUND
         logfile("login-error.html", data)  # DEBUG 0
         print "LoginError, expired account?"  # DEBUG 0
         raise LoginError
     if data.find("Sorry_Pg3.gif") <> -1:  # IF FOUND
         print "\nLoginError: to many logins today?"
         logfile("login-error.html", data)  # DEBUG 0
         raise LoginError
     data = self.sirius.sanitize(data)
     soup = BeautifulSoup(data)
     for catstrm in soup.findAll("option"):
         if catstrm["value"].find("|") <> -1:  # IF FOUND
             chunks = catstrm["value"].split("|")
             stream = {
                 "channelKey": chunks[2],
                 "genreKey": chunks[1],
                 "categoryKey": chunks[0],
                 "selectedStream": catstrm["value"],
                 "longName": catstrm.contents[0].split(";")[-1].lower(),
             }
             allstreams.append(stream)
     if len(allstreams) < 5:
         log("ERROR getting streams, see streams-DEBUG.html")  # DEBUG
         logfile("streams-DEBUG.html", data)  # DEBUG
         raise AuthError
     else:
         logfile("streams.log", repr(allstreams))
         log("Streams retrieved, see streams.log")
         return allstreams
Exemplo n.º 44
0
def createUser():
    global uname, pword, sex, bdaymonth, bdayday, bdayyear, amountOfTries, waitTime, successUrl, proxyURL, proxyEnabled
    executeableDriver = 'chromedriver.exe'
    #executeableDriver = 'phantomjs.exe'

    chromeOptions = Options()
    #chromeOptions.add_argument("--headless")
    chromeOptions.add_argument("--proxy-server=" + proxyURL)
    '''
    if(proxyEnabled):
        service_args = [
        '--proxy={}'.format(proxyURL),
        '--proxy-type=socks5',
        ]
    else:
        service_args = []
        '''

    browser = webdriver.Chrome(executeableDriver, chrome_options=chromeOptions)
    #browser = webdriver.PhantomJS(executeableDriver)#,service_args=service_args
    browser.get('https://www.roblox.com')

    print("{0}:{1}:{2}:{3}/{4}-{5}".format(uname, pword, sex, bdaymonth,
                                           bdayday, bdayyear),
          end="",
          flush=True)

    #Assigns different ids from the homepage variable names.
    usernameId = browser.find_element_by_id("signup-username")
    passwordId = browser.find_element_by_id("signup-password")
    password2Id = browser.find_element_by_id("signup-password-confirm")
    gender = browser.find_element_by_id(sex + "Button")
    month = browser.find_element_by_id("MonthDropdown")
    day = browser.find_element_by_id("DayDropdown")
    year = browser.find_element_by_id("YearDropdown")

    #BDAY: Sets the birthdate.
    select = Select(month)
    select.select_by_value(bdaymonth)
    select = Select(day)
    select.select_by_value(bdayday)
    select = Select(year)
    select.select_by_value(bdayyear)

    #Uses the ids assigned before, clicks and types in boxes.
    usernameId.send_keys(uname)
    passwordId.send_keys(pword)
    password2Id.send_keys(pword)
    gender.click()
    browser.find_element_by_xpath('//*[@id="agreeTermsPrivacyLabel"]').click()
    browser.find_element_by_xpath('//*[@id="signup-button"]').click()

    #Checks weather the registration was successful.
    CurrURL = browser.current_url
    log(CurrURL)
    tries = 0
    while not successUrl in CurrURL:
        if (tries < amountOfTries):
            CurrURL = browser.current_url
            log("Trying again, Tries: {0}/{1}; URL: {2}".format(
                tries, amountOfTries, CurrURL))
            snooze(waitTime)
            tries += 1
        else:
            break
    #browser.save_screenshot('screen.png')
    if (successUrl in CurrURL):
        #Created account successfully.
        print("...Account was created.")
        try:
            makedirs(join(outputFolder, "cookies"))
        except:
            pass
        if not (proxyEnabled):
            open(join(outputFolder, uname),
                 'w').write("{0}:{1}".format(uname, pword))
        else:
            open(join(outputFolder, uname),
                 'w').write("{0}:{1}.{2}".format(uname, pword, proxyURL))
        pickle.dump(browser.get_cookies(),
                    open(join(outputFolder, "cookies", uname + ".pkl"), "wb"))
    else:
        #Failed creating account.
        print("...Account could not be created. Landing page: {}".format(
            CurrURL))
    browser.save_screenshot('screenshot {}.png'.format(uname))
    browser.quit()
Exemplo n.º 45
0
def hasBasinLevelBijections(graph1, graph2):
    basinLevelBijectionsList = []
    basinSize_BasinsList_Dict1 = analyseGraphBasins(graph1)
    basinSize_BasinsList_Dict2 = analyseGraphBasins(graph2)

    for basinSize in basinSize_BasinsList_Dict1:

        if not basinSize in basinSize_BasinsList_Dict2:
            log("basin sizes do not match")  # N_04_K_02/34027, 34028 to trigger
            return []

        equalBasinSizeBasinsList1 = basinSize_BasinsList_Dict1[basinSize]
        equalBasinSizeBasinsList2 = basinSize_BasinsList_Dict2[basinSize]

        if len(equalBasinSizeBasinsList1) != len(equalBasinSizeBasinsList2):

            log("amounts of basins of certain size do not match")
            return []

        if len(equalBasinSizeBasinsList1) == 1:
            log("simple bijection established")
            addToAllBijections(equalBasinSizeBasinsList1[0], equalBasinSizeBasinsList2[0], basinLevelBijectionsList)

        else:

            attractorSize_BasinList_Dict1 = analyseGraphBasinAttractors(graph1, equalBasinSizeBasinsList1)
            attractorSize_BasinList_Dict2 = analyseGraphBasinAttractors(graph2, equalBasinSizeBasinsList2)

            for attractorSize in attractorSize_BasinList_Dict1:

                if not attractorSize in attractorSize_BasinList_Dict2:
                    log("attractor of certain size is absent")
                    return []

                equalAttractorSizeBasinsList1 = attractorSize_BasinList_Dict1[attractorSize]
                equalAttractorSizeBasinsList2 = attractorSize_BasinList_Dict2[attractorSize]

                if len(attractorSize_BasinList_Dict1[attractorSize]) != len(
                    attractorSize_BasinList_Dict2[attractorSize]
                ):
                    log("attractor sizes do not match")
                    return []

                if len(attractorSize_BasinList_Dict1[attractorSize]) == 1:
                    log("simple bijection established")
                    addToAllBijections(
                        attractorSize_BasinList_Dict1[attractorSize][0],
                        attractorSize_BasinList_Dict1[attractorSize][0],
                        basinLevelBijectionsList,
                    )
                else:
                    log("brute force is used to establish bijections")
                    # permutations are the ways to establish basin level bijections between equal sized and "attractor"ed basins
                    permutationsList = ThroughAllAutomata.throughAllPermutations(
                        len(attractorSize_BasinList_Dict1[attractorSize])
                    )

                    copiedBijectionsList = copy.deepcopy(basinLevelBijectionsList)

                    basinLevelBijectionsList = []

                    for permutation in permutationsList:
                        iFrom = 0
                        currentBijectionsList = copy.deepcopy(copiedBijectionsList)

                        for iTo in permutation:

                            addToAllBijections(
                                equalAttractorSizeBasinsList1[iFrom],
                                equalAttractorSizeBasinsList2[iTo],
                                currentBijectionsList,
                            )
                            # print iFrom, iTo, currentBijectionsList
                            iFrom += 1
                        basinLevelBijectionsList += currentBijectionsList
    log("All Fits")  # N_04_K_02/34027, N_04_K_02/34025 to trigger
    return basinLevelBijectionsList
Exemplo n.º 46
0
def hasBasinLevelBijections(graph1, graph2):
    basinLevelBijectionsList = []
    basinSize_BasinsList_Dict1 = analyseGraphBasins(graph1)
    basinSize_BasinsList_Dict2 = analyseGraphBasins(graph2)

    for basinSize in basinSize_BasinsList_Dict1:

        if not basinSize in basinSize_BasinsList_Dict2:
            log("basin sizes do not match"
                )  # N_04_K_02/34027, 34028 to trigger
            return []

        equalBasinSizeBasinsList1 = basinSize_BasinsList_Dict1[basinSize]
        equalBasinSizeBasinsList2 = basinSize_BasinsList_Dict2[basinSize]

        if len(equalBasinSizeBasinsList1) != len(equalBasinSizeBasinsList2):

            log("amounts of basins of certain size do not match")
            return []

        if len(equalBasinSizeBasinsList1) == 1:
            log("simple bijection established")
            addToAllBijections(equalBasinSizeBasinsList1[0],
                               equalBasinSizeBasinsList2[0],
                               basinLevelBijectionsList)

        else:

            attractorSize_BasinList_Dict1 = analyseGraphBasinAttractors(
                graph1, equalBasinSizeBasinsList1)
            attractorSize_BasinList_Dict2 = analyseGraphBasinAttractors(
                graph2, equalBasinSizeBasinsList2)

            for attractorSize in attractorSize_BasinList_Dict1:

                if not attractorSize in attractorSize_BasinList_Dict2:
                    log("attractor of certain size is absent")
                    return []

                equalAttractorSizeBasinsList1 = attractorSize_BasinList_Dict1[
                    attractorSize]
                equalAttractorSizeBasinsList2 = attractorSize_BasinList_Dict2[
                    attractorSize]

                if len(attractorSize_BasinList_Dict1[attractorSize]) != len(
                        attractorSize_BasinList_Dict2[attractorSize]):
                    log("attractor sizes do not match")
                    return []

                if len(attractorSize_BasinList_Dict1[attractorSize]) == 1:
                    log("simple bijection established")
                    addToAllBijections(
                        attractorSize_BasinList_Dict1[attractorSize][0],
                        attractorSize_BasinList_Dict1[attractorSize][0],
                        basinLevelBijectionsList)
                else:
                    log("brute force is used to establish bijections")
                    #permutations are the ways to establish basin level bijections between equal sized and "attractor"ed basins
                    permutationsList = ThroughAllAutomata.throughAllPermutations(
                        len(attractorSize_BasinList_Dict1[attractorSize]))

                    copiedBijectionsList = copy.deepcopy(
                        basinLevelBijectionsList)

                    basinLevelBijectionsList = []

                    for permutation in permutationsList:
                        iFrom = 0
                        currentBijectionsList = copy.deepcopy(
                            copiedBijectionsList)

                        for iTo in permutation:

                            addToAllBijections(
                                equalAttractorSizeBasinsList1[iFrom],
                                equalAttractorSizeBasinsList2[iTo],
                                currentBijectionsList)
                            #print iFrom, iTo, currentBijectionsList
                            iFrom += 1
                        basinLevelBijectionsList += currentBijectionsList
    log("All Fits")  #N_04_K_02/34027, N_04_K_02/34025 to trigger
    return basinLevelBijectionsList
Exemplo n.º 47
0
select.select_by_value(bdaymonth)
select = Select(day)
select.select_by_value(bdayday)
select = Select(year)
select.select_by_value(bdayyear)

username.send_keys(uname)
password.send_keys(pword)
password2.send_keys(pword)
gender.click()
browser.find_element_by_xpath('//*[@id="agreeTermsPrivacyLabel"]').click(
)  #//*[@id="agreeTermsPrivacyLabel"]
browser.find_element_by_xpath('//*[@id="signup-button"]').click()

CurrURL = browser.current_url
log(CurrURL)
tries = 0
while not successUrl in CurrURL:
    if (tries < amountOfTries):
        CurrURL = browser.current_url
        log("Trying again, Tries: {0}/{1}; URL: {2}".format(
            tries, amountOfTries, CurrURL))
        snooze(waitTime)
        tries += 1
    else:
        break
browser.save_screenshot('screen.png')
if (successUrl in CurrURL):
    #Created account successfully.
    print("...Account was created.")
else:
Exemplo n.º 48
0
 def save_data(self):
     self.letter_name = self.name_entry.get()
     self.data[self.letter_name] = self.imageProcessor.trimmed_image
     self.message = "added " + self.letter_name
     log(self.message)
Exemplo n.º 49
0
def initial_function(api, handleUser):
    fileName = time.strftime("%Y-%m-%d_%H_%M_%S")
    fileName = "FollowLog_" + fileName + ".txt"
    f = open(fileName, "w", 1)

    f.write("LOG\n")

    # scans for my ID, and ensures to NOT FOLLOW said ID
    me = api.me()
    myid = me.id

    print("Scanning users...")
    i = 1
    modulur = 0
    ids = []
    for page in tweepy.Cursor(api.followers_ids,
                              screen_name=handleUser).pages():
        ids.extend(page)

    for x in ids:
        modulur = i % 100
        if modulur == 0:
            log("Integer hit 100x. Stalling System.", f)
            countdown(15, 0)
        user = api.get_user(x)
        if user.id != myid:
            if user.friends_count < 500:
                api.destroy_friendship(user.screen_name)
                try:
                    user.follow()
                    log("Followed : " + user.screen_name, f)

                except Exception:
                    log("TweepError Raised. Stalling System.", f)
                    countdown(15, 0)
                    continue
            else:
                log("Skipped - Over Limit : " + user.screen_name + "", f)

        else:
            log("I was skipped!", f)

        i = i + 1
    log("All users followed!", f)
    f.close()