Exemplo n.º 1
0
def send_reset_email(request, schema, **kwargs):
    email = schema.email
    api   = globalMongoStampedAPI()
    
    if not utils.validate_email(email):
        msg = "Invalid format for email address"
        logs.warning(msg)
        raise StampedInvalidEmailError("Invalid email address")
    
    # verify account exists
    try:
        user = stampedAPIProxy.checkAccount(email)
        
        if user is None:
            raise
    except Exception:
        utils.printException()
        logs.error("ERROR: invalid email '%s'" % email)
        
        ### TODO: Display appropriate error message
        errorMsg = 'No account information was found for that email address.'
        raise StampedHTTPError(404, msg="Email address not found", kind='invalid_input')
    
    account = stampedAPIProxy.getAccount(user['user_id'])
    auth_service = account['auth_service']
    
    if auth_service != 'stamped':
        raise StampedInputError("Account password not managed by Stamped for user '%s' (primary account service is '%s')" % (account['screen_name'], auth_service))
    
    # send email
    logs.info("sending email to '%s' (user: '******')" % (email, user['screen_name']))
    result = g_stamped_auth.forgotPassword(email)
    
    return transform_output(result)
Exemplo n.º 2
0
 def test_resolve_artist(self):
     mongoApi = globalMongoStampedAPI()
     collection = mongoApi._entityDB
     allItems = collection.getEntitiesByQuery(dict())
     for item in allItems:
         if item.isType('artist') and (item.albums or item.tracks):
             del item.albums
             del item.tracks
             mongoApi._mergeEntity(item)
             self.verifyAllLinks(item.entity_id, collection)
             break
Exemplo n.º 3
0
 def test_resolve_song(self):
     mongoApi = globalMongoStampedAPI()
     collection = mongoApi._entityDB
     allItems = collection.getEntitiesByQuery(dict())
     merged = None
     for item in allItems:
         if item.isType('track') and item.title == 'Call Me Maybe':
             del item.albums
             del item.artists
             merged = mongoApi._mergeEntity(item)
             break
     else:
         raise Exception('could not find track')
     for artist in merged.artists:
         if artist.title == ARTIST:
             self.verifyAllLinks(artist.entity_id, collection)
def main():
    conn = S3Connection(keys.aws.AWS_ACCESS_KEY_ID, keys.aws.AWS_SECRET_KEY)
    bucketName = "stamped.com.static.images"
    bucket = conn.lookup(bucketName)

    stampedAPI = globalMongoStampedAPI()
    screenNames = stampedAPI._userDB._getAllScreenNames()
    sizes = [24, 48, 60, 96, 144]

    for screenName in screenNames:

        # Check if image exists
        key = "/users/%s.jpg" % screenName
        if not _checkImageOnS3(bucket, key):
            logs.info("No user image exists: %s" % screenName)
            continue

        # Check what images need to be resized
        newSizes = set()
        for size in sizes:
            key = "/users/%s-%sx%s.jpg" % (screenName, size, size)
            if not _checkImageOnS3(bucket, key):
                newSizes.add(size)

        if len(newSizes) == 0:
            logs.info("No need to resize: %s" % screenName)
            continue

        # Get current full-size image
        key = "/users/%s.jpg" % screenName
        imgData = _getImageFromS3(bucket, key)
        io = StringIO(imgData)
        img = Image.open(io)

        for size in newSizes:
            resized = img.resize((size, size), Image.ANTIALIAS)
            out = StringIO()
            resized.save(out, "jpeg", optimize=True, quality=90)
            key = "/users/%s-%sx%s.jpg" % (screenName, size, size)
            _addImageToS3(bucket, key, out)
            logs.info("Added image: /users/%s-%sx%s.jpg" % (screenName, size, size))
Exemplo n.º 5
0
def revive_tombstoned_entities(entity_id):
    """
    Finds all entities that are tombstoned to the given entity, undo the tombstone. This function will also find all
    stamps and todos that were transfered to the given entity as a consequence of tombstoning, and return those items to
    the original entity.
    """

    entities_by_id = {}
    entity_db = MongoEntityCollection.MongoEntityCollection()
    for entity in entity_db.getEntitiesByTombstoneId(entity_id):
        clear_tombstone_id(entity, entity_db, entities_by_id)

    todo_db = MongoTodoCollection.MongoTodoCollection()
    todo_seed_db = MongoTodoCollection.MongoSeedTodoCollection()
    for todo_id in todo_db.getTodoIdsFromEntityId(entity_id):
        original_entity_id = todo_seed_db.getEntityIdForTodo(todo_id)
        if original_entity_id is None:
            logs.warn('Could not find entity for seed todo: ' + todo_id)
            continue
        if original_entity_id in entities_by_id:
            entity = entities_by_id[original_entity_id]
        else:
            entity = entity_db.getEntity(original_entity_id)
            entity = clear_tombstone_id(entity, entity_db, entities_by_id)
        todo_db.updateTodoEntity(todo_id, entity.minimize())

    stamp_db = MongoStampCollection.MongoStampCollection()
    stamp_seed_db = MongoStampCollection.MongoSeedStampCollection()
    for stamp_id in stamp_db.getStampIdsForEntity(entity_id):
        original_entity_id = stamp_seed_db.getStamp(stamp_id).entity.entity_id
        if original_entity_id in entities_by_id:
            entity = entities_by_id[original_entity_id]
        else:
            entity = entity_db.getEntity(original_entity_id)
            entity = clear_tombstone_id(entity, entity_db, entities_by_id)
        stamp_db.updateStampEntity(stamp_id, entity.minimize())

    api = globalMongoStampedAPI()
    for entity in entities_by_id.itervalues():
        api.mergeEntity(entity)
