コード例 #1
0
ファイル: views.py プロジェクト: bmschwa/Sefaria-Project
def get_user_collections_for_sheet(uid, sheet_id):
    """
    Returns a list of `uid`'s collections that `sheet_id` is included in.
    """
    collections = CollectionSet({"$or": [{"admins": uid, "sheets": sheet_id}, {"members": uid, "sheets": sheet_id}]})
    collections = [collection.listing_contents(uid) for collection in collections]
    return collections
コード例 #2
0
ファイル: views.py プロジェクト: bmschwa/Sefaria-Project
def collections_get_api(request, slug=None):
    if not slug:
        return jsonResponse(CollectionSet.get_collection_listing(request.user.id))
    collection_obj = Collection().load({"slug": unquote(slug)})
    if not collection_obj:
        return jsonResponse({"error": "No collection with slug '{}'".format(slug)})
    is_member = request.user.is_authenticated and collection_obj.is_member(request.user.id)
    collection_content = collection_obj.contents(with_content=True, authenticated=is_member)
    return jsonResponse(collection_content)
コード例 #3
0
ファイル: views.py プロジェクト: bmschwa/Sefaria-Project
def get_user_collections(uid, private=True):
    """
    Returns a list of Collections that user belongs to.
    """
    if not uid:
        return None
    collections = CollectionSet().for_user(uid, private=private)
    collections = [collection.listing_contents(uid) for collection in collections]
    return collections
コード例 #4
0
ファイル: views.py プロジェクト: yairm210/Sefaria-Project
def collections_post_api(request, user_id, slug=None):
    if request.method == "POST":
        j = request.POST.get("json")
        if not j:
            return jsonResponse({"error": "No JSON given in post data."})
        collection_data = json.loads(j)
        if "slug" in collection_data:
            collection = Collection().load({"slug": collection_data["slug"]})
            if not collection:
                return jsonResponse({
                    "error":
                    "Collection with slug `{}` not found.".format(
                        collection["slug"])
                })
            # check poster is a collection admin
            if user_id not in collection.admins:
                return jsonResponse({
                    "error":
                    "You do not have permission to edit this collection."
                })

            collection.load_from_dict(collection_data)
            collection.save()
        else:
            collection_data["admins"] = [user_id]
            collection = Collection(collection_data)
            collection.save()
        return jsonResponse({
            "status":
            "ok",
            "collection":
            collection.listing_contents(request.user.id)
        })

    elif request.method == "DELETE":
        if not slug:
            return jsonResponse(
                {"error": "Please specify a collection in the URL."})
        existing = Collection().load({"slug": slug})
        if existing:
            if user_id not in existing.admins:
                return jsonResponse({
                    "error":
                    "You do not have permission to delete this collection."
                })
            else:
                CollectionSet({"slug": slug}).delete()
                return jsonResponse({"status": "ok"})
        else:
            return jsonResponse({
                "error":
                "Collection with the slug `{}` does not exist".format(slug)
            })

    else:
        return jsonResponse({"error": "Unsupported HTTP method."})
コード例 #5
0
def annotate_user_collections(sheets, user_id):
	"""
	Adds a `collections` field to each sheet in `sheets` which includes the collections
	that `user_id` has put that sheet in.
	"""
	sheet_ids = [sheet["id"] for sheet in sheets]
	user_collections = CollectionSet({"sheets": {"$in": sheet_ids}})
	for sheet in sheets:
		sheet["collections"] = []
		for collection in user_collections:
			if sheet["id"] in collection.sheets:
				sheet["collections"].append({"name": collection.name, "slug": collection.slug})

	return sheets
コード例 #6
0
ファイル: search.py プロジェクト: shaneerosen/Sefaria-Project
def index_sheet(index_name, id):
    """
    Index source sheet with 'id'.
    """

    sheet = db.sheets.find_one({"id": id})
    if not sheet: return False

    pud = public_user_data(sheet["owner"])
    tag_terms_simple = make_sheet_tags(sheet)
    tags = [t["en"] for t in tag_terms_simple]
    topics = []
    for t in sheet.get('topics', []):
        topic_obj = Topic.init(t['slug'])
        if not topic_obj:
            continue
        topics += [topic_obj]
    collections = CollectionSet({"sheets": id, "listed": True})
    collection_names = [c.name for c in collections]
    try:
        doc = {
            "title": strip_tags(sheet["title"]),
            "content": make_sheet_text(sheet, pud),
            "owner_id": sheet["owner"],
            "owner_name": pud["name"],
            "owner_image": pud["imageUrl"],
            "profile_url": pud["profileUrl"],
            "version": "Source Sheet by " + user_link(sheet["owner"]),
            "tags": tags,
            "topic_slugs": [topic_obj.slug for topic_obj in topics],
            "topics_en": [topic_obj.get_primary_title('en') for topic_obj in topics],
            "topics_he": [topic_obj.get_primary_title('he') for topic_obj in topics],
            "sheetId": id,
            "summary": sheet.get("summary", None),
            "collections": collection_names,
            "datePublished": sheet.get("datePublished", None),
            "dateCreated": sheet.get("dateCreated", None),
            "dateModified": sheet.get("dateModified", None),
            "views": sheet.get("views", 0)
        }
        es_client.create(index=index_name, doc_type='sheet', id=id, body=doc)
        global doc_count
        doc_count += 1
        return True
    except Exception as e:
        print("Error indexing sheet %d" % id)
        print(e)
        return False
コード例 #7
0
def annotate_displayed_collections(sheets):
	"""
	Adds `displayedCollectionName` field to each sheet in `sheets` that has `displayedCollection`.
	"""
	slugs = list(set([sheet["displayedCollection"] for sheet in sheets if sheet.get("displayedCollection", None)]))
	if len(slugs) == 0:
		return sheets
	displayed_collections = CollectionSet({"slug": {"$in": slugs}})
	for sheet in sheets:
		if not sheet.get("displayedCollection", None):
			continue
		for collection in displayed_collections:
			if sheet["displayedCollection"] == collection.slug:
				sheet["displayedCollectionName"] = collection.name

	return sheets
コード例 #8
0
ファイル: sheets.py プロジェクト: bmschwa/Sefaria-Project
def get_sheets_for_ref(tref, uid=None, in_collection=None):
    """
	Returns a list of sheets that include ref,
	formating as need for the Client Sidebar.
	If `uid` is present return user sheets, otherwise return public sheets.
	If `in_collection` (list of slugs) is present, only return sheets in one of the listed collections.
	"""
    oref = model.Ref(tref)
    # perform initial search with context to catch ranges that include a segment ref
    segment_refs = [r.normal() for r in oref.all_segment_refs()]
    query = {"expandedRefs": {"$in": segment_refs}}
    if uid:
        query["owner"] = uid
    else:
        query["status"] = "public"
    if in_collection:
        collections = CollectionSet({"slug": {"$in": in_collection}})
        sheets_list = [collection.sheets for collection in collections]
        sheets_ids = [sheet for sublist in sheets_list for sheet in sublist]
        query["id"] = {"$in": sheets_ids}

    sheetsObj = db.sheets.find(
        query, {
            "id": 1,
            "title": 1,
            "owner": 1,
            "viaOwner": 1,
            "via": 1,
            "dateCreated": 1,
            "includedRefs": 1,
            "expandedRefs": 1,
            "views": 1,
            "topics": 1,
            "status": 1,
            "summary": 1,
            "attribution": 1,
            "assigner_id": 1,
            "likes": 1,
            "displayedCollection": 1,
            "options": 1
        }).sort([["views", -1]])
    sheetsObj.hint("expandedRefs_1")
    sheets = [s for s in sheetsObj]
    user_ids = list({s["owner"] for s in sheets})
    django_user_profiles = User.objects.filter(id__in=user_ids).values(
        'email', 'first_name', 'last_name', 'id')
    user_profiles = {item['id']: item for item in django_user_profiles}
    mongo_user_profiles = list(
        db.profiles.find({"id": {
            "$in": user_ids
        }}, {
            "id": 1,
            "slug": 1,
            "profile_pic_url_small": 1
        }))
    mongo_user_profiles = {item['id']: item for item in mongo_user_profiles}
    for profile in user_profiles:
        try:
            user_profiles[profile]["slug"] = mongo_user_profiles[profile][
                "slug"]
        except:
            user_profiles[profile]["slug"] = "/"

        try:
            user_profiles[profile][
                "profile_pic_url_small"] = mongo_user_profiles[profile].get(
                    "profile_pic_url_small", '')
        except:
            user_profiles[profile]["profile_pic_url_small"] = ""

    results = []
    for sheet in sheets:
        anchor_ref_list, anchor_ref_expanded_list = oref.get_all_anchor_refs(
            segment_refs, sheet.get("includedRefs", []),
            sheet.get("expandedRefs", []))
        ownerData = user_profiles.get(
            sheet["owner"], {
                'first_name': 'Ploni',
                'last_name': 'Almoni',
                'email': '*****@*****.**',
                'slug': 'Ploni-Almoni',
                'id': None,
                'profile_pic_url_small': ''
            })

        if "assigner_id" in sheet:
            asignerData = public_user_data(sheet["assigner_id"])
            sheet["assignerName"] = asignerData["name"]
            sheet["assignerProfileUrl"] = asignerData["profileUrl"]
        if "viaOwner" in sheet:
            viaOwnerData = public_user_data(sheet["viaOwner"])
            sheet["viaOwnerName"] = viaOwnerData["name"]
            sheet["viaOwnerProfileUrl"] = viaOwnerData["profileUrl"]

        if "displayedCollection" in sheet:
            collection = Collection().load(
                {"slug": sheet["displayedCollection"]})
            sheet["collectionTOC"] = getattr(collection, "toc", None)
        topics = add_langs_to_topics(sheet.get("topics", []))
        for anchor_ref, anchor_ref_expanded in zip(anchor_ref_list,
                                                   anchor_ref_expanded_list):
            sheet_data = {
                "owner": sheet["owner"],
                "_id": str(sheet["_id"]),
                "id": str(sheet["id"]),
                "public": sheet["status"] == "public",
                "title": strip_tags(sheet["title"]),
                "sheetUrl": "/sheets/" + str(sheet["id"]),
                "anchorRef": anchor_ref.normal(),
                "anchorRefExpanded": [r.normal() for r in anchor_ref_expanded],
                "options": sheet["options"],
                "collectionTOC": sheet.get("collectionTOC", None),
                "ownerName":
                ownerData["first_name"] + " " + ownerData["last_name"],
                "via": sheet.get("via", None),
                "viaOwnerName": sheet.get("viaOwnerName", None),
                "assignerName": sheet.get("assignerName", None),
                "viaOwnerProfileUrl": sheet.get("viaOwnerProfileUrl", None),
                "assignerProfileUrl": sheet.get("assignerProfileUrl", None),
                "ownerProfileUrl": "/profile/" + ownerData["slug"],
                "ownerImageUrl": ownerData.get('profile_pic_url_small', ''),
                "status": sheet["status"],
                "views": sheet["views"],
                "topics": topics,
                "likes": sheet.get("likes", []),
                "summary": sheet.get("summary", None),
                "attribution": sheet.get("attribution", None),
                "is_featured": sheet.get("is_featured", False),
                "category": "Sheets",  # ditto
                "type": "sheet",  # ditto
            }

            results.append(sheet_data)
    return results