Exemple #1
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)
Exemple #2
0
def get_discoversong_user(user_id):
  assert user_id is not None
  db = get_db()

  disco_user = list(db.select(USER_TABLE, where="rdio_user_id=%i" % user_id))
  
  if len(disco_user) == 0:
    access_token = web.cookies().get('at')
    access_token_secret = web.cookies().get('ats')
    
    db.insert(USER_TABLE,
      rdio_user_id=user_id,
      address=make_unique_email(),
      token=access_token,
      secret=access_token_secret,
      first_use=datetime.date.today(),
      last_use=datetime.date.today(),
      emails=0,
      searches=0,
      songs=0,
      prefs=BSONPostgresSerializer.from_dict({}))
    
    disco_user = list(db.select(USER_TABLE, where="rdio_user_id=%i" % user_id))[0]
    count = int(list(db.query("SELECT count(*) from %s" % USER_TABLE))[0]['count'])
    announce_new_user(count)
    
  else:
    disco_user = disco_user[0]
    
    def none_or_empty(strg):
      return strg is None or strg == ''
    
    def fields_need_update(field_names):
      for field in field_names:
        if not disco_user.has_key(field):
          return True
        if none_or_empty(disco_user[field]):
          return True
      return False
    
    if fields_need_update(['token', 'secret', 'address', 'prefs']):
      
      if fields_need_update(['token', 'secret']):
        access_token = web.cookies().get('at')
        access_token_secret = web.cookies().get('ats')
        db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, secret=access_token_secret, token=access_token)
      if fields_need_update(['address']):
        db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, address=make_unique_email())
      if fields_need_update(['prefs']):
        db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, prefs=BSONPostgresSerializer.from_dict({}))
      
      disco_user = list(db.select(USER_TABLE, where="rdio_user_id=%i" % user_id))[0]
  
  if not disco_user.has_key('prefs') or not disco_user['prefs']:
    logging.info('resetting preferences')
    db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, prefs=BSONPostgresSerializer.from_dict({}))
    disco_user = list(db.select(USER_TABLE, where="rdio_user_id=%i" % user_id))[0]

  return disco_user, BSONPostgresSerializer.to_dict(disco_user['prefs'])
Exemple #3
0
 def get_value(self, user):
   if self.store_as_db_field:
     value = getattr(user, self.name, 'None')
   else:
     prefs = BSONPostgresSerializer.to_dict(user['prefs'])
     value = prefs.get(self.name)
   return value
Exemple #4
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('/')
Exemple #5
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('/')
def return_results(rdio, user_id, song_artist_url_list, from_tweet_id=None):
    db = get_db()
    prefs = get_db_prefs(user_id, db=db)

    playlist_key = prefs.get(Preferences.PlaylistToSaveTo, "new")
    add_to_collection = prefs.get(Preferences.AddToCollection, False)
    track_keys_list = [s[3] for s in song_artist_url_list]

    playlists_call = rdio.call("getPlaylists")
    if "result" in playlists_call:
        playlists = playlists_call["result"]["owned"]
    else:
        playlists = []
    p_keys = [playlist["key"] for playlist in playlists]
    p_names = [playlist["name"] for playlist in playlists]

    if playlist_key in ["new", "alwaysnew"] or playlist_key not in p_keys:
        new_name = generate_playlist_name(p_names)
        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_list),
            },
        )
        new_key = result["result"]["key"]

        if playlist_key == "new" or playlist_key not in p_keys:
            prefs[Preferences.PlaylistToSaveTo] = new_key
            db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, prefs=BSONPostgresSerializer.from_dict(prefs))

        # else leave 'alwaysnew' to repeat this behavior every time

    else:
        rdio.call("addToPlaylist", {"playlist": playlist_key, "tracks": ", ".join(track_keys_list)})

    if add_to_collection:
        rdio.call("addToCollection", {"keys": ", ".join(track_keys_list)})

    stats.found_songs(user_id, len(song_artist_url_list))

    twitter_name_config = Capabilities.Twitter().config_options_dict()["twitter_name"]
    user, message = get_discoversong_user(user_id)

    twitter_name = "@" + twitter_name_config.get_value(user)
    reply_to_tweet_id = from_tweet_id

    song, artist, url, track_key = song_artist_url_list[0]
    try:
        tweet_about_found_song(song, artist, url, mention_name=twitter_name, reply_to_tweet_id=reply_to_tweet_id)
    except twython.TwythonError as twe:
        if twe.error_code == 403:
            pass
Exemple #7
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)
def return_results(rdio, user_id, song_artist_url_list, from_tweet_id=None):
  db = get_db()
  prefs = get_db_prefs(user_id, db=db)
  
  playlist_key = prefs.get(Preferences.PlaylistToSaveTo, 'new')
  add_to_collection = prefs.get(Preferences.AddToCollection, False)
  track_keys_list = [s[3] for s in song_artist_url_list]
  
  playlists_call = rdio.call('getPlaylists')
  if 'result' in playlists_call:
    playlists = playlists_call['result']['owned']
  else:
    playlists = []
  p_keys = [playlist['key'] for playlist in playlists]
  p_names = [playlist['name'] for playlist in playlists]
  
  if playlist_key in ['new', 'alwaysnew'] or playlist_key not in p_keys:
    new_name = generate_playlist_name(p_names)
    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_list)})
    new_key = result['result']['key']
    
    if playlist_key == 'new' or playlist_key not in p_keys:
      prefs[Preferences.PlaylistToSaveTo] = new_key
      db.update(USER_TABLE, where="rdio_user_id=%i" % user_id, prefs=BSONPostgresSerializer.from_dict(prefs))
    
    # else leave 'alwaysnew' to repeat this behavior every time
  
  else:
    rdio.call('addToPlaylist', {'playlist': playlist_key, 'tracks': ', '.join(track_keys_list)})
  
  if add_to_collection:
    rdio.call('addToCollection', {'keys': ', '.join(track_keys_list)})
  
  stats.found_songs(user_id, len(song_artist_url_list))
  
  twitter_name_config = Capabilities.Twitter().config_options_dict()['twitter_name']
  user, message = get_discoversong_user(user_id)
  
  twitter_name = '@' + twitter_name_config.get_value(user)
  reply_to_tweet_id = from_tweet_id
  
  song, artist, url, track_key = song_artist_url_list[0]
  try:
    tweet_about_found_song(song, artist, url, mention_name=twitter_name, reply_to_tweet_id=reply_to_tweet_id)
  except twython.TwythonError as twe:
    if twe.error_code == 403:
      pass
Exemple #9
0
def get_db_prefs(user_id, db=None):
  if db is None:
    db = get_db()
  prefs = BSONPostgresSerializer.to_dict(list(db.select(USER_TABLE, what='prefs', where="rdio_user_id=%i" % user_id))[0]['prefs'])
  return prefs