Ejemplo n.º 1
0
  def GET(self):
    
    rdio, currentUser, user_id = get_rdio_and_current_user()
    
    if rdio and currentUser:
      if user_id in config.ADMIN_USERS:
        input = get_input()
        
        if 'button' in input.keys():
          action = input['button']
          db = get_db()
          
          if action == 'doitnow_go_on_killme':
            if user_id in config.ADMIN_USERS:
              db.delete(USER_TABLE, where="rdio_user_id=%i" % user_id)
            raise web.seeother('/')

          elif action == 'clear_preferences':
            if user_id in config.ADMIN_USERS:
              db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, prefs=BSONPostgresSerializer.from_dict({}))
          
            raise web.seeother('/admin')
        
        else:
          admin=get_admin_content()
          return render.admin(env_message=get_environment_message(), admin=admin)
      
    raise web.seeother('/')
Ejemplo n.º 2
0
  def GET(self):
    
    rdio, current_user, user_id = get_rdio_and_current_user()
    
    if rdio and current_user:
      if user_id in config.ADMIN_USERS:
        form_input = get_input()
        
        if 'button' in form_input.keys():
          action = form_input['button']
          db = get_db()
          
          if action == 'doitnow_go_on_killme':
            if user_id in config.ADMIN_USERS:
              db.delete(USER_TABLE, where="rdio_user_id=%i" % user_id)
            raise web.seeother('/')

          elif action == 'clear_preferences':
            if user_id in config.ADMIN_USERS:
              db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, prefs=BSONPostgresSerializer.from_dict({}))
          
            raise web.seeother('/admin')
        
        else:
          content=get_admin_content()
          db = get_db()
          users = db.select(USER_TABLE, what='rdio_user_id, last_use')
          users = dict([('s%s' % u['rdio_user_id'], u['last_use']) for u in users])
          rdio_users = rdio.call('get', {'keys': ','.join(users.keys()), 'extras': '-*,username,url'})['result']
          user_list = [(u['username'], u['url'], users[uid]) for uid, u in rdio_users.items()]
          user_list.sort(key=lambda x: x[2], reverse=True)
          return render.admin(env_message=get_environment_message(), admin=content, users=user_list)
      
    raise web.seeother('/')
Ejemplo n.º 3
0
 def GET(self):
   
   rdio, currentUser = get_rdio_and_current_user()
   
   if rdio and currentUser:
     user_id = int(currentUser['key'][1:])
     
     myPlaylists = rdio.call('getPlaylists')['result']['owned']
     
     db = get_db()
     
     result = list(db.select('discoversong_user', what='address, playlist', where="rdio_user_id=%i" % user_id))
     if len(result) == 0:
       access_token = web.cookies().get('at')
       access_token_secret = web.cookies().get('ats')
       db.insert('discoversong_user', rdio_user_id=user_id, address=make_unique_email(currentUser), token=access_token, secret=access_token_secret, playlist='new')
       result = list(db.select('discoversong_user', what='address, playlist', where="rdio_user_id=%i" % user_id))[0]
     else:
       result = result[0]
     
     message = ''
     if 'saved' in get_input():
       message = '  Saved your selections.'
     
     return render.loggedin(name=currentUser['firstName'],
                            message=message,
                            to_address=result['address'],
                            editform=editform(myPlaylists, result['playlist'])
                           )
   else:
     return render.loggedout()
Ejemplo n.º 4
0
  def GET(self):
    
    form_input = get_input()
    action = form_input['button']
    svc, current_user, user_id = get_rdio_and_current_user()
    db = get_db()
    where_to_next = '/'
    
    if action == 'new_email':
      new_email = make_unique_email()
      db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, address=new_email)
      where_to_next += 'config?saved=True'
    
    elif action == 'save':
      where_to_next += 'config?saved=True'
      preferences = get_db_prefs(user_id, db=db)
      new_preferences = get_preferences_from_input(form_input)
      preferences.update(new_preferences)
      db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, prefs=BSONPostgresSerializer.from_dict(preferences))

      # circular import
      from discoversong.sources import SourceAppsManager
      for source_app in SourceAppsManager.ALL:
        for capability in source_app.capabilities:
          for configurable_thing in capability.config_options():
            if isinstance(configurable_thing, ConfigStoredValue):
              new_value = configurable_thing.read_from_input(form_input)
              if not configurable_thing.store_as_db_field:
                preferences = get_db_prefs(user_id, db=db)
                preferences[configurable_thing.name] = new_value
                db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, prefs=BSONPostgresSerializer.from_dict(preferences))
              else:
                db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, **{configurable_thing.name: new_value})

    raise web.seeother(where_to_next)
