Commits

ronald martinez committed af6bbef

ready

  • Participants
  • Parent commits 71f917c

Comments (0)

Files changed (177)

celeryconfig.py

-from celery.schedules import crontab
-
-import settings
-
-CELERY_IMPORTS = ('tasks',)
-BROKER_TRANSPORT = 'sqs'
-BROKER_TRANSPORT_OPTIONS = {
-    'region': 'us-east-1',
-}
-
-CELERY_SEND_TASK_SENT_EVENT = 1
-
-BROKER_URL = 'sqs://%s:%s@' % (settings.AWS_KEY, settings.AWS_SECRET) 
-
-#BROKER_USER = settings.AWS_KEY
-#BROKER_PASSWORD = settings.AWS_SECRET
-
-CELERYBEAT_SCHEDULE = {
-    "generate_thumbs": {
-        'task': "generate_thumbs",
-        'schedule': crontab(minute="*/1"),
-    }
-}

controllers/admin/__init__.py

Empty file removed.

controllers/admin/auth.py

-import logging
-
-from datetime import datetime
-from controllers import BaseHandler
-from models import SystemUser
-
-
-class Login(BaseHandler):
-
-    def get(self, status_code=None):
-
-        if self.current_user:
-            self.redirect(self.reverse_url('admin_product'))
-            return
-
-        self.render('admin/login.html', status_code=status_code)
-
-    def post(self):
-        username = self.get_argument('username')
-        password = self.get_argument('password')
-        status_code = 0
-
-        if not username or not password:
-            status_code = 1
-        else:
-            _user = SystemUser.auth(username, password)
-            if _user:
-                _user.last_login_at = datetime.now()
-                try:
-                    _user.save()
-                except Exception as exc:
-                    logging.error(exc)
-                    status_code = 3
-                else:
-                    self.set_secure_cookie('user', str(_user.id))
-                    self.redirect(
-                        self.get_argument(
-                            'next',
-                            self.reverse_url('admin_product')
-                        )
-                    )
-                return
-            else:
-                status_code = 2
-
-        self.get(status_code)
-
-
-class Logout(BaseHandler):
-
-    def get(self):
-        if self.current_user:
-            self.clear_all_cookies()
-        self.redirect(self.reverse_url('admin_login'))

controllers/admin/product.py

-import logging
-
-from tornado.web import HTTPError, authenticated
-
-from controllers import BaseHandler, ListMixin
-from models import Product, Category, Match
-
-from boto.s3.connection import S3Connection
-
-import datetime
-import settings
-
-
-class List(BaseHandler, ListMixin):
-
-    #@authenticated
-    def get(self):
-
-        filters = {'created_at__gte': datetime.date(2012, 01, 01)}
-        status = self.get_argument('status', None)
-
-        if status:
-            filters['status'] = status
-
-        #queryset = Product.objects.order_by('-id')
-        queryset = Product.objects.filter(**filters).order_by('-created_at')
-
-        #created_at__gte=datetime.date(2012, 01, 01)
-        #.order_by('-created_at')
-
-        self.render(
-            'admin/product/list.html',
-            status=status,
-            **self.get_pagination(count=len(queryset), query=queryset)
-        )
-
-
-class Edit(BaseHandler):
-
-    @authenticated
-    def get(self, id, **kwargs):
-        user = self.get_current_user()
-
-        try:
-            product = Product.objects.get(id)
-        except:
-            self.send_error(404)
-            return
-
-        if not product.title:
-            product.title = 'product'
-
-        if not product.description:
-            product.description = 'This is a brief description..'
-
-        if not product.cost:
-            product.cost = 50
-
-        if not product.will_travel:
-            product.will_travel = 1000
-
-        if product.published_at:
-            try:
-                product.published_at = product.published_at.date()
-            except Exception as exc:
-                logging.error(exc)
-        else:
-            product.published_at = datetime.datetime.now().strftime('%Y-%m-%d')
-
-        if product.expires_at:
-            try:
-                product.expires_at = product.expires_at.date()
-            except Exception as exc:
-                logging.error(exc)
-        else:
-            product.expires_at = (datetime.datetime.now() + \
-                datetime.timedelta(days=5)).strftime('%Y-%m-%d')
-
-        if not product.location:
-            product.location = 'WC 12 avenue'
-
-        categories = Category.objects.all()
-
-        if not product.categories:
-            product.categories = [u'metarials', u'sporting']
-
-        if product.categories:
-            for x, y in enumerate(categories):
-                if y.title.lower() in product.categories:
-                    categories[x].checked = True
-                else:
-                    categories[x].checked = False
-
-        logging.info('image: %s' % product.image)
-        logging.info('tyny_image: %s' % product.tiny_url)
-        logging.info('small_image: %s' % product.small_url)
-        logging.info('large_image: %s' % product.large_url)
-        logging.info('medium_image: %s' % product.medium_url)
-        logging.info('is_upload_thumbs: %s' % product.is_upload_thumbs)
-
-        kwargs['product'] = product
-        kwargs['categories'] = categories
-        kwargs['audiences'] = Product.AUDIENCES_TYPES
-        kwargs['user'] = user
-        kwargs['action'] = 'edit'
-        self.render('product.html', **kwargs)
-
-    @authenticated
-    def post(self, id):
-        status_code = 0
-
-        categories = self.get_arguments('categories', None)
-        title = self.get_argument('title', '')
-        description = self.get_argument('description', '')
-        cost = self.get_argument('cost', '')
-        will_travel = self.get_argument('will_travel', '')
-        allow_retailers = self.get_argument('allow_retailers', None)
-        allow_charities = self.get_argument('allow_charities', None)
-        donate_now = self.get_argument('donate_now', None)
-        published_at = self.get_argument('published_at', '')
-        expires_at = self.get_argument('expires_at', '')
-        type = self.get_argument('type', None)
-        location = self.get_argument('location', '')
-        audience = self.get_argument('audience', '')
-
-        try:
-            will_travel = int(will_travel)
-        except Exception as exc:
-            logging.error(exc)
-            will_travel = 0
-
-        try:
-            cost = int(cost)
-        except Exception as exc:
-            logging.error(exc)
-            cost = 0
-
-        user = self.get_current_user()
-
-        if not user:
-            self.send_error(404)
-
-        try:
-            product = Product.objects.get(id)
-        except Exception as exc:
-            self.send_error(404)
-
-        if len(title) < 1 or len(description) < 1 or len(published_at) < 1:
-            status_code = 1
-        elif not type in ('have', 'want'):
-            status_code = 1
-
-        if status_code == 0:
-            try:
-                published_at = datetime.datetime.strptime(
-                    published_at, '%Y-%m-%d')
-            except ValueError as exc:
-                logging.error(exc)
-                status_code = 2
-
-            logging.info(expires_at)
-
-            try:
-                expires_at = datetime.datetime.strptime(
-                    expires_at, '%Y-%m-%d')
-            except ValueError as exc:
-                logging.error(exc)
-                status_code = 2
-
-        if status_code == 0:
-            if not categories:
-                status_code = 4
-
-        if status_code == 0:
-            try:
-                _raw_image = self.request.files['filename'][0]
-            except (KeyError, IndexError) as exc:
-                _raw_image = None
-
-            product.title = title
-            product.description = description
-            product.cost = cost
-            product.will_travel = will_travel
-            product.allow_charities = True if allow_charities else False
-            product.allow_retailers = True if allow_retailers else False
-            product.donate_now = True if donate_now else False
-            product.published_at = published_at
-            product.expires_at = expires_at
-            product.type = type
-            product.user = user.email
-            product.categories = categories
-            product.location = location
-            product.audience = audience
-            product.status = 'active'
-            product.set_slug(title)
-
-            try:
-                product.update()
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 5
-
-            if status_code == 0:
-                if _raw_image:
-
-                    if not product.upload_img(_raw_image.get('body')):
-                        status_code = 4
-                    else:
-                        if not product.send_message_to_generate_thumbs():
-                        #if not product.generate_thumbs():
-                            logging.error('no generate slug')
-                            #status_code = 4
-                        #generate_thumbs.delay(product.id)
-
-                    if status_code == 0:
-                        self.redirect(self.reverse_url('product_edit',
-                            product.id))
-                        return
-
-        self.get(id, status_code=status_code)
-
-
-class Delete(BaseHandler):
-
-    #@authenticated
-    #def post(self):
-    def get(self):
-
-        #if self.request.headers.get('X-Requested-With') != 'XMLHttpRequest':
-            #raise HTTPError(403)
-
-        status_code = 0
-
-        try:
-            product = Product.objects.get(self.get_argument('id'))
-        except Exception as exc:
-            status_code = 1
-            logging.error(exc)
-            raise HTTPError(404)
-        else:
-
-            for conversation in product.conversations:
-                print conversation
-                conversation.delete()
-
-            for match in Match.objects.filter(source=product.id):
-                print match
-                match.delete()
-
-            for match in Match.objects.filter(target=product.id):
-                print match
-                match.delete()
-
-            try:
-                product.delete()
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 2
-            else:
-                cn = S3Connection(
-                    settings.AWS_KEY, settings.AWS_SECRET
-                )
-
-                for suffix in ('', '_large', '_medium', '_small', '_tiny'):
-
-                    print '%s/%s%s' % (settings.S3_UPLOAD_PATH_PRODUCT,
-                        product.id, suffix)
-
-                    try:
-                        key = cn.get_bucket(settings.S3_BUCKET_NAME).get_key(
-                            '%s/%s%s' % (settings.S3_UPLOAD_PATH_PRODUCT,
-                                product.id, suffix))
-                        key.delete()
-                    except Exception as exc:
-                        logging.error(exc)
-
-        self.finish({'status_code': status_code})
-
-
-class DeleteImage(BaseHandler):
-
-    #@authenticated
-    def post(self):
-        #if self.request.headers.get('X-Requested-With') != 'XMLHttpRequest':
-            #raise HTTPError(403)
-
-        status_code = 0
-
-        try:
-            product = Product.objects.get(self.get_argument('id'))
-        except Exception as exc:
-            logging.error(exc)
-        else:
-
-            cn = S3Connection(
-                settings.AWS_KEY, settings.AWS_SECRET
-            )
-
-            key = cn.get_bucket(settings.S3_BUCKET_NAME).get_key(
-                '%s/%s' % (settings.S3_UPLOAD_PATH_PRODUCT, product.id))
-            key.delete()
-
-        self.finish({'status_code': status_code})

controllers/admin/user.py

-import logging
-
-from tornado.web import HTTPError, authenticated
-
-from controllers import BaseHandler, ListMixin
-from models import User
-
-from boto.s3.connection import S3Connection
-
-import datetime
-import settings
-
-
-class List(BaseHandler, ListMixin):
-
-    #@authenticated
-    def get(self):
-
-        filters = {'created_at__gte': datetime.date(2012, 01, 01)}
-        status = self.get_argument('status', None)
-
-        if status:
-            filters['status'] = status
-
-        #queryset = User.objects.order_by('-id')
-        queryset = User.objects.filter(**filters).order_by('-created_at')
-
-        #created_at__gte=datetime.date(2012, 01, 01)
-        #.order_by('-created_at')
-
-        self.render(
-            'admin/user/list.html',
-            status=status,
-            **self.get_pagination(count=len(queryset), query=queryset)
-        )
-
-
-class Edit(BaseHandler):
-
-    @authenticated
-    def get(self, id, **kwargs):
-        user = self.get_current_user()
-
-        try:
-            user = User.objects.get(id)
-        except:
-            self.send_error(404)
-            return
-
-        if not user.title:
-            user.title = 'user'
-
-        if not user.description:
-            user.description = 'This is a brief description..'
-
-        if not user.cost:
-            user.cost = 50
-
-        if not user.will_travel:
-            user.will_travel = 1000
-
-        if user.published_at:
-            try:
-                user.published_at = user.published_at.date()
-            except Exception as exc:
-                logging.error(exc)
-        else:
-            user.published_at = datetime.datetime.now().strftime('%Y-%m-%d')
-
-        if user.expires_at:
-            try:
-                user.expires_at = user.expires_at.date()
-            except Exception as exc:
-                logging.error(exc)
-        else:
-            user.expires_at = (datetime.datetime.now() + \
-                datetime.timedelta(days=5)).strftime('%Y-%m-%d')
-
-        if not user.location:
-            user.location = 'WC 12 avenue'
-
-        categories = Category.objects.all()
-
-        if not user.categories:
-            user.categories = [u'metarials', u'sporting']
-
-        if user.categories:
-            for x, y in enumerate(categories):
-                if y.title.lower() in user.categories:
-                    categories[x].checked = True
-                else:
-                    categories[x].checked = False
-
-        logging.info('image: %s' % user.image)
-        logging.info('tyny_image: %s' % user.tiny_url)
-        logging.info('small_image: %s' % user.small_url)
-        logging.info('large_image: %s' % user.large_url)
-        logging.info('medium_image: %s' % user.medium_url)
-        logging.info('is_upload_thumbs: %s' % user.is_upload_thumbs)
-
-        kwargs['user'] = user
-        kwargs['categories'] = categories
-        kwargs['audiences'] = User.AUDIENCES_TYPES
-        kwargs['user'] = user
-        kwargs['action'] = 'edit'
-        self.render('user.html', **kwargs)
-
-    @authenticated
-    def post(self, id):
-        status_code = 0
-
-        categories = self.get_arguments('categories', None)
-        title = self.get_argument('title', '')
-        description = self.get_argument('description', '')
-        cost = self.get_argument('cost', '')
-        will_travel = self.get_argument('will_travel', '')
-        allow_retailers = self.get_argument('allow_retailers', None)
-        allow_charities = self.get_argument('allow_charities', None)
-        donate_now = self.get_argument('donate_now', None)
-        published_at = self.get_argument('published_at', '')
-        expires_at = self.get_argument('expires_at', '')
-        type = self.get_argument('type', None)
-        location = self.get_argument('location', '')
-        audience = self.get_argument('audience', '')
-
-        try:
-            will_travel = int(will_travel)
-        except Exception as exc:
-            logging.error(exc)
-            will_travel = 0
-
-        try:
-            cost = int(cost)
-        except Exception as exc:
-            logging.error(exc)
-            cost = 0
-
-        user = self.get_current_user()
-
-        if not user:
-            self.send_error(404)
-
-        try:
-            user = User.objects.get(id)
-        except Exception as exc:
-            self.send_error(404)
-
-        if len(title) < 1 or len(description) < 1 or len(published_at) < 1:
-            status_code = 1
-        elif not type in ('have', 'want'):
-            status_code = 1
-
-        if status_code == 0:
-            try:
-                published_at = datetime.datetime.strptime(
-                    published_at, '%Y-%m-%d')
-            except ValueError as exc:
-                logging.error(exc)
-                status_code = 2
-
-            logging.info(expires_at)
-
-            try:
-                expires_at = datetime.datetime.strptime(
-                    expires_at, '%Y-%m-%d')
-            except ValueError as exc:
-                logging.error(exc)
-                status_code = 2
-
-        if status_code == 0:
-            if not categories:
-                status_code = 4
-
-        if status_code == 0:
-            try:
-                _raw_image = self.request.files['filename'][0]
-            except (KeyError, IndexError) as exc:
-                _raw_image = None
-
-            user.title = title
-            user.description = description
-            user.cost = cost
-            user.will_travel = will_travel
-            user.allow_charities = True if allow_charities else False
-            user.allow_retailers = True if allow_retailers else False
-            user.donate_now = True if donate_now else False
-            user.published_at = published_at
-            user.expires_at = expires_at
-            user.type = type
-            user.user = user.email
-            user.categories = categories
-            user.location = location
-            user.audience = audience
-            user.status = 'active'
-            user.set_slug(title)
-
-            try:
-                user.update()
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 5
-
-            if status_code == 0:
-                if _raw_image:
-
-                    if not user.upload_img(_raw_image.get('body')):
-                        status_code = 4
-                    else:
-                        if not user.send_message_to_generate_thumbs():
-                        #if not user.generate_thumbs():
-                            logging.error('no generate slug')
-                            #status_code = 4
-                        #generate_thumbs.delay(user.id)
-
-                    if status_code == 0:
-                        self.redirect(self.reverse_url('user_edit',
-                            user.id))
-                        return
-
-        self.get(id, status_code=status_code)
-
-
-class Delete(BaseHandler):
-
-    #@authenticated
-    #def post(self):
-    def get(self):
-
-        #if self.request.headers.get('X-Requested-With') != 'XMLHttpRequest':
-            #raise HTTPError(403)
-
-        status_code = 0
-
-        try:
-            user = User.objects.get(self.get_argument('id'))
-        except Exception as exc:
-            status_code = 1
-            logging.error(exc)
-            raise HTTPError(404)
-        else:
-
-            for conversation in user.conversations:
-                print conversation
-                conversation.delete()
-
-            for match in Match.objects.filter(source=user.id):
-                print match
-                match.delete()
-
-            for match in Match.objects.filter(target=user.id):
-                print match
-                match.delete()
-
-            try:
-                user.delete()
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 2
-            else:
-                cn = S3Connection(
-                    settings.AWS_KEY, settings.AWS_SECRET
-                )
-
-                for suffix in ('', '_large', '_medium', '_small', '_tiny'):
-
-                    print '%s/%s%s' % (settings.S3_UPLOAD_PATH_PRODUCT,
-                        user.id, suffix)
-
-                    try:
-                        key = cn.get_bucket(settings.S3_BUCKET_NAME).get_key(
-                            '%s/%s%s' % (settings.S3_UPLOAD_PATH_PRODUCT,
-                                user.id, suffix))
-                        key.delete()
-                    except Exception as exc:
-                        logging.error(exc)
-
-        self.finish({'status_code': status_code})
-
-
-class DeleteImage(BaseHandler):
-
-    #@authenticated
-    def post(self):
-        #if self.request.headers.get('X-Requested-With') != 'XMLHttpRequest':
-            #raise HTTPError(403)
-
-        status_code = 0
-
-        try:
-            user = User.objects.get(self.get_argument('id'))
-        except Exception as exc:
-            logging.error(exc)
-        else:
-
-            cn = S3Connection(
-                settings.AWS_KEY, settings.AWS_SECRET
-            )
-
-            key = cn.get_bucket(settings.S3_BUCKET_NAME).get_key(
-                '%s/%s' % (settings.S3_UPLOAD_PATH_PRODUCT, user.id))
-            key.delete()
-
-        self.finish({'status_code': status_code})
-

controllers/product.py

-import logging
-import datetime
-
-from models import Product, Category, Match, Conversation, Comment
-from controllers import BaseHandler
-from tornado.web import authenticated
-
-from tasks import generate_thumbs
-
-
-class Add(BaseHandler):
-
-    @authenticated
-    def get(self, **kwargs):
-        user = self.get_current_user()
-        kwargs['user'] = user
-        self.render('site/product/add.html', **kwargs)
-
-    @authenticated
-    def post(self):
-        status_code = 0
-
-        title = self.get_argument('title', '')
-        description = self.get_argument('description', '')
-        cost = self.get_argument('cost', '')
-        type = self.get_argument('type', None)
-
-        user = self.get_current_user()
-
-        if not user:
-            self.send_error(404)
-
-        try:
-            cost = int(cost)
-        except Exception as exc:
-            logging.error(exc)
-            cost = 0
-
-        if len(title) < 1 or len(description) < 1:
-            status_code = 1
-        elif not type in ('have', 'want'):
-            status_code = 1
-        else:
-            try:
-                _raw_image = self.request.files['filename'][0]
-            except (KeyError, IndexError) as exc:
-                logging.error(exc)
-                status_code = 1
-
-        if status_code == 0:
-            product = Product()
-            product.title = title
-            product.description = description
-            product.cost = cost
-            product.type = type
-            product.user = user.email
-            #product.set_slug(title)
-
-            try:
-                product.save()
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 5
-            else:
-
-                if not product.upload_img(_raw_image.get('body')):
-                    status_code = 3
-                    logging.error('no upload image')
-                else:
-                    #if not product.send_message_to_generate_thumbs():
-                        #logging.error('no send queue to generate_thumbs')
-                        #status_code = 4
-                    generate_thumbs.delay(product.id)
-                    self.redirect(self.reverse_url('product_edit', product.slug))
-                    return
-
-        self.get(status_code=status_code)
-
-
-class Edit(BaseHandler):
-
-    @authenticated
-    def get(self, slug, **kwargs):
-        user = self.get_current_user()
-
-        try:
-            #product = Product.objects.get(id)
-            product = Product.objects.filter(slug=slug)[0]
-        except:
-            self.send_error(404)
-            return
-
-        """
-        if not product.title:
-            product.title = 'product'
-
-        if not product.description:
-            product.description = 'This is a brief description..'
-
-        if not product.cost:
-            product.cost = 50
-        """
-
-        if not product.will_travel:
-            product.will_travel = 1000
-
-        if product.published_at:
-            try:
-                product.published_at = product.published_at.date()
-            except Exception as exc:
-                logging.error(exc)
-        else:
-            product.published_at = datetime.datetime.now().strftime('%Y-%m-%d')
-
-        """
-        if product.expires_at:
-            try:
-                product.expires_at = product.expires_at.date()
-            except Exception as exc:
-                logging.error(exc)
-        else:
-        """
-
-        if not product.expires_at:
-            product.expires_at = (datetime.datetime.now() + \
-                datetime.timedelta(days=5)).strftime('%Y-%m-%d')
-
-        if not product.location:
-            product.location = 'WC 12 avenue'
-
-        categories = Category.objects.all()
-
-        if not product.categories:
-            product.categories = [u'metarials', u'sporting']
-
-        if product.categories:
-            for x, y in enumerate(categories):
-                if y.title.lower() in product.categories:
-                    categories[x].checked = True
-                else:
-                    categories[x].checked = False
-
-        logging.info('image: %s' % product.image)
-        logging.info('tyny_image: %s' % product.tiny_url)
-        logging.info('small_image: %s' % product.small_url)
-        logging.info('large_image: %s' % product.large_url)
-        logging.info('medium_image: %s' % product.medium_url)
-        logging.info('is_upload_thumbs: %s' % product.is_upload_thumbs)
-
-
-        logging.info(product.allow_charities)
-        logging.info(type(product.allow_charities))
-
-        kwargs['product'] = product
-        kwargs['categories'] = categories
-        kwargs['audiences'] = Product.AUDIENCES_TYPES
-        kwargs['user'] = user
-        kwargs['action'] = 'edit'
-        self.render('site/product/add.html', **kwargs)
-
-    @authenticated
-    def post(self, slug):
-        status_code = 0
-
-        categories = self.get_arguments('categories', None)
-        title = self.get_argument('title', '')
-        description = self.get_argument('description', '')
-        cost = self.get_argument('cost', '')
-        will_travel = self.get_argument('will_travel', '')
-        allow_retailers = self.get_argument('allow_retailers', None)
-        allow_charities = self.get_argument('allow_charities', None)
-        donate_now = self.get_argument('donate_now', None)
-        published_at = self.get_argument('published_at', '')
-        expires_at = self.get_argument('expires_at', '')
-        type = self.get_argument('type', None)
-        location = self.get_argument('location', '')
-        audience = self.get_argument('audience', '')
-
-        try:
-            will_travel = int(will_travel)
-        except Exception as exc:
-            logging.error(exc)
-            will_travel = 0
-
-        try:
-            cost = int(cost)
-        except Exception as exc:
-            logging.error(exc)
-            cost = 0
-
-        user = self.get_current_user()
-
-        if not user:
-            self.send_error(404)
-
-        try:
-            #product = Product.objects.get(id)
-            product = Product.objects.filter(slug=slug)[0]
-        except Exception as exc:
-            self.send_error(404)
-
-        #if len(title) < 1 or len(description) < 1 or len(published_at) < 1:
-        if len(title) < 1 or len(description) < 1:
-            status_code = 1
-        elif not type in ('have', 'want'):
-            status_code = 1
-
-        if status_code == 0:
-            """
-            try:
-                published_at = datetime.datetime.strptime(
-                    published_at, '%Y-%m-%d')
-            except ValueError as exc:
-                logging.error(exc)
-                status_code = 2
-            """
-
-            logging.info(expires_at)
-
-            try:
-                _expires_at = datetime.datetime.strptime(
-                    expires_at, '%Y-%m-%d')
-            except ValueError as exc:
-                logging.error(exc)
-                status_code = 2
-            else:
-                logging.info('_expires_at: %s' % _expires_at)
-
-        if status_code == 0:
-            if not categories:
-                status_code = 4
-
-        if status_code == 0:
-            try:
-                _raw_image = self.request.files['filename'][0]
-            except (KeyError, IndexError) as exc:
-                _raw_image = None
-
-            _status = product.status
-
-            product.title = title
-            product.description = description
-            product.cost = cost
-            product.will_travel = will_travel
-            product.allow_charities = True if allow_charities else False
-            product.allow_retailers = True if allow_retailers else False
-            product.donate_now = True if donate_now else False
-            product.published_at = published_at
-            product.expires_at = expires_at
-            product.type = type
-            product.user = user.email
-            product.categories = categories
-            product.location = location
-            product.audience = audience
-            product.status = 'active'
-            #product.set_slug(title)
-
-            try:
-                product.update()
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 5
-            else:
-                product.save_points(_status)
-
-            if status_code == 0:
-                if _raw_image:
-
-                    if not product.upload_img(_raw_image.get('body')):
-                        status_code = 4
-                    else:
-                        #if not product.send_message_to_generate_thumbs():
-                        #if not product.generate_thumbs():
-                            #logging.error('no generate slug')
-                            #status_code = 4
-                        generate_thumbs.delay(product.id)
-
-                    if status_code == 0:
-                        self.redirect(self.reverse_url('product_edit',
-                            product.id))
-                        return
-
-        logging.info('status_code: %s' % status_code)
-        self.get(slug, status_code=status_code)
-
-
-class View(BaseHandler):
-
-    def get(self, slug):
-
-        product = Product.get_by_slug(slug)
-
-        if not product:
-            self.send_error(404)
-            return
-
-        logging.info('id: %s' % product.id)
-
-        tot_unread_comments = 0
-        conversations = []
-        comments = []
-        is_owner = False
-        user = self.get_current_user()
-
-        if user:
-            is_owner = product.is_owner(user)
-
-            logging.info('is_owner: %s' % is_owner)
-            logging.info('current_user: %s' % user.email)
-            logging.info('product_owner: %s' % product.user)
-
-            if not is_owner:
-                conversation = product.get_conversation(user.email)
-
-                if conversation:
-                    comments = [dict(user=x.user_data.name,
-                        text=x.description,
-                        created_at=x.created_at_f) \
-                            for x in conversation.comments]
-            else:
-
-                for c in product.conversations:
-
-                    _comments = [dict(user=x.user_data.name,
-                        is_owner=1 if x.user == product.user else 0,
-                        text=x.description,
-                        created_at=x.created_at_f) \
-                            for x in c.comments]
-
-                    tot_unread_comments += int(c.unread_comments)
-                    conversations.append(dict(id=c.id,
-                        user=c.user_data.name,
-                        unread_comments=c.unread_comments,
-                        comments=_comments))
-
-        #logging.info('notifications: %s' % product.notifications)
-        logging.info('notifications: %s' % product.expired)
-
-        self.render('site/product/view.html',
-            user=user,
-            product=product,
-            is_owner=is_owner,
-            comments=comments,
-            conversations=conversations,
-            tot_unread_comments=tot_unread_comments)
-
-
-class Delete(BaseHandler):
-
-    @authenticated
-    def post(self, id):
-
-        if self.request.headers.get('X-Requested-With') != 'XMLHttpRequest':
-            logging.error('not from ajax')
-            self.send_error(403)
-            return
-
-        try:
-            product = Product.objects.get(id)
-        except Exception as exc:
-            logging.error(exc)
-            self.send_error(403)
-            return
-
-        status_code = 0
-
-        try:
-            product.delete()
-        except Exception as exc:
-            logging.error(exc)
-            status_code = 1
-
-        self.finish({'status_code': status_code})
-
-
-class SendMessage(View):
-
-    @authenticated
-    def post(self, slug):
-        product = Product.get_by_slug(slug)
-
-        if not product:
-            self.send_error(404)
-            return
-
-        status_code = 0
-        message = self.get_argument('message', '')
-
-        if len(message) < 3:
-            status_code = 1
-        else:
-
-            user = self.get_current_user()
-
-            if product.is_owner(user):
-                self.send_error(404)
-                return
-
-            try:
-                conversation = Conversation.objects.filter(
-                    product=product.id,
-                    with_user=user.email
-                )
-            except Exception as exc:
-                logging.error(exc)
-            else:
-                try:
-                    conversation = conversation[0]
-                except:
-                    pass
-
-            if not conversation:
-                conversation = Conversation()
-                conversation.product = product.id
-                conversation.with_user = user.email
-
-                try:
-                    conversation.save()
-                except Exception as exc:
-                    logging.error(exc)
-                    status_code = 2
-
-            comment = Comment()
-            comment.description = message
-            comment.conversation = conversation.id
-            comment.user = user.email
-
-            try:
-                comment.save()
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 2
-            else:
-                conversation.increase_unread_comments()
-
-                try:
-                    conversation.update()
-                except Exception as exc:
-                    logging.error(exc)
-                    status_code = 2
-
-        logging.info('status_code: %s' % status_code)
-        self.get(slug)
-
-
-class SendMessageOwner(View):
-
-    @authenticated
-    def post(self, slug):
-        product = Product.get_by_slug(slug)
-
-        if not product:
-            self.send_error(404)
-            return
-
-        status_code = 0
-        conversation_id = self.get_argument('conversation_id', None)
-
-        message = self.get_argument('message', '')
-
-        if len(message) < 3 or not conversation_id:
-            status_code = 1
-        else:
-
-            user = self.get_current_user()
-
-            if not product.is_owner(user):
-                self.send_error(404)
-                return
-
-            conversation = Conversation.get(conversation_id)
-
-            if not conversation:
-                self.send_error(404)
-                return
-            else:
-                comment = Comment()
-                comment.description = message
-                comment.conversation = conversation.id
-                comment.user = user.email
-
-                try:
-                    comment.save()
-                except Exception as exc:
-                    logging.error(exc)
-                    status_code = 2
-
-        logging.info('status_code: %s' % status_code)
-        self.get(slug)
-
-
-class ResetUnreadComments(BaseHandler):
-
-    def post(self):
-
-        status_code = 0
-        conversation_id = self.get_argument('conversation_id', None)
-
-        try:
-            conversation = Conversation.objects.get(
-                conversation_id)
-        except Exception as exc:
-            logging.error(exc)
-            status_code = 1
-        else:
-            conversation.unread_comments = 0
-
-            try:
-                conversation.update()
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 1
-
-        self.finish(dict(status_code=status_code))
-
-
-class MatchItems(BaseHandler):
-
-    @authenticated
-    def get(self):
-        status_code = 0
-        #source = want
-        #target = have
-        user = self.get_current_user()
-        product_1 = self.get_argument('product_1', None)
-        product_2 = self.get_argument('product_2', None)
-
-        wait = self.get_argument('wait', None)
-
-        if product_1 == product_2:
-            status_code = 1
-            logging.info('same user!')
-        else:
-            try:
-                product_1 = Product.objects.get(product_1)
-            except Exception as exc:
-                logging.error(exc)
-                self.send_error(404)
-                return
-
-            if wait:
-                if product_1.user == user.email:
-                    logging.info('same user with wait')
-                    status_code = 5
-
-            if status_code == 0:
-
-                try:
-                    product_2 = Product.objects.get(product_2)
-                except Exception as exc:
-                    logging.error(exc)
-                    self.send_error(404)
-                    return
-
-                match = Match.objects.filter(
-                    source=product_1.id,
-                    target=product_2.id,
-                    user=user.email
-                )
-
-                if len(match) < 1:
-                    match = Match()
-                    match.source = product_1.id
-                    match.target = product_2.id
-                    match.user = user.email
-
-                    if wait:
-                        match.status = 'inactive'
-
-                    try:
-                        match.save()
-                    except Exception as exc:
-                        logging.error(exc)
-                        status_code = 2
-                    else:
-
-                        if not wait:
-
-                            match.save_points()
-                            user.score = int(user.score) + 1
-
-                            try:
-                                user.update()
-                            except Exception as exc:
-                                logging.error(exc)
-                                status_code = 4
-                            else:
-                                logging.info('update score')
-                else:
-                    logging.info('Maked!')
-                    status_code = 3
-
-        logging.info('status_code: %s' % status_code)
-        self.finish(dict(status_code=status_code))
-
-
-class ActiveMatch(BaseHandler):
-
-    @authenticated
-    def post(self):
-        status_code = 0
-        id = self.get_argument('id', None)
-
-        if not id:
-            status_code = 1
-        else:
-            try:
-                match = Match.objects.get(id)
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 1
-            else:
-                match.status = 'active'
-                match.type = 'match_have'
-
-                try:
-                    match.update()
-                except Exception as exc:
-                    logging.error(exc)
-                    status_code = 1
-                else:
-                    logging.info('update ok')
-
-        logging.info('status_code: %s' % status_code)
-        self.finish(dict(status_code=status_code))

controllers/user.py

-import logging
-import settings
-
-from tornado.auth import FacebookGraphMixin
-from models import User, Product
-from controllers import BaseHandler
-from tornado.web import authenticated, asynchronous
-from tasks import send_email
-from utils import check_email
-
-
-class Add(BaseHandler):
-
-    def get(self, **kwargs):
-        self.render('site/user/add.html', **kwargs)
-
-    def post(self):
-        status_code = 0
-        name = self.get_argument('name', '')
-        lastname = self.get_argument('lastname', '')
-        gender = self.get_argument('gender', None)
-        password = self.get_argument('password', '')
-        confirm_password = self.get_argument('confirm_password', '')
-        email = self.get_argument('email', '')
-
-        if len(name) < 1 or len(lastname) < 1 or \
-            len(password) < 1 or len(email) < 1:
-            status_code = 1
-        elif not (password == confirm_password):
-            status_code = 2
-        elif not check_email(email):
-            status_code = 3
-        elif not gender in ('male', 'female'):
-            status_code = 4
-        elif User.email_exists(email):
-            status_code = 5
-
-        if status_code == 0:
-            user = User()
-            user.email = email
-            user.password = password
-            user.name = name
-            user.lastname = lastname
-            user.gender = gender
-            user.activation = User.get_token('activation')
-            user.activation_passwd = User.get_token('activation_passwd')
-
-            try:
-                user.save()
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 6
-            else:
-                content = self.render_string(
-                    "mail/confirmation.html",
-                    first_name=name,
-                    last_name=lastname,
-                    url=self.reverse_url("user_activate",
-                        user.activation),
-                    settings=self.settings
-                )
-
-                mail = dict(sender=settings.AWS_EMAIL_FROM,
-                    subject='Registration confirmation',
-                    body=content,
-                    to=['m4cf1.server@gmail.com']
-                )
-
-                send_email.delay(mail)
-                status_code = 7
-
-        self.get(status_code=status_code)
-
-
-class Edit(BaseHandler):
-
-    @authenticated
-    def get(self, **kwargs):
-
-        user = self.get_current_user()
-        kwargs['user'] = user
-        self.render('site/user/add.html', **kwargs)
-
-    @authenticated
-    def post(self):
-        status_code = 0
-        name = self.get_argument('name', '')
-        lastname = self.get_argument('lastname', '')
-        gender = self.get_argument('gender', None)
-        password = self.get_argument('password', '')
-        confirm_password = self.get_argument('confirm_password', '')
-        user = self.get_current_user()
-
-        if len(name) < 1 or len(lastname) < 1:
-            status_code = 1
-        elif len(password) > 0:
-            if not (password == confirm_password):
-                status_code = 2
-        elif gender not in ('male', 'female'):
-            status_code = 4
-
-        if status_code == 0:
-            if password:
-                user.set_password(password)
-
-            user.name = name
-            user.lastname = lastname
-            user.gender = gender
-
-            try:
-                user.update()
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 6
-            else:
-                status_code = 8
-
-        self.get(status_code=status_code)
-
-
-class Activate(BaseHandler):
-    def get(self, token):
-        try:
-            user = User.objects.filter(activation=token)[0]
-        except Exception as exc:
-            logging.error(exc)
-            self.send_error(404)
-            return
-        else:
-            user.status = 'active'
-            #user.token = ''
-            user.activation = ''
-
-            try:
-                user.update()
-            except Exception as exc:
-                logging.error(exc)
-                self.send_error(409)
-                return
-
-        self.set_secure_cookie('user', user.email)
-        self.redirect(self.reverse_url("home"))
-        return
-
-
-class SetPasswordFacebook(BaseHandler):
-    def get(self, token, **kwargs):
-
-        status_code = None
-
-        if 'status_code' in kwargs:
-            status_code = kwargs['status_code']
-
-        try:
-            user = User.objects.filter(
-                activation_passwd_facebook=token)[0]
-        except Exception as exc:
-            logging.error(exc)
-            self.send_error(404)
-            return
-        else:
-            logging.info(user.email)
-
-        #self.set_secure_cookie('token_facebook',
-            #user.activation_passwd_facebook)
-        self.render('site/user/facebook/set_password.html',
-            status_code=status_code)
-
-    def post(self, token):
-
-        status_code = 0
-
-        try:
-            user = User.objects.filter(
-                activation_passwd_facebook=token)[0]
-        except Exception as exc:
-            logging.error(exc)
-            self.send_error(404)
-            return
-
-        password = self.get_argument('password', '')
-
-        if len(password) < 1:
-            status_code = 1
-        else:
-
-            user.set_password(password)
-            #user.password = password
-
-            try:
-                user.update()
-            except Exception as exc:
-                status_code = 2
-                logging.error(exc)
-                #self.send_error(409)
-                #return
-            else:
-
-                user.activation_passwd_facebook = ''
-
-                try:
-                    user.update()
-                except Exception as exc:
-                    #status_code = 3
-                    logging.error(exc)
-
-                self.set_secure_cookie('user', user.email)
-                self.redirect(self.reverse_url("home"))
-                return
-
-        self.get(token, status_code=status_code)
-
-
-class Login(BaseHandler):
-
-    def get(self, **kwargs):
-        self.render('site/user/login.html', **kwargs)
-
-    def post(self):
-        status_code = 0
-        email = self.get_argument('email', '')
-        password = self.get_argument('password', '')
-
-        if len(email) < 5 or len(password) < 1:
-            status_code = 1
-        elif not check_email(email):
-            status_code = 1
-
-        if status_code == 0:
-            if User.auth(email, password):
-                self.set_secure_cookie('user', email)
-                #self.redirect(self.reverse_url('home'))
-                #return
-            else:
-                status_code = 2
-
-        logging.info('status_code: %s' % status_code)
-        self.finish(dict(status_code=status_code))
-        #self.get(status_code=status_code)
-
-
-class LoginFacebook(FacebookGraphMixin, BaseHandler):
-
-    @asynchronous
-    def get(self):
-        url = "%s://%s%s" % (
-            self.request.protocol,
-            self.request.host,
-            self.reverse_url("user_login_facebook")
-        )
-
-        if self.get_argument('code', None):
-            self.get_authenticated_user(
-                redirect_uri=url,
-                client_id=self.settings['facebook_api_key'],
-                client_secret=self.settings['facebook_secret'],
-                code=self.get_argument('code'),
-                callback=self._on_auth,
-            )
-            return
-
-        self.authorize_redirect(
-            redirect_uri=url,
-            client_id=self.settings['facebook_api_key'],
-            extra_params={"scope": "email"}
-        )
-
-    def _on_auth(self, user):
-        if not user:
-            self.send_error(500)
-        else:
-            self.facebook_request(
-                '/me',
-                self._on_stream,
-                access_token=user['access_token']
-            )
-        return
-
-    def _on_stream(self, data):
-        if not data:
-            self.send_error(500)
-            return
-
-        save_ok = True
-        email = data['email']
-
-        if not User.email_exists(email):
-            logging.info('save fb_user')
-            user = User()
-            user.email = email
-            user.name = data['first_name']
-            user.lastname = '%s %s' % (
-                data['middle_name'], data['last_name'])
-            user.gender = data['gender']
-            user.facebook_id = data['id']
-            user.status = 'active'
-            user.activation_passwd_facebook = User.get_token(
-                'activation_passwd_facebook')
-
-            try:
-                user.save()
-            except Exception as exc:
-                save_ok = False
-                logging.error(exc)
-            else:
-
-                content = self.render_string(
-                    "mail/set_passwd_facebook.html",
-                    first_name=user.name,
-                    last_name=user.lastname,
-                    url=self.reverse_url("user_set_password_facebook",
-                        user.activation_passwd_facebook),
-                    settings=self.settings
-                )
-
-                mail = dict(sender=settings.AWS_EMAIL_FROM,
-                    subject='Set Password',
-                    body=content,
-                    to=['m4cf1.server@gmail.com']
-                )
-
-                #logging.info('send email 1')
-                send_email.delay(mail)
-                #logging.info('send email 2')
-
-                self.redirect(self.reverse_url('confirmation'))
-
-        else:
-            logging.info('exits email')
-            user = User.objects.get(email)
-
-            if not user.facebook_id:
-                logging.info('exists email but not fbid')
-                user.facebook_id = data.get('id')
-
-                try:
-                    user.update()
-                except Exception as exc:
-                    save_ok = False
-                    logging.error(exc)
-
-        if save_ok:
-            self.set_secure_cookie('user', email)
-            self.redirect(self.reverse_url('home'))
-        else:
-            self.render('site/user/login.html', status_code=2)
-        return
-
-
-class Logout(BaseHandler):
-
-    def get(self):
-        self.clear_cookie("user")
-        self.redirect(self.reverse_url('home'))
-
-
-class ForgotPassword(BaseHandler):
-
-    def get(self, **kwargs):
-        self.render('site/user/forgot_password.html', **kwargs)
-
-    def post(self):
-        status_code = 0
-        email = self.get_argument('email', '')
-
-        if len(email) < 4 or not check_email(email):
-            status_code = 1
-        else:
-            try:
-                user = User.objects.get(email)
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 2
-            else:
-                user.activation_passwd = User.get_token('activation_passwd')
-
-                try:
-                    user.update()
-                except Exception as exc:
-                    logging.error(exc)
-                else:
-                    content = self.render_string(
-                        "mail/change_password.html",
-                        first_name=user.name,
-                        last_name=user.lastname,
-                        url=self.reverse_url("user_change_password",
-                                user.activation_passwd),
-                        settings=self.settings
-                    )
-
-                    # override for testing
-                    email = 'm4cf1.server@gmail.com'
-
-                    mail = dict(sender=settings.AWS_EMAIL_FROM,
-                        subject='Change password',
-                        body=content,
-                        to=[email]
-                    )
-
-                    send_email.delay(mail)
-                    status_code = 3
-
-        self.get(status_code=status_code)
-
-
-class ChangePassword(BaseHandler):
-
-    def get(self, token, **kwargs):
-        try:
-            user = User.objects.filter(activation_passwd=token)[0]
-        except:
-            self.send_error(405)
-            return
-        else:
-            self.set_cookie('token_pwd', user.activation_passwd)
-        self.render('site/user/change_password.html', **kwargs)
-
-    def post(self, token, **kwargs):
-        status_code = 0
-        password = self.get_argument('password', '')
-        confirm_password = self.get_argument('confirm_password', '')
-
-        try:
-            user = User.objects.filter(activation_passwd=token)[0]
-        except:
-            self.send_error(405)
-            return
-
-        if len(password) < 4 or len(confirm_password) < 4:
-            status_code = 1
-        elif not (password == confirm_password):
-            status_code = 2
-
-        if status_code == 0:
-            user.set_password(password)
-
-            try:
-                user.update()
-            except Exception as exc:
-                logging.error(exc)
-                status_code = 3
-            else:
-                self.clear_cookie('token_pwd')
-                status_code = 4
-
-        self.get(token, status_code=status_code)
-
-
-class HaveProducts(BaseHandler):
-
-    @authenticated
-    def get(self):
-
-        products = Product.objects.filter(type='have', status='active')
-
-        page = self.get_argument('page', 1)
-        limit = self.get_argument('limit', 10)
-
-        try:
-            page = int(page)
-        except Exception as exc:
-            logging.error(exc)
-            page = 1
-        else:
-            if page < 1:
-                page = 1
-
-        try:
-            limit = int(limit)
-        except Exception as exc:
-            logging.error(exc)
-            limit = 10
-
-        user = self.get_current_user()
-        products = products.filter(user=user.email)
-
-        offset = (page - 1) * limit
-        limit = page * limit
-
-        self.render('site/user/have_products.html', products=products)
-
-
-class Confirmation(BaseHandler):
-
-    def get(self):
-        self.render('site/user/facebook/confirmation.html')

create_categories.py

-from models import Category
-
-CATEGORIES = ('APLIANCES', 'ANTIQUES', 'BARKER', 'BIKES', 'BOATS', 'BOOKS',
-'BUSINESS', 'COMPUTER', 'FREE', 'FURNITURE', 'GENERAL', 'JEWELRY',
-'METARIALS', 'RVS', 'SPORTING', 'TICKETS', 'TOOLS', 'WANTED')
-
-for x in CATEGORIES:
-    cat = Category()
-    cat.title = x
-    cat.status = 'enabled'
-    cat.save()

delete_domain.py

-import sys
-import settings
-
-from simpledb import SimpleDB
-
-sdb = SimpleDB(settings.AWS_KEY, settings.AWS_SECRET)
-
-if len(sys.argv) > 1:
-    del sdb[sys.argv[1]]

frontend/build.js

-function building() {
-  var build = require('building');
-  
-  var destino = __dirname + '/..';
-  build.prepare({
-    remove: [
-      destino + '/static'
-    ],
-    create: [
-      destino + '/static/js',
-      //destino + '/static/js/libs',
-      destino + '/static/css'
-    ]
-  });
-
-
-  // template
-  build.templates({
-    jade: { 
-      pretty: true
-    },
-    origin: __dirname + '/templates',
-    destino: destino + '/templates/site',
-    validFile: function(file) {
-      return file.indexOf('_') === -1 &&
-        file.indexOf('layout') === -1 &&
-        file.indexOf('base.jade') === -1;
-    }
-  });
-
-  //build.javascript({
-    //origin: __dirname + '/static/js/site.home.js',
-    //destino: destino + '/static/js/site.home.js'
-  //});
-
-  //build.copy(
-    //__dirname + '/static/js/libs/',
-     //destino + '/static/js/libs/'
-  //);
-  build.copy(
-    __dirname + '/static/js/',
-     destino + '/static/js/'
-  );
-
-
-  build.styles({
-    origin: __dirname + '/static/css/site.styl',
-    destino: destino + '/static/css/site.css'
-  });
-
-  build.copy(
-    __dirname + '/static/images',
-     destino + '/static/images'
-  );
-
-  build.copy(
-    __dirname + '/static/fonts',
-     destino + '/static/fonts'
-  );
-}
-
-exports.building = building;
-
-building();

frontend/node_modules/building/index.js

-(function() {
-  var fs = require('fs');
-  var util = require('util');
-  var jade = require('jade');
-  var mkdirp = require('mkdirp');
-  var uglifyjs = require('uglify-js');
-  var findit = require('findit');
-  var stylus = require('stylus');
-  var path = require('path');
-  var basename = path.basename;
-  var dirname = path.dirname;
-  var resolve = path.resolve;
-  var wrench = require('wrench');
-  
-  var color = require('color');
-
-  /* Recorre el sistema de archivos buscando carpetas y archivos */
-  function FI() {