Exemplo n.º 6
0
def export_stamps(request, schema, **kwargs):
    login = schema.login
    
    try:
        if "@" in login:
            account = stampedAPIProxy.getAccountByEmail(login)
        else:
            account = stampedAPIProxy.getAccountByScreenName(login)
    except Exception:
        utils.printException()
        account = None
    
    if account is None:
        raise StampedInputError("invalid account")
    
    kwargs.setdefault('content_type', 'application/pdf')
    kwargs.setdefault('mimetype',     'application/pdf')
    
    user_id     = account['user_id']
    screen_name = account['screen_name']
    
    logs.info("screen_name: %s" % screen_name)
    
    exporter    = api.DataExporter.DataExporter(globalMongoStampedAPI())
    tmpfile     = '/tmp/%s.pdf' % user_id
    
    logs.info("tmpfile: %s" % tmpfile)
    
    with open(tmpfile, 'w') as fout:
        exporter.export_user_data(user_id, fout)
    
    logs.info("resulting tmpfile: %s" % tmpfile)
    f = open(tmpfile, "rb")
    response = HttpResponse(f, **kwargs)
    response['Content-Disposition'] = 'attachment; filename="%s_stamps.pdf"' % screen_name
    
    return response
Exemplo n.º 7
0
def main():
    conn = S3Connection(keys.aws.AWS_ACCESS_KEY_ID, keys.aws.AWS_SECRET_KEY)
    bucketName = 'stamped.com.static.images'
    bucket = conn.lookup(bucketName)
    
    stampedAPI  = globalMongoStampedAPI()
    
    users = stampedAPI._userDB._collection.find({'timestamp.image_cache': {'$exists': True}})
    
    failed = set()
    
    for user in users:
        screenName = user['screen_name_lower']
        
        # Check if image exists
        key = '/users/%s.jpg' % screenName
        if not _checkImageOnS3(bucket, key):
            if user['timestamp']['image_cache'] < datetime.datetime.utcnow() - datetime.timedelta(hours=1):
                logs.info("No user image exists: %s" % screenName)
                failed.add(user['_id'])
                stampedAPI._userDB._collection.update({'_id': user['_id']}, {'$unset': {'timestamp.image_cache': 1}})
    
    print "%s missing photos" % len(failed)
    print failed
Exemplo n.º 8
0
def _entityDB():
    api = globalMongoStampedAPI()
    return api._entityDB
Exemplo n.º 9
0
def _api():
    return globalMongoStampedAPI()
Exemplo n.º 10
0
 def __init__(self):
     self._prod = IS_PROD
     self._ec2  = utils.is_ec2()
     
     self.api    = globalMongoStampedAPI()
     self._cache = globalMemcache()
Exemplo n.º 11
0
    'http://www.stamped.com', 
    'http://dev.stamped.com', 
]

if not IS_PROD:
    VALID_ORIGINS.extend([
        'http://localhost:19000', 
        'http://localhost:18000', 
        'http://localhost:8000', 
    ])

t1 = time.time()

# TODO (travis): use single global stamped API instance
# e.g., there are MongoStampedAPIs instantiated throughout the codebase => refactor
stampedAPI  = globalMongoStampedAPI()
stampedAuth = MongoStampedAuth()
cache       = globalMemcache()

t2 = time.time()
duration = (t2 - t1) * 1.0
logs.info("INIT: %s sec" % duration)

if duration > 2:
    logs.warning("LONG INIT: %s sec" % duration)

defaultExceptions = [
    (StampedDocumentNotFoundError,      404,    'not_found',            'There was a problem retrieving the requested data'),
    (StampedAuthError,                  401,    'invalid_credentials',  'There was an error during authentication'),
    (StampedInputError,                 400,    'invalid_request',      'An error occurred. Please try again later.'),
    (StampedIllegalActionError,         403,    'invalid_request',      'An error occurred. Please try again later.'),
Exemplo n.º 12
0
 def __init__(self):
     self.__registered_tasks = []
     self.__api = globalMongoStampedAPI()
Exemplo n.º 13
0
import Globals
from api.MongoStampedAPI import globalMongoStampedAPI
from resolve.UMDSource import *
from resolve.StampedSource import StampedSource
import datetime
from sys import argv

api = globalMongoStampedAPI()
stampedSource = StampedSource(api)
if len(argv) != 3 or argv[1] not in ('track', 'album'):
    raise Exception('Usage:  import_umd_from_file.py <track or album> <filename>')
umdClass = UMDTrack if argv[1]=='track' else UMDAlbum
with open(argv[2]) as fileIn:
    for line in fileIn:
        data = eval(line)
        proxy = umdClass(data)
        api.mergeProxyIntoDb(proxy, stampedSource)