Exemplo n.º 1
0
def startSession():
    if 'android_id' in request.args:
        android_id = request.args.get('android_id')
        if android_id in []:
            return jsonify({'debug': 'True', 'ip': '52.74.20.228'})

    # VERSION SPECIFIC
    app_version = int(request.headers.get(
        'App-Version')) if 'App-Version' in request.headers else 0

    # Search().getContentData(key="recommendations")
    # Search().getContentData(key="most_searched")

    reading_multiplier = webapp.config[
        'NEW_READING_RATE'] if app_version >= 6030000 else webapp.config[
            'NEW_READING_RATE'] - 0.01
    data = {
        'most_searched': Collection(4).getObj()['items'],
        'recommendations': Collection(5).getObj()['items'],
        'categories': Search.getSearchCategoriesForApp(),
        'return_days': webapp.config['DEFAULT_RETURN_DAYS'],
        'reading_multiplier': reading_multiplier,
        'time_slots': Order.getTimeSlotsForOrder(),
        'user_model': None
    }

    if 'user_id' in request.args:
        user_id = request.args.get('user_id')
        if user_id and int(user_id) > -1:
            user = User(user_id)
            user.getOrderSlots()
            data['user_model'] = user.getObj()
            user.logMetadata(app_version)
    return jsonify(data)
Exemplo n.º 2
0
def copy_collection_from(
    user: InternalUserDTO, src_collection_uuid: UUID, dst_collection_uuid: UUID,
) -> CollectionDTO:
    try:
        src_collection = Collection.find_readable_or_fail(user, src_collection_uuid)
    except ModelNotFoundError:
        raise PermissionError()

    copy_items_by_collection_uuid(src_collection_uuid, dst_collection_uuid)
    src_collection.session.commit()
    collection = Collection.find_readable_or_fail(user, dst_collection_uuid)
    return to_model(collection, CollectionDTO)
Exemplo n.º 3
0
def copy_collection_to_new(
    user: InternalUserDTO, src_collection_uuid: UUID, dst_collection_dto: CollectionDTO,
) -> CollectionDTO:
    try:
        src_collection = Collection.find_readable_or_fail(user, src_collection_uuid)
    except ModelNotFoundError:
        raise PermissionError()

    dst_collection_dto.provider_uuid = user.provider_uuid
    dst_collection = Collection.create(**dst_collection_dto.to_dict())
    copy_items_by_collection_uuid(src_collection_uuid, dst_collection.uuid)
    src_collection.session.commit()
    return to_model(dst_collection, CollectionDTO)
Exemplo n.º 4
0
 def test_tv_items_query(self):
     u = User(username='******', password='******', email='*****@*****.**')
     tv1 = TV(name='a',
              serialized='1',
              img_sm='/',
              new_episode=3,
              update_detail='w:1')
     tv2 = TV(name='b',
              serialized='1',
              img_sm='/',
              new_episode=4,
              update_detail='w:2')
     tv3 = TV(name='c',
              serialized='1',
              img_sm='/',
              new_episode=5,
              update_detail='w:3')
     db.session.add(u)
     db.session.add(tv1)
     db.session.add(tv2)
     db.session.add(tv3)
     db.session.commit()
     c = Collection(user_id=u.id, name='w')
     c.add_tv(tv1)
     c.add_tv(tv2)
     c.add_tv(tv3)
     db.session.commit()
     r = c.tv_items_query()
     assert isinstance(r, BaseQuery)
     for i in r.all():
         assert i in c.tv_items_list()
Exemplo n.º 5
0
 def test_tv_items_list(self):
     u = User(username='******', password='******', email='*****@*****.**')
     tv1 = TV(name='a',
              serialized='1',
              img_sm='/',
              new_episode=3,
              update_detail='w:1')
     tv2 = TV(name='b',
              serialized='1',
              img_sm='/',
              new_episode=4,
              update_detail='w:2')
     tv3 = TV(name='c',
              serialized='1',
              img_sm='/',
              new_episode=5,
              update_detail='w:3')
     db.session.add(u)
     db.session.add(tv1)
     db.session.add(tv2)
     db.session.add(tv3)
     db.session.commit()
     c = Collection(user_id=u.id, name='w')
     c.add_tv(tv1)
     c.add_tv(tv2)
     c.add_tv(tv3)
     db.session.commit()
     r = c.tv_items_list()
     r_id = [i.id for i in r]
     assert isinstance(r, list)
     assert tv1.id in r_id
     assert tv2.id in r_id
     assert tv3.id in r_id
     assert len(r) == 3
Exemplo n.º 6
0
 def test_remove_tv(self):
     u = User(username='******', password='******', email='*****@*****.**')
     tv1 = TV(name='a',
              serialized='1',
              img_sm='/',
              new_episode=3,
              update_detail='w:1')
     tv2 = TV(name='b',
              serialized='1',
              img_sm='/',
              new_episode=4,
              update_detail='w:2')
     tv3 = TV(name='c',
              serialized='1',
              img_sm='/',
              new_episode=5,
              update_detail='w:3')
     db.session.add(u)
     db.session.add(tv1)
     db.session.add(tv2)
     db.session.add(tv3)
     db.session.commit()
     c = Collection(user_id=u.id, name='w')
     c.add_tv(tv1)
     c.add_tv(tv2)
     c.add_tv(tv3)
     db.session.commit()
     c.remove_tv(tv1)
     db.session.commit()
     assert c.tv == '2;3'
     c.remove_tv(2)
     db.session.commit()
     assert c.tv == '3'
     with pytest.raises(ValueError):
         c.remove_tv('a')
Exemplo n.º 7
0
def add_collection(current_user):
  if not check_session():
    return jsonify({'message': 'You are not logged in!', 'isLoggedIn': False})
  request_data = request.get_json(silent=True, force=True)
  if not (request_data or request_data['name']):

    return jsonify({'message': 'Something went wrong!', 'isAdded': False})
  
  same_named_collection = None
  for collection in current_user.collections:
    if collection.name == request_data['name']:
      same_named_collection = collection
      break
  
  if same_named_collection:
    return jsonify({'message': 'You already have collection named'+request_data['name'], 'isAdded': False})

  new_collection = Collection(name=request_data['name'])
  db.session.add(new_collection)
  current_user.collections.append(new_collection)
  db.session.commit()

  new_collection_response = {"id": new_collection.id, "name": new_collection.name, "createdAt": new_collection.createdAt, "updatedAt": new_collection.updatedAt, "translationsQuantity": 0, "learnedQuantity": 0}

  return jsonify({'isAdded': True, 'newCollection': new_collection_response})
Exemplo n.º 8
0
    def save_data(self, movie_data_list, collections_list, genre_data_list,
                  production_companies_list, production_countries_list):
        movie_objects = Movie.get_or_create(*movie_data_list)

        for n, movie in enumerate(movie_objects):
            if collections_list[n] is not None:
                collection_object = Collection.get_or_create(
                    collections_list[n])[0]
                movie.is_part_of.connect(collection_object)

        for n, genres in enumerate(genre_data_list):
            movie = movie_objects[n]
            genres_objects = Genre.get_or_create(*genres)
            [movie.genres.connect(genre) for genre in genres_objects]

        for n, production_companies in enumerate(production_companies_list):
            movie = movie_objects[n]
            production_companies_objects = ProductionCompany.get_or_create(
                *production_companies)
            [
                movie.produced_by.connect(production_company)
                for production_company in production_companies_objects
            ]

        for n, production_country in enumerate(production_countries_list):
            movie = movie_objects[n]
            production_country_objects = ProductionCountry.get_or_create(
                *production_country)
            [
                movie.produced_in.connect(production_country)
                for production_country in production_country_objects
            ]
Exemplo n.º 9
0
    def get(self, collection_uid=None):
        """Get a list of a user's collections, or """
        request_args = get_current_request_args()

        user_uid = request_args.get('user_uid')

        if user_uid is not None:
            user = User.get_not_deleted(uid=user_uid)
            if user is None:
                raise ResourceNotFound('User not found')

        else:
            user = get_current_user()

        if collection_uid is not None:
            collection = Collection.get_not_deleted(uid=collection_uid,
                                                    user_id=user.id)

            if collection is None:
                raise ResourceNotFound('Collection not found')

            return api_success_response(collection.as_json())

        pagination = user.collections.paginate()

        return api_success_response(
            data=[collection.as_json() for collection in pagination.items()],
            meta=pagination.meta)
Exemplo n.º 10
0
    def create_collection(params):
        """Create a collection and return the ORM object of the collection
        created"""
        collection = Collection(**params)
        collection.save()

        return collection
Exemplo n.º 11
0
def create_collection_items(
    user: InternalUserDTO,
    collection_uuid: UUID,
    items: List[ItemDTO],
    replace: bool = False,
) -> List[ItemDTO]:
    collection = Collection.find_writeable_or_fail(user, collection_uuid)

    if replace:
        Item.where(collection_uuid=collection.uuid).delete()
    new_items: List[Item] = [
        Item(**{
            **item.to_dict(),
            **{
                "uuid": uuid4()
            }
        }) for item in items
    ]
    Item.session.bulk_save_objects(new_items)
    Item.session.commit()
    uuids = []
    for item in new_items:
        if isinstance(item.uuid, str):
            uuids.append(UUID(item.uuid))
        else:
            uuids.append(item.uuid)
    fetched_items = Item.find_writeable(user, uuids)
    return to_models(fetched_items, ItemDTO)
Exemplo n.º 12
0
def collect_blog(blog_id):
    collection = Collection(UserID=current_user.UserID, BlogID=blog_id)
    if db.session.add(collection):
        db.session.commit()
        return "success"
    else:
        return "fail"
Exemplo n.º 13
0
def create_collection(
    user: InternalUserDTO, collection: CollectionDTO
) -> CollectionDTO:
    collection.provider_uuid = user.provider_uuid
    collection = Collection(**collection.to_dict())
    collection.save()
    collection.session.commit()
    return to_model(collection, CollectionDTO)
Exemplo n.º 14
0
 def test_tv_id_list(self):
     u = User(username='******', password='******', email='*****@*****.**')
     db.session.add(u)
     db.session.commit()
     c = Collection(user_id=u.id, tv='1;2;3', name='w')
     db.session.add(c)
     db.session.commit()
     assert c.tv_id_list() == ['1', '2', '3']
Exemplo n.º 15
0
def collection_private(db, provider, request):
    from app.models import Collection

    collection = Collection.create(name="test-collection-private1",
                                   is_public=False,
                                   provider_uuid=provider["uuid"])
    Collection.session.commit()
    return collection.to_dict()
Exemplo n.º 16
0
def collection2(db, provider2, request):
    from app.models import Collection

    collection = Collection.create(name="test-collection1",
                                   is_public=True,
                                   provider_uuid=provider2["uuid"])
    Collection.session.commit()
    return collection.to_dict()
Exemplo n.º 17
0
 def test_save_load(self):
     u = User(username='******', password='******', email='*****@*****.**')
     db.session.add(u)
     db.session.commit()
     c = Collection(user_id=u.id, name='w')
     db.session.add(c)
     db.session.commit()
     assert Collection.query.get(1).user_id == u.id
Exemplo n.º 18
0
def create_collection_item(user: InternalUserDTO, collection_uuid: UUID,
                           item_dto: ItemDTO) -> ItemDTO:
    coll = Collection.find_writeable_or_fail(user, collection_uuid)
    item_dto.collection_uuid = coll.uuid  # type: ignore
    item = Item(**item_dto.to_dict())
    item.save()
    item.session.commit()
    return to_model(item, ItemDTO)
Exemplo n.º 19
0
def getMultiplePanels():
    cursor = mysql.connect().cursor()
    cursor.execute(
        """SELECT collection_id FROM collections WHERE active = 1 AND
        partial_order = 1 ORDER BY collection_id DESC""")
    panels = []
    for col_id in cursor.fetchall():
        panels.append(Collection(col_id).getObj())
    return json.dumps(panels)
Exemplo n.º 20
0
def update_collection_by_uuid(
    user: InternalUserDTO, collection_uuid: UUID, collection_update: CollectionDTO
) -> CollectionDTO:
    collection = Collection.find_writeable_or_fail(user, collection_uuid)
    collection.name = collection_update.name
    collection.is_public = collection_update.is_public
    collection.save()
    collection.session.commit()
    return to_model(collection, CollectionDTO)
Exemplo n.º 21
0
    def delete(self, collection_uid):
        """Delete a collection"""
        collection = Collection.get_active(collection_uid)
        if collection is None:
            raise ResourceNotFound('Collection not found')

        collection.delete()

        return api_deleted_response()
Exemplo n.º 22
0
def generateData(numUser,numCategory,numBlog):
    User.fake(numUser)
    
    Follow.fake(numUser)
        
    Category.fake(numCategory)
    
    Blog.fake(numBlog,numUser)
    
    Comment.fake(numBlog,numUser)
    
    BlogCategory.fake(numBlog,numCategory*5)
    
    BlogLabel.fake(numBlog)
    
    BlogLike.fake(numBlog*20,numUser,numBlog)
    
    CommentLike.fake(numBlog*30,numUser,numBlog*8)
    
    Collection.fake(numBlog*10,numUser,numBlog)
Exemplo n.º 23
0
def creates1():
    form = CollectionForm()
    if form.validate_on_submit():
        collection = Collection(name=form.name.data, numb=form.numb.data, user_id=current_user.id)
        #current_user.add_collection(collection)
        db.session.add(collection)
        db.session.commit()
        flash('Congratulations, you added deal "'+str(form.name.data) +
              '" on '+form.numb.data.strftime('%d.%m.%Y')+'!')
        return render_template('creates1.html', title='Collection create', form=form)
    return render_template('creates1.html', title='Collection create', form=form)
Exemplo n.º 24
0
def uncollect_blog(blog_id):
    if len(
            Collection.query.filter_by(UserID=current_user.UserID,
                                       BlogID=blog_id)) == 0:
        return "fail"
    collection = Collection(UserID=current_user.UserID, BlogID=blog_id)
    if db.session.delete(collection):
        db.session.commit()
        return "success"
    else:
        return "fail"
Exemplo n.º 25
0
    def patch(self, collection_uid):
        request_data = get_current_request_data()

        collection = Collection.get_active(collection_uid)
        if collection is None:
            raise ResourceNotFound('Collection not found')

        params = self.__validate_collection_update_params(request_data)

        collection = self.edit_collection(collection, params)

        return api_success_response(collection.as_json())
Exemplo n.º 26
0
def collect_school_dynamic():
    try:
        collection = Collection(request.args.get("collection_id"),
                                session["user_number"], session["user_type"],
                                request.args.get('dynamic_type'))
        id = str(uuid.uuid1())
        collection.id = id
        db.session.add(collection)
        db.session.commit()
        return json.dumps({'code': 1, "id": id})
    except:
        return json.dumps({"code": -1})
Exemplo n.º 27
0
def collection():
    collection_id = request.args.get('id')
    collection = Collection.fetch_by_id(collection_id)

    photos = collection.fetch_photos()

    photos_json = json.dumps(photos)
    loaded_photos = json.loads(photos_json)
    return render_template('collection.html',
                           photos=loaded_photos,
                           name=collection.name,
                           info=collection.info)
Exemplo n.º 28
0
def insert_into_db(word):
    subtitle = Subtitle(directory="")
    sentence = subtitle.get_word_sentence(word)
    collection = Collection(
        name=word,
        collect_time=date.today(),
        full_sentence=sentence
    )
    db.session.add(collection)
    try:
        db.session.commit()
    except:
        db.session.rollback()
Exemplo n.º 29
0
def addCol():
    jsons = {}
    blog_id = getBlogID(request.form['url'])
    if Collection.query.filter(Collection.user_id == session['id'],
                               Collection.blog_id == blog_id).first():
        jsons['isSuccess'] = 9  # 已经收藏
        return jsonify(jsons)
    col_add = Collection(user_id=session['id'], blog_id=blog_id)
    db.session.add(col_add)
    db.session.commit()
    UserLogAdd(session['id'], session['username'], 105, "博客id:" + str(blog_id))
    jsons['isSuccess'] = 0
    return jsonify(jsons)
Exemplo n.º 30
0
    def put(self, collection_uid, post_uid):
        """Add a post to a collection"""
        collection = Collection.get_not_deleted(uid=collection_uid)
        if collection is None:
            raise ResourceNotFound('Collection not found')

        post = Post.get_not_deleted(uid=post_uid)
        if post is None:
            raise ResourceNotFound('Post not found')

        post.update(collection_id=collection.id)

        return api_success_response()