Ejemplo n.º 5
0
 def POST(self):
   db = get_db()
   
   form_input = get_input()
   
   envelope = json.loads(form_input['envelope'])
   to_addresses = envelope['to']
   
   for to_address in to_addresses:
     
     lookup = db.select(USER_TABLE, where="address='%s'" % to_address)
     
     if len(lookup) == 1:
       result = lookup[0]
       
       access_token = str(result['token'])
       access_token_secret = str(result['secret'])
       
       rdio, current_user, user_id = get_rdio_and_current_user(access_token=access_token, access_token_secret=access_token_secret)
       
       stats.got_email(user_id)
       
       subject = form_input['subject']
       body = form_input['text']
       
       try:
         title, artist = parse(subject, body)
       except Exception as e:
         logging.exception(e.message)
         return None
       
       search_results = well_formed_search(rdio, user_id, artist, title)
       return_results(rdio, user_id, search_results)
   
   return None
Ejemplo n.º 6
0
 def GET(self):
   rdio, current_user, user_id = get_rdio_and_current_user()
   disco_user, prefs = get_discoversong_user(user_id)
   # circular import
   from discoversong.sources import SourceAppsManager
   
   return render.config(params=Params(user=disco_user, preferences=prefs, message="", environment_message=get_environment_message()),
                        capabilities=SourceAppsManager.all_capabilities(),
                        editform=editform(playlists=rdio.call('getPlaylists')['result']['owned'], prefs=get_db_prefs(user_id)))
Ejemplo n.º 7
0
 def GET(self):
   svc, current_user, user_id = get_rdio_and_current_user()
   
   if svc and current_user:
     if user_id in config.ADMIN_USERS:
       db = get_db()
       db_users = db.select(USER_TABLE, what='*')
       return render.admin_users(env_message=get_environment_message(), users=db_users)
   
   raise web.seeother('/')
Ejemplo n.º 8
0
 def GET(self):
   rdio, currentUser, user_id = get_rdio_and_current_user()
   disco_user, message = get_discoversong_user(user_id)
   prefs = BSONPostgresSerializer.to_dict(disco_user['prefs'])
   # circular import
   from discoversong.sources import SourceAppsManager
   
   return render.config(user=disco_user,
                        prefs=prefs,
                        capabilities=SourceAppsManager.all_capabilities(),
                        editform=editform(playlists=rdio.call('getPlaylists')['result']['owned'], prefs=get_db_prefs(user_id)),
                        env_message=get_environment_message(),
                        message=message)
Ejemplo n.º 9
0
 def GET(self):
   
   input = get_input()
   action = input['button']
   
   rdio, currentUser = get_rdio_and_current_user()
   user_id = int(currentUser['key'][1:])
   db = get_db()
   
   if action == 'save':
   
     db.update('discoversong_user', where="rdio_user_id=%i" % user_id, playlist=input['playlist'])
     
   raise web.seeother('/?saved=True') 
Ejemplo n.º 10
0
  def GET(self):
    rdio, current_user, user_id = get_rdio_and_current_user()
    disco_user, prefs = get_discoversong_user(user_id)
    programs_page = etree.parse("http://www.kpfa.org/programs/music", etree.HTMLParser())

    divs = try_get(programs_page, '//div[@class="node"][.//a[starts-with(@href, "/playlists/show/")]]')

    shows = []
    for div in divs:
      title = try_get(div, './/h2/a[@title]/@title')
      playlists_link = try_get(div, './/a[starts-with(@href, "/playlists/show/")]/@href')
      show_num = int(playlists_link[len("/playlists/show/"):])
      shows.append(show(title=title, number=show_num))

    return render.list_shows(params=Params(user=disco_user, preferences=prefs, message="", environment_message=get_environment_message()),
                          shows=shows)
Ejemplo n.º 11
0
 def GET(self):
   rdio, currentUser, user_id = get_rdio_and_current_user()
   
   if rdio and currentUser:
     if not_allowed(user_id):
       raise web.seeother('/logout')
     
     disco_user, message = get_discoversong_user(user_id)
     stats.visited(user_id)
     # circular import
     from discoversong.sources import SourceAppsManager
     return render.loggedin(name=currentUser['firstName'],
                            message=message,
                            sourceapps=SourceAppsManager.ALL,
                            env_message=get_environment_message())
   else:
     return render.loggedout(env_message=get_environment_message())
Ejemplo n.º 12
0
 def GET(self):
   svc, current_user, user_id = get_rdio_and_current_user()
   
   if svc and current_user:
     if not_allowed(user_id):
       raise web.seeother('/logout')
     
     disco_user, prefs = get_discoversong_user(user_id)
     stats.visited(user_id)
     # circular import
     from discoversong.sources import SourceAppsManager
     return render.loggedin(params=Params(user=disco_user,
                                                preferences=prefs,
                                                message="",
                                                environment_message=get_environment_message()),
                            name=current_user['firstName'],
                            sourceapps=SourceAppsManager.ALL)
   else:
     return render.loggedout(env_message=get_environment_message())
Ejemplo n.º 13
0
  def GET(self, show_number, episode_number):
    episode_url = "http://www.kpfa.org/playlist/id/%i" % int(episode_number)
    playlist_page = etree.parse(episode_url, etree.HTMLParser())

    show_title = try_get(playlist_page, '//div[@class="field-item"]/a/text()')
    episode_title = try_get(playlist_page, '//div[@class="orangeheader"]/text()', xform=get_episode_title)

    songs = EpisodeImporter().scrape_songs(episode_number)

    rdio, current_user, user_id = get_rdio_and_current_user()
    disco_user, prefs = get_discoversong_user(user_id)

    return render.import_episode(params=Params(user=disco_user, preferences=prefs, message="", environment_message=get_environment_message()),
                                 search=search,
                                 importing=[],
                                 show_title=show_title,
                                 show_number=show_number,
                                 episode_title=episode_title,
                                 episode_number=episode_number,
                                 show_url="/import/" + show_number,
                                 songs=songs)
Ejemplo n.º 14
0
  def GET(self, show_number):
    inputs = web.input()
    p_url = inputs.get('p')
    rdio, current_user, user_id = get_rdio_and_current_user()
    disco_user, prefs = get_discoversong_user(user_id)

    show_url = "http://www.kpfa.org/playlists/show/" + show_number
    episodes_page = etree.parse(show_url, etree.HTMLParser())

    show_title = try_get(episodes_page, '//div[@class="orangeheader"]/text()')
    show_title = show_title[:show_title.index(": Playlists")]
    episode_links = try_get(episodes_page, '//a[starts-with(@href, "/playlist/id/")]')
    episodes = []
    for episode_link in episode_links:
      title = try_get(episode_link, 'text()', xform=get_episode_title)
      url = try_get(episode_link, '@href')
      number = int(url[len("/playlist/id/"):])
      episodes.append(episode(title=title, number=number))

    return render.list_episodes(params=Params(user=disco_user, preferences=prefs, message="", playlist_url=p_url, environment_message=get_environment_message()),
                                show=show(title=show_title, number=show_number),
                                episodes=episodes)
Ejemplo n.º 15
0
  def POST(self, show_number, episode_number):
    inputs = web.input()
    rdio, current_user, user_id = get_rdio_and_current_user()
    disco_user, prefs = get_discoversong_user(user_id)

    songs = EpisodeImporter().scrape_songs(episode_number)

    importing = []

    for song in songs:
      new_query = inputs.get('query_%s' % song.hash())
      if new_query != song.query:
        song.query = new_query
      for r in search(song):
        new_import = inputs.get('import_keys_%i_%s' % (song.hash(), r.key))
        if new_import:
          if r.key not in importing:
            importing.append(r.key)

    action = inputs.get('submit')
    if action.startswith('Retry'):
      return render.import_episode(params=Params(user=disco_user, preferences=prefs, message="", environment_message=get_environment_message()),
                                   search=search,
                                   importing=importing,
                                   show_title=inputs['show_title'],
                                   show_number=show_number,
                                   episode_title=inputs['episode_title'],
                                   episode_number=episode_number,
                                   show_url="/import/" + show_number,
                                   songs=songs)
    else:
      p = rdio.call('createPlaylist', {'name': inputs['pname'],
                                       'description': 'Imported by discoversong on %s' % datetime.datetime.now().strftime('%x'),
                                       'tracks': ','.join(importing),
                                       'isPublished': False})['result']
      return web.seeother("/import/%s?p=%s" % (show_number, p['shortUrl']))
Ejemplo n.º 16
0
#!/usr/bin/env python

from discoversong.parse import parse_twitter
from discoversong.rdio import get_discoversong_user_by_twitter, get_rdio_and_current_user
from discoversong.twitter import get_mentions
from discoversong.stats import read_to_mention
from discoversong.well_formed_search import well_formed_search, return_results

mentions = get_mentions()
for mention in mentions:
  disco_user_row = get_discoversong_user_by_twitter(mention["user"]["screen_name"])
  if disco_user_row is None:
    continue
  try:
    title, artist = parse_twitter(mention["text"])
  except:
    continue
  
  token, secret = str(disco_user_row['token']), str(disco_user_row['secret'])
  
  rdio, current_user, user_id = get_rdio_and_current_user(access_token=token, access_token_secret=secret)
  search_results = well_formed_search(rdio, user_id, artist, title)
  return_results(rdio, user_id, search_results, from_tweet_id=mention["id"])
  read_to_mention(mention["id"])
Ejemplo n.º 17
0
def search(song):
  svc, current_user, user_id = get_rdio_and_current_user()
  return rdio_songs_matching_scrape(svc, song, text_renderer=lambda result: render.compared_song(song, result))
Ejemplo n.º 18
0
  def POST(self):
    db = get_db()
    
    input = get_input()
    
    envelope = json.loads(input['envelope'])
    to_addresses = envelope['to']
    
    print 'received email to', to_addresses
    
    for to_address in to_addresses:
      
      lookup = db.select('discoversong_user', what='rdio_user_id, playlist, token, secret', where="address='%s'" % to_address)
      
      if len(lookup) == 1:
        result = lookup[0]
        
        access_token = str(result['token'])
        access_token_secret = str(result['secret'])
        
        rdio, current_user = get_rdio_and_current_user(access_token=access_token, access_token_secret=access_token_secret)
        
        print 'found user', current_user['username']
        
        subject = input['subject']
        
        title, artist = parse(subject)
        
        print 'parsed artist', artist, 'title', title
        
        search_result = rdio.call('search', {'query': ' '.join([title, artist]), 'types': 'Track'})
        
        track_keys = []
        name_artist_pairs_found = {}
        
        for possible_hit in search_result['result']['results']:
          
          if possible_hit['canStream']:
            
            name = possible_hit['name']
            artist_name = possible_hit['artist']
            
            if name_artist_pairs_found.has_key((name, artist_name)):
              continue
            
            name_artist_pairs_found[(name, artist_name)] = True
            
            track_key = possible_hit['key']
            track_keys.append(track_key)
        
        print 'found tracks', track_keys
        
        playlist_key = result['playlist']
        
        if playlist_key in ['new', 'alwaysnew']:
          
          p_names = [playlist['name'] for playlist in rdio.call('getPlaylists')['result']['owned']]

          new_name = generate_playlist_name(p_names)
          
          print 'creating new playlist', new_name
          
          result = rdio.call('createPlaylist', {'name': new_name,
                                                'description': 'Songs found by discoversong on %s.' % datetime.datetime.now().strftime('%A, %d %b %Y %H:%M'),
                                                'tracks': ', '.join(track_keys)})
          new_key = result['result']['key']
          
          if playlist_key == 'new':
            
            print 'setting', new_key, 'as the playlist to use next time'
            
            user_id = int(current_user['key'][1:])
            db.update('discoversong_user', where="rdio_user_id=%i" % user_id, playlist=new_key)
          # else leave 'alwaysnew' to repeat this behavior every time
        
        else:
          rdio.call('addToPlaylist', {'playlist': playlist_key, 'tracks': ', '.join(track_keys)})
    
    return None