Пример #1
0
def post_feed():
    """
    Insert feed
    """
    data = request.get_json(silent=True)
    type = data['type']
    if type == 1:
        video = data['video']
        title = video['title']
        description = video['description']
        url = video['url']
        v_result = Video.create(title=title, description=description, url=url)

    if type == 2:
        photo = data['photo']
        title = photo['title']
        description = photo['description']
        url = photo['url']
        Photo.create(title=title, description=description, url=url)

    if type == 3:
        article = data['news']

    print(data)

    if 'name' in data and 'description' in data and 'slug' in data:
        name = data['name']
        description = data['description']
        slug = data['slug']
        Feed.create(name=name, description=description, slug=slug)
        return make_response(jsonify({'success': True, 'result': 'Category Created'}), 201)
    else:
        return make_response(jsonify({'success': False, 'result': 'Incomplete parameters'}), 400)
 def create(self, payloads):
     response = ResponseBuilder()
     feed = Feed()
     sponsor = db.session.query(Sponsor).filter_by(
         id=payloads['sponsor_id']).first()
     attachment = self.save_file(
         payloads['attachment']
     ) if payloads['attachment'] is not None else None
     feed.message = payloads['message']
     feed.attachment = attachment
     feed.user_id = payloads['user_id']
     feed.type = payloads['type']
     feed.redirect_url = payloads['redirect_url']
     feed.sponsor_id = payloads['sponsor_id']
     db.session.add(feed)
     try:
         db.session.commit()
         user = feed.user.include_photos().as_dict()
         del user['fcmtoken']
         data = feed.as_dict()
         data['attachment'] = Helper().url_helper(
             data['attachment'], current_app.config['GET_DEST']
         ) if data['attachment'] is not None else None
         if 'user' in payloads['type']:
             data['user'] = user
         elif 'sponsor' in payloads['type']:
             data['user'] = sponsor.as_dict()
         return response.set_data(data).build()
     except SQLAlchemyError as e:
         data = e.orig.args
         return response.set_data(data).set_error(True).build()
Пример #3
0
    def create_feed(cls, db, mc, cfg, user_id):
        def get_random_key():
            return ''.join(
                random.SystemRandom().choice(string.ascii_lowercase +
                                             string.ascii_uppercase +
                                             string.digits) for _ in range(12))

        try:
            # get user details from Google Plus
            service = cls._get_plus_service(cfg.get('feed.api_key'))
            person = service.people().get(userId=user_id).execute()

            # change photo size
            photo_url_site = person['image']['url']
            photo_url_db = person['image']['url']
            idx = photo_url_site.index('?')
            if idx != -1:
                photo_url_site = '%s?sz=%s' % (
                    photo_url_site[:idx], cfg.get('feed.photo_size.website'))
                photo_url_db = '%s?sz=%s' % (
                    photo_url_db[:idx], cfg.get('feed.photo_size.database'))

            # check feed existence
            uid = person['id']
            feed = Feed.get_by_user_id(db, uid)
            if not feed:
                # create a new feed
                rnd_key = get_random_key()
                while Feed.get_by_pkey(db, rnd_key):
                    rnd_key = get_random_key()
                feed = Feed(rnd_key, uid)
                feed.save(db)

            else:
                mc.delete(cls.MEMCACHE_KEY % feed.pkey)

            # update photo
            feed.photo_url = photo_url_db
            feed.save(db)

            return {
                'pkey': feed.pkey,
                'photo': photo_url_site,
                'name': person['displayName']
            }

        except HttpError as e:
            if e.resp.status == 404:
                raise cls.UserIdNotFoundException
            raise e
Пример #4
0
	def sponsor_create(self, payloads):
		response = ResponseBuilder()
		feed = Feed()
		for key in payloads:
			setattr(feed, key, payloads[key])
		db.session.add(feed)
		try:
			db.session.commit()
			user = feed.user.include_photos().as_dict()
			sponsor = db.session.query(Sponsor).filter_by(id=payloads['sponsor_id']).first()		
			del user['fcmtoken']
			data = feed.as_dict()
			data['attachment'] = Helper().url_helper(data['attachment'], current_app.config['GET_DEST']) if data['attachment'] is not None else None
			if 'user' in payloads['type']:
				data['user'] = user
			elif 'sponsor' in payloads['type']:
				data['user'] = sponsor.as_dict()
			return response.set_data(data).build()
		except SQLAlchemyError as e:
			data = e.orig.args
			return response.set_data(data).set_error(True).build()
Пример #5
0
def submit():
    form = SubmissionForm()
    if form.validate_on_submit():
        if current_user.is_authenticated:
            feed = Feed(
                owner=form.owner.data,
                rss=form.rss.data,
                html=form.html.data,
                user_id=current_user.id,
            )
            db.session.add(feed)
            db.session.commit()
        return redirect(url_for("home.index"))
    return render_template("/feed/submit.html", title="submission", form=form)
Пример #6
0
    def create_feed(cls, db, mc, cfg, user_id):
        def get_random_key():
            return ''.join(
                random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in
                range(12))

        service = cls._get_plus_service(cfg.get('feed.credentials_file'), cfg.get('feed.cache_dir'))
        try:
            # get user details from Google Plus
            person = service.people().get(userId=user_id).execute()

            # change photo size
            photo_url_site = person['image']['url']
            photo_url_db = person['image']['url']
            idx = photo_url_site.index('?')
            if idx != -1:
                photo_url_site = '%s?sz=%s' % (photo_url_site[:idx], cfg.get('feed.photo_size.website'))
                photo_url_db = '%s?sz=%s' % (photo_url_db[:idx], cfg.get('feed.photo_size.database'))

            # check feed existence
            uid = person['id']
            feed = Feed.get_by_user_id(db, uid)
            if not feed:
                # create a new feed
                rnd_key = get_random_key()
                while Feed.get_by_pkey(db, rnd_key):
                    rnd_key = get_random_key()
                feed = Feed(rnd_key, uid)
                feed.save(db)

            else:
                mc.delete(str(cls.MEMCACHE_KEY % feed.pkey))

            # update photo
            feed.photo_url = photo_url_db
            feed.save(db)

            return {'pkey': feed.pkey, 'photo': photo_url_site, 'name': person['displayName']}

        except HttpError as e:
            if e.resp.status == 404:
                raise cls.UserIdNotFoundException
            raise e

        finally:
            del service
Пример #7
0
def get_feed(id):
    """
    Fetch shopping_list
    """

    query = Feed.objects(id=UUID(id))
    if query.count > 0:
        data = {'results': []}
        i = 0
        for instance in query:
            data['results'].append({'id': instance.id,
                                    'title': instance.title,
                                    'slug': instance.slug,
                                    'description': instance.description,
                                    'created_at': instance.created_at})
            i += 1
            if i == query.count():
                return make_response(jsonify({'success': True, 'results': data['results']}), 200)
    else:
        return make_response(jsonify({'success': True, 'results': []}), 204)
Пример #8
0
def submit_feed_form():
    print(request.form)
    form_data = request.get_json()
    print(form_data)
    if form_data is not None and form_data.get('formData') is not None:
        duck_feed_form = DuckFeedForm()
        validation_result = duck_feed_form.is_valid(form_data.get('formData'))
        if validation_result.get('valid') is False:
            return jsonify({'success': False, 'message':validation_result.get('message')}), 400
        # validation successful
        permitted_params = duck_feed_form.get_permitted_params(form_data.get('formData'))
        try:
            permitted_params['feedTime'] = datetime.strptime(permitted_params.pop('dateTime'), '%Y-%m-%dT%H:%M:%S.%fZ')
        except Exception as e:
            return jsonify({'success': False, 'message': 'Bad request. Invalid format of dateTime. Expected format is %Y-%m-%dT%H:%M:%S.%fZ'}), 400
            print(e)
        print(permitted_params)
        # insert in mongo
        feed_id = Feed().insert_one(permitted_params)
        if feed_id is not None:
            return jsonify({'success': True, 'message':'Feed Form successfully submitted', 'feed_id':str(feed_id)}), 200
        else:
            return jsonify({'success': False, 'message': 'Error while submitting feed form data'}), 400
    return jsonify({'success': False, 'message':'Bad request. Form data cannot be empty'}), 400
Пример #9
0
def get_feed_form_submissions():
    form_data = Feed().fetch_all()
    if form_data is not None:
        return jsonify({'success': True, 'message':'successfully fetched feed form data', 'data':form_data}), 200
    else:
        return jsonify({'success': False, 'message': 'Something went wrong.'}), 400
Пример #10
0
    def get_feed_activities(cls, db, mc, cfg, pkey):
        def process_activity_data(atv):
            # check re-shared post
            title = ''
            content = ''
            url = ''
            if atv['actorId'] != user_id:
                # check attachment
                if atv['hasAttachment']:
                    # check comment
                    if atv['hasComment']:
                        if 'comment' in atv:
                            title = atv['comment']
                        if 'attachmentTitle' in atv:
                            content = atv['attachmentTitle']
                        if 'attachmentUrl' in atv:
                            url = atv['attachmentUrl']

                    else:
                        if 'attachmentTitle' in atv:
                            title = atv['attachmentTitle']
                        if 'attachmentContent' in atv:
                            content = atv['attachmentContent']
                        if 'attachmentUrl' in atv:
                            url = atv['attachmentUrl']
                else:
                    # set only title and content
                    if 'title' in atv and atv['title'] != '':
                        title = atv['title']
                    if 'content' in atv and atv['content'] != '':
                        content = atv['content']

            else:
                if 'title' in atv and atv['title'] != '':
                    title = atv['title']
                elif atv['hasAttachment'] and 'attachmentTitle' in atv:
                    title = atv['attachmentTitle']

                if 'content' in atv and atv['content'] != '':
                    content = atv['content']
                elif atv['hasAttachment'] and 'attachmentContent' in atv:
                    content = atv['attachmentContent']

                if atv['hasAttachment'] and 'attachmentUrl' in atv:
                    url = atv['attachmentUrl']

            # update activity
            atv['title'] = title
            atv['content'] = content
            if url is not None and url != '':
                atv['url'] = url

        # check memcache for existing value
        m_key = str(cls.MEMCACHE_KEY % pkey)
        feed = mc.get(m_key)
        if not feed:
            # load feed from DB
            db_feed = Feed.get_by_pkey(db, pkey)
            if not db_feed:
                db_feed = 404
            mc.set(m_key, db_feed)
            del feed
            feed = db_feed

        if feed == 404:
            raise cls.FeedNotFoundException()

        user_id = feed.user_id
        photo_url = feed.photo_url
        del feed

        service = cls._get_plus_service(cfg.get('feed.credentials_file'), cfg.get('feed.cache_dir'))
        try:
            # get user activities
            obj = service.activities().list(userId=user_id, collection='public', maxResults='5').execute()

        except HttpError as e:
            if e.resp.status == 404:
                raise cls.UserIdNotFoundException
            raise e

        finally:
            del service

        # parse activities
        activities = []
        name = None
        for item in obj.get('items'):
            # compose activity
            activity = {'id': item['id'], 'url': item['url'], 'title': item['title'],
                        'content': item['object']['content'],
                        'datePublished': item['published'], 'actorId': item['actor']['id'],
                        'hasAttachment': 'attachments' in item['object'] and len(item['object']['attachments']) > 0,
                        'hasComment': 'annotation' in item}

            # check annotation
            if activity['hasComment']:
                activity['comment'] = item['annotation']

            # check geocode
            if 'geocode' in item:
                c = item['geocode'].split(' ')

                activity['hasCoordinates'] = True
                activity['latitude'] = c[0]
                activity['longitude'] = c[1]

            else:
                activity['hasCoordinates'] = False

            # in case set attachment data
            temp_url = None
            if activity['hasAttachment']:
                # check different actor
                if 'actor' in item['object'] and 'id' in item['object']['actor']:
                    activity['actorId'] = item['object']['actor']['id']

                # scroll attachments
                for attachment in item['object']['attachments']:
                    # check attachment type
                    if 'objectType' in attachment and attachment['objectType'] == 'article':
                        # article

                        activity['attachmentTitle'] = attachment.get('displayName', '')
                        activity['attachmentContent'] = attachment.get('content', '')
                        activity['attachmentUrl'] = attachment.get('url', '')

                    elif 'objectType' in attachment and attachment['objectType'] == 'photo':
                        # photo

                        temp_url = attachment['url']
                        if 'fullImage' in attachment:
                            if 'url' in attachment['fullImage']:
                                activity['imageUrl'] = attachment['fullImage']['url']
                            if 'width' in attachment['fullImage']:
                                activity['imageWidth'] = str(attachment['fullImage']['width'])
                            if 'height' in attachment['fullImage']:
                                activity['imageHeight'] = str(attachment['fullImage']['height'])

                        else:
                            if 'url' in attachment['image']:
                                activity['imageUrl'] = attachment['image']['url']
                            if 'width' in attachment['image']:
                                activity['imageWidth'] = str(attachment['image']['width'])
                            if 'height' in attachment['image']:
                                activity['imageHeight'] = str(attachment['image']['height'])

                # check activity URL
                if 'attachmentUrl' not in activity and temp_url is not None:
                    activity['attachmentUrl'] = temp_url

            if name is None and item['actor']['id'] == user_id:
                name = item['actor']['displayName']

            process_activity_data(activity)
            activities.append(activity)

        del obj
        return {'name': name or 'unknown', 'activities': activities, 'user_id': user_id, 'photo_url': photo_url}