From f28532aa794f2da28db54648a11536d98fe92e44 Mon Sep 17 00:00:00 2001 From: yonadavGit Date: Sun, 3 Nov 2024 13:46:01 +0200 Subject: [PATCH 001/127] test(topic page): test simple topic page elements --- e2e-tests/tests/topics.spec.ts | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/e2e-tests/tests/topics.spec.ts b/e2e-tests/tests/topics.spec.ts index 47d6b9e446..a703719fe6 100644 --- a/e2e-tests/tests/topics.spec.ts +++ b/e2e-tests/tests/topics.spec.ts @@ -1,5 +1,6 @@ import { test } from '@playwright/test'; import {goToPageWithLang} from '../utils'; +import {LANGUAGES} from "../globals"; test('Go to topic page', async ({ context }) => { @@ -8,6 +9,32 @@ test('Go to topic page', async ({ context }) => { await page.getByRole('link', { name: 'Rosh Hashanah' }).first().isVisible(); }); +test('Check source', async ({ context }) => { + const page = await goToPageWithLang(context, '/topics'); + await page.getByRole('link', { name: 'Jewish Calendar' }).click(); + await page.getByRole('link', { name: 'Shabbat' }).first().click(); + await page.getByRole('link', { name: 'Notable Sources' }).first().isVisible(); + await page.getByRole('link', { name: 'All Sources' }).first().isVisible(); +}); + +test('Check sources he interface', async ({ context }) => { + const page = await goToPageWithLang(context, '/topics', LANGUAGES.HE); + await page.getByRole('link', { name: 'מועדי השנה' }).click(); + await page.getByRole('link', { name: 'שבת' }).first().click(); + await page.getByRole('link', { name: 'מקורות מרכזיים' }).first().isVisible(); + await page.getByRole('link', { name: 'כל המקורות' }).first().isVisible(); +}); + +test('Check author page', async ({ context }) => { + const page = await goToPageWithLang(context, '/topics/jonathan-sacks'); + await page.getByRole('link', { name: 'Works on Sefaria' }).first().isVisible(); +}); + +test('Check redirection for sourcesless topic', async ({ context }) => { + const page = await goToPageWithLang(context, '/topics/Monkey'); + await page.waitForURL('https://example.com/target', { timeout: 5000 }); + await page.getByRole('link', { name: 'Works on Sefaria' }).first().isVisible(); +}); test('Filter topics', async ({ context }) => { const page = await goToPageWithLang(context, '/topics/all/a'); From 7025b5ba15bb6065b4a8b8d11eec9dec62bbed4d Mon Sep 17 00:00:00 2001 From: yonadavGit Date: Sun, 3 Nov 2024 17:45:47 +0200 Subject: [PATCH 002/127] tests(topic page): admin user tests --- e2e-tests/globals.ts | 7 ++++++- e2e-tests/tests/topics.spec.ts | 32 +++++++++++++++++++++++++++----- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/e2e-tests/globals.ts b/e2e-tests/globals.ts index a4b53698f2..127047d687 100644 --- a/e2e-tests/globals.ts +++ b/e2e-tests/globals.ts @@ -14,4 +14,9 @@ export const cookieObject = { export const testUser = { email: 'test@example.com', password: 'test', -} \ No newline at end of file +} + +export const testAdminUser = { + email: process.env.ADMIN_EMAIL, + password: process.env.ADMIN_PASSWORD, +}; \ No newline at end of file diff --git a/e2e-tests/tests/topics.spec.ts b/e2e-tests/tests/topics.spec.ts index a703719fe6..e51423a0c4 100644 --- a/e2e-tests/tests/topics.spec.ts +++ b/e2e-tests/tests/topics.spec.ts @@ -1,6 +1,7 @@ -import { test } from '@playwright/test'; -import {goToPageWithLang} from '../utils'; -import {LANGUAGES} from "../globals"; +import {expect, test} from '@playwright/test'; +import {goToPageWithLang, goToPageWithUser} from '../utils'; +import {LANGUAGES, testAdminUser} from "../globals"; +import * as assert from "node:assert"; test('Go to topic page', async ({ context }) => { @@ -17,6 +18,15 @@ test('Check source', async ({ context }) => { await page.getByRole('link', { name: 'All Sources' }).first().isVisible(); }); +test('Check admin tab', async ({ context }) => { + const page = await goToPageWithUser(context, '/topics', testAdminUser); + await page.getByRole('link', { name: 'Jewish Calendar' }).click(); + await page.getByRole('link', { name: 'Shabbat' }).first().click(); + await page.getByRole('link', { name: 'Notable Sources' }).first().isVisible(); + await page.getByRole('link', { name: 'All Sources' }).first().isVisible(); + await page.getByRole('link', { name: 'Admin' }).first().isVisible(); +}); + test('Check sources he interface', async ({ context }) => { const page = await goToPageWithLang(context, '/topics', LANGUAGES.HE); await page.getByRole('link', { name: 'מועדי השנה' }).click(); @@ -32,8 +42,20 @@ test('Check author page', async ({ context }) => { test('Check redirection for sourcesless topic', async ({ context }) => { const page = await goToPageWithLang(context, '/topics/Monkey'); - await page.waitForURL('https://example.com/target', { timeout: 5000 }); - await page.getByRole('link', { name: 'Works on Sefaria' }).first().isVisible(); + // await page.waitForURL('https://www.sefaria.org/search?q=Monkey&tab=sheet&tvar=1&tsort=relevance&stopics_enFilters=Monkey&svar=1&ssort=relevance', { timeout: 50000 }); + const expectedUrl = 'https://www.sefaria.org/search?q=Monkey&tab=sheet&tvar=1&tsort=relevance&stopics_enFilters=Monkey&svar=1&ssort=relevance' + // await expect(page).toHaveURL(expectedUrl, { timeout: 90000 }); + await page.waitForTimeout(10000) + expect(page.url()).toEqual(expectedUrl) + // await page.waitForURL(expectedUrl, { timeout: 100000 }); +}); + +test('Check no redirection when user is admin', async ({ context }) => { + const page = await goToPageWithUser(context, '/topics/Monkey', testAdminUser); + await page.waitForTimeout(2000) + await page.getByRole('link', { name: 'Admin' }).first().isVisible(); + + }); test('Filter topics', async ({ context }) => { From 917e73cf3da837bd4a7b59ab53d38efae354fd4b Mon Sep 17 00:00:00 2001 From: yonadavGit Date: Mon, 4 Nov 2024 12:47:38 +0200 Subject: [PATCH 003/127] tests(topic page): redirection test using timeout of 10 seconds --- e2e-tests/tests/topics.spec.ts | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/e2e-tests/tests/topics.spec.ts b/e2e-tests/tests/topics.spec.ts index e51423a0c4..95a295ed14 100644 --- a/e2e-tests/tests/topics.spec.ts +++ b/e2e-tests/tests/topics.spec.ts @@ -42,20 +42,15 @@ test('Check author page', async ({ context }) => { test('Check redirection for sourcesless topic', async ({ context }) => { const page = await goToPageWithLang(context, '/topics/Monkey'); - // await page.waitForURL('https://www.sefaria.org/search?q=Monkey&tab=sheet&tvar=1&tsort=relevance&stopics_enFilters=Monkey&svar=1&ssort=relevance', { timeout: 50000 }); const expectedUrl = 'https://www.sefaria.org/search?q=Monkey&tab=sheet&tvar=1&tsort=relevance&stopics_enFilters=Monkey&svar=1&ssort=relevance' - // await expect(page).toHaveURL(expectedUrl, { timeout: 90000 }); await page.waitForTimeout(10000) expect(page.url()).toEqual(expectedUrl) - // await page.waitForURL(expectedUrl, { timeout: 100000 }); }); test('Check no redirection when user is admin', async ({ context }) => { const page = await goToPageWithUser(context, '/topics/Monkey', testAdminUser); - await page.waitForTimeout(2000) + await page.waitForTimeout(10000) await page.getByRole('link', { name: 'Admin' }).first().isVisible(); - - }); test('Filter topics', async ({ context }) => { From 5207bf676c7964cd083dad568e5a85737260a2e8 Mon Sep 17 00:00:00 2001 From: yonadavGit Date: Mon, 4 Nov 2024 16:16:09 +0200 Subject: [PATCH 004/127] tests(topic page): create testUser from env vars --- e2e-tests/globals.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/e2e-tests/globals.ts b/e2e-tests/globals.ts index 127047d687..c90baa3741 100644 --- a/e2e-tests/globals.ts +++ b/e2e-tests/globals.ts @@ -12,11 +12,11 @@ export const cookieObject = { } export const testUser = { - email: 'test@example.com', - password: 'test', + email: process.env.PLAYWRIGHT_USER_EMAIL, + password: process.env.PLAYWRIGHT_USER_PASSWORD, } export const testAdminUser = { - email: process.env.ADMIN_EMAIL, - password: process.env.ADMIN_PASSWORD, + email: process.env.PLAYWRIGHT_SUPERUSER_EMAIL, + password: process.env.PLAYWRIGHT_SUPERUSER_PASSWORD, }; \ No newline at end of file From cb871b2985ba6b1b432876b244c6cb06d5d9ba32 Mon Sep 17 00:00:00 2001 From: yonadavGit Date: Mon, 4 Nov 2024 16:29:17 +0200 Subject: [PATCH 005/127] tests(topic page): fix typo --- e2e-tests/tests/topics.spec.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e2e-tests/tests/topics.spec.ts b/e2e-tests/tests/topics.spec.ts index 95a295ed14..9a36db4875 100644 --- a/e2e-tests/tests/topics.spec.ts +++ b/e2e-tests/tests/topics.spec.ts @@ -40,7 +40,7 @@ test('Check author page', async ({ context }) => { await page.getByRole('link', { name: 'Works on Sefaria' }).first().isVisible(); }); -test('Check redirection for sourcesless topic', async ({ context }) => { +test('Check redirection for sourceless topic', async ({ context }) => { const page = await goToPageWithLang(context, '/topics/Monkey'); const expectedUrl = 'https://www.sefaria.org/search?q=Monkey&tab=sheet&tvar=1&tsort=relevance&stopics_enFilters=Monkey&svar=1&ssort=relevance' await page.waitForTimeout(10000) From bcd594ef8d6b255ba561593b6d96850910bf2d74 Mon Sep 17 00:00:00 2001 From: yonadavGit Date: Sun, 10 Nov 2024 14:53:25 +0200 Subject: [PATCH 006/127] chore(playwright tests): add new env users secrets as env var to workflow yaml --- .github/workflows/integration-testing.yaml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/integration-testing.yaml b/.github/workflows/integration-testing.yaml index fb9b9cf2eb..5423ad5c22 100644 --- a/.github/workflows/integration-testing.yaml +++ b/.github/workflows/integration-testing.yaml @@ -193,7 +193,12 @@ jobs: - name: Run Playwright tests run: npx playwright test - + env: + PLAYWRIGHT_SUPERUSER_EMAIL: "${{ secrets.PLAYWRIGHT_SUPERUSER_EMAIL }}" + PLAYWRIGHT_SUPERUSER_PASSWORD: "${{ secrets.PLAYWRIGHT_SUPERUSER_PASSWORD }}" + PLAYWRIGHT_USER_EMAIL: "${{ secrets.PLAYWRIGHT_USER_EMAIL }}" + PLAYWRIGHT_USER_PASSWORD: "${{ secrets.PLAYWRIGHT_USER_PASSWORD }}" + - name: Upload Playwright report uses: actions/upload-artifact@v3 if: always() From 03766da15a47d4a21a6f5bcd6aec9a6e71748f5e Mon Sep 17 00:00:00 2001 From: Brendan Galloway Date: Wed, 9 Oct 2024 14:39:38 +0200 Subject: [PATCH 007/127] ci: don't skip on manual workflow --- .github/workflows/integration-testing.yaml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/integration-testing.yaml b/.github/workflows/integration-testing.yaml index 5423ad5c22..c7d87da32e 100644 --- a/.github/workflows/integration-testing.yaml +++ b/.github/workflows/integration-testing.yaml @@ -8,7 +8,7 @@ concurrency: integration_environment jobs: variables: - if: ${{ github.event_name == 'merge_group' }} + if: ${{ github.event_name == 'merge_group' || github.event_name == 'workflow_dispatch' }} runs-on: ubuntu-latest outputs: date: ${{ steps.data.outputs.date }} @@ -29,7 +29,7 @@ jobs: echo "current_branch=merge-queue" >> $GITHUB_OUTPUT build-generic: - if: ${{ github.event_name == 'merge_group' }} + if: ${{ github.event_name == 'merge_group' || github.event_name == 'workflow_dispatch' }} name: "Integration Image Build" needs: - variables @@ -83,7 +83,7 @@ jobs: tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} build-derived: - if: ${{ github.event_name == 'merge_group' }} + if: ${{ github.event_name == 'merge_group' || github.event_name == 'workflow_dispatch' }} runs-on: ubuntu-latest name: "Integration Image Build Stage 2" permissions: @@ -140,7 +140,7 @@ jobs: tags: ${{ steps.meta.outputs.tags }} labels: ${{ steps.meta.outputs.labels }} run-tests: - if: ${{ github.event_name == 'merge_group' }} + if: ${{ github.event_name == 'merge_group' || github.event_name == 'workflow_dispatch' }} name: "Playwright" # This name is referenced when slacking status needs: - build-derived @@ -209,7 +209,7 @@ jobs: - name: Uninstall run: helm delete integration-${{ needs.variables.outputs.commit }} -n ${{ secrets.DEV_SANDBOX_NAMESPACE }} --debug --timeout 10m0s ending-notification: - if: ${{ github.event_name == 'merge_group' }} + if: ${{ github.event_name == 'merge_group' || github.event_name == 'workflow_dispatch' }} runs-on: ubuntu-latest needs: - run-tests From 69c57177f3736c5ae11c74c7fd2eba161c206284 Mon Sep 17 00:00:00 2001 From: yonadavGit Date: Mon, 11 Nov 2024 15:45:19 +0200 Subject: [PATCH 008/127] ci: don't skip on manual workflow --- sefaria/settings.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sefaria/settings.py b/sefaria/settings.py index 7eea25ff70..6b9f96fcc6 100644 --- a/sefaria/settings.py +++ b/sefaria/settings.py @@ -334,6 +334,9 @@ } } +CELERY_ENABLED = False +SLACK_URL = '' + DATA_UPLOAD_MAX_MEMORY_SIZE = 24000000 BASE_DIR = os.path.dirname(os.path.dirname(__file__)) From 9ab8c544043c906e584413368b0b5a8997591b61 Mon Sep 17 00:00:00 2001 From: yonadavGit Date: Mon, 11 Nov 2024 16:08:12 +0200 Subject: [PATCH 009/127] fix(settings): remove celery settings from settings.py --- sefaria/settings.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/sefaria/settings.py b/sefaria/settings.py index 6b9f96fcc6..a0a26fdd53 100644 --- a/sefaria/settings.py +++ b/sefaria/settings.py @@ -334,8 +334,6 @@ } } -CELERY_ENABLED = False -SLACK_URL = '' DATA_UPLOAD_MAX_MEMORY_SIZE = 24000000 From 984d64cd786fe80ed5860043860115d6b62fb579 Mon Sep 17 00:00:00 2001 From: Skyler Cohen Date: Mon, 2 Dec 2024 19:30:37 -0500 Subject: [PATCH 010/127] feat(email subscriptions): Modify subscribe endpoint to optionally include a list of newsletter mailing lists and create a new api endpoint to retrieve the existing mailing lists. The new endpoint will be used for syncing the available newsletters that can be subscribed to with a CMS --- sefaria/helper/crm/crm_mediator.py | 7 +++-- sefaria/helper/crm/salesforce.py | 45 +++++++++++++++++++++++++++--- sefaria/urls.py | 3 +- sefaria/views.py | 5 +++- 4 files changed, 52 insertions(+), 8 deletions(-) diff --git a/sefaria/helper/crm/crm_mediator.py b/sefaria/helper/crm/crm_mediator.py index 87980f1175..5e91812f13 100644 --- a/sefaria/helper/crm/crm_mediator.py +++ b/sefaria/helper/crm/crm_mediator.py @@ -20,8 +20,8 @@ def create_crm_user(self, email, first_name, last_name, lang="en", educator=Fals except: return False - def subscribe_to_lists(self, email, first_name, last_name, educator=False, lang="en"): - return self._crm_connection.subscribe_to_lists(email, first_name, last_name, educator, lang) + def subscribe_to_lists(self, email, first_name, last_name, educator=False, lang="en", mailing_lists=[]): + return self._crm_connection.subscribe_to_lists(email, first_name, last_name, educator, lang, mailing_lists) def sync_sustainers(self): current_sustainers = CrmInfoStore.get_current_sustainers() @@ -71,3 +71,6 @@ def get_and_save_crm_id(self, email=None): CrmInfoStore.save_crm_id(crm_id, email) else: return False + + def get_available_lists(self): + return self._crm_connection.get_available_lists() diff --git a/sefaria/helper/crm/salesforce.py b/sefaria/helper/crm/salesforce.py index 8f850d803f..3708b410e2 100644 --- a/sefaria/helper/crm/salesforce.py +++ b/sefaria/helper/crm/salesforce.py @@ -6,6 +6,11 @@ from sefaria.helper.crm.crm_connection_manager import CrmConnectionManager from sefaria import settings as sls +from typing import Any, Optional, List +from pprint import pprint +import traceback + + class SalesforceConnectionManager(CrmConnectionManager): def __init__(self): CrmConnectionManager.__init__(self, sls.SALESFORCE_BASE_URL) @@ -13,6 +18,7 @@ def __init__(self): self.resource_prefix = f"services/data/v{self.version}/sobjects/" def create_endpoint(self, *args): + print(f"{sls.SALESFORCE_BASE_URL}/{self.resource_prefix}{'/'.join(args)}") return f"{sls.SALESFORCE_BASE_URL}/{self.resource_prefix}{'/'.join(args)}" def make_request(self, request, **kwargs): @@ -25,7 +31,7 @@ def make_request(self, request, **kwargs): def get(self, endpoint): headers = {'Content-type': 'application/json', 'Accept': 'application/json'} - return self.session.get(endpoint, headers) + return self.session.get(endpoint, headers=headers) def post(self, endpoint, **kwargs): headers = {'Content-type': 'application/json', 'Accept': 'application/json'} @@ -120,8 +126,18 @@ def find_crm_id(self, email=None): except: return False - def subscribe_to_lists(self, email, first_name=None, last_name=None, lang="en", educator=False): - # TODO: Implement once endpoint exists + def subscribe_to_lists( + self, + email: str, + first_name: Optional[str] = None, + last_name: Optional[str] = None, + lang: str = "en", + educator: bool = False, + mailing_lists: Optional[List[str]] = None) -> Any: + + if mailing_lists is None: + mailing_lists = [] + CrmConnectionManager.subscribe_to_lists(self, email, first_name, last_name, lang, educator) if lang == "he": language = "Hebrew" @@ -134,7 +150,8 @@ def subscribe_to_lists(self, email, first_name=None, last_name=None, lang="en", "Last_Name__c": last_name, "Sefaria_App_Email__c": email, "Hebrew_English__c": language, - "Educator__c": educator + "Educator__c": educator, + "Newsletter_Names__c": mailing_lists }) res = self.post(self.create_endpoint("Sefaria_App_Data__c"), json={ @@ -145,3 +162,23 @@ def subscribe_to_lists(self, email, first_name=None, last_name=None, lang="en", except: return False return res + + def get_available_lists(self) -> List[str]: + print("reaching here") + try: + resource_prefix = f"services/data/v{self.version}/query" + endpoint = f"{sls.SALESFORCE_BASE_URL}/{resource_prefix}/" + response = self.get(endpoint + "?q=SELECT+Subscriptions__c+FROM+AC_to_SF_List_Mapping__mdt") + pprint(response) + pprint(response.json()) + records = response.json()["records"] + return [record["Subscriptions__c"] for record in records] + except Exception as e: + print("An unexpected error occurred:") + pprint({ + "type": type(e).__name__, + "message": str(e), + "args": e.args, + "traceback": traceback.format_exc() + }) + return [] diff --git a/sefaria/urls.py b/sefaria/urls.py index b73ae60733..40a04bd052 100644 --- a/sefaria/urls.py +++ b/sefaria/urls.py @@ -396,10 +396,11 @@ url(r'^api/send_feedback$', sefaria_views.generate_feedback), ] -# Email Subscribe +# Email Newsletter Subscriptions urlpatterns += [ url(r'^api/subscribe/(?P.+)/(?P.+)$', sefaria_views.generic_subscribe_to_newsletter_api), url(r'^api/subscribe/(?P.+)$', sefaria_views.subscribe_sefaria_newsletter_view), + url(r'^api/newsletter_mailing_lists/?$', sefaria_views.get_available_newsletter_mailing_lists), ] # Admin diff --git a/sefaria/views.py b/sefaria/views.py index 80f3939e0d..ebc2eac15c 100644 --- a/sefaria/views.py +++ b/sefaria/views.py @@ -210,9 +210,12 @@ def subscribe_sefaria_newsletter(request, email, first_name, last_name): body = json.loads(request.body) language = body.get("language", "") educator = body.get("educator", False) + mailing_lists = body.get("lists", []) crm_mediator = CrmMediator() - return crm_mediator.subscribe_to_lists(email, first_name, last_name, educator=educator, lang=language) + return crm_mediator.subscribe_to_lists(email, first_name, last_name, educator=educator, lang=language, mailing_lists=mailing_lists) +def get_available_newsletter_mailing_lists(request): + return jsonResponse({"newsletter_mailing_lists": CrmMediator().get_available_lists()}) def subscribe_steinsaltz(request, email, first_name, last_name): """ From aeaa1390583b16ee8e7dd537b62f1af803108295 Mon Sep 17 00:00:00 2001 From: Skyler Cohen Date: Mon, 2 Dec 2024 19:39:10 -0500 Subject: [PATCH 011/127] chore(email subscriptions): Remove debugging statements --- sefaria/helper/crm/salesforce.py | 16 ++-------------- 1 file changed, 2 insertions(+), 14 deletions(-) diff --git a/sefaria/helper/crm/salesforce.py b/sefaria/helper/crm/salesforce.py index 3708b410e2..4e696f0458 100644 --- a/sefaria/helper/crm/salesforce.py +++ b/sefaria/helper/crm/salesforce.py @@ -7,8 +7,6 @@ from sefaria import settings as sls from typing import Any, Optional, List -from pprint import pprint -import traceback class SalesforceConnectionManager(CrmConnectionManager): @@ -18,7 +16,6 @@ def __init__(self): self.resource_prefix = f"services/data/v{self.version}/sobjects/" def create_endpoint(self, *args): - print(f"{sls.SALESFORCE_BASE_URL}/{self.resource_prefix}{'/'.join(args)}") return f"{sls.SALESFORCE_BASE_URL}/{self.resource_prefix}{'/'.join(args)}" def make_request(self, request, **kwargs): @@ -164,21 +161,12 @@ def subscribe_to_lists( return res def get_available_lists(self) -> List[str]: - print("reaching here") try: resource_prefix = f"services/data/v{self.version}/query" endpoint = f"{sls.SALESFORCE_BASE_URL}/{resource_prefix}/" response = self.get(endpoint + "?q=SELECT+Subscriptions__c+FROM+AC_to_SF_List_Mapping__mdt") - pprint(response) - pprint(response.json()) records = response.json()["records"] return [record["Subscriptions__c"] for record in records] - except Exception as e: - print("An unexpected error occurred:") - pprint({ - "type": type(e).__name__, - "message": str(e), - "args": e.args, - "traceback": traceback.format_exc() - }) + except: + print("Unable to retrieve newsletter mailing lists from Salesforce CRM") return [] From 752947e311f37edcf122517734ebcfaef3a00505 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Tue, 3 Dec 2024 14:49:04 +0200 Subject: [PATCH 012/127] docs(topics): document ImageCropper --- static/js/ImageCropper.jsx | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/static/js/ImageCropper.jsx b/static/js/ImageCropper.jsx index b65955b407..b8866c5530 100644 --- a/static/js/ImageCropper.jsx +++ b/static/js/ImageCropper.jsx @@ -5,6 +5,14 @@ import {LoadingRing} from "./Misc"; import 'react-image-crop/dist/ReactCrop.css'; export const ImageCropper = ({loading, error, src, onClose, onSave}) => { + /** + * loading - bool, is the image cropper loading data + * error - str, error message + * src + * onClose - fn, called when ImageCropper is closed + * onSave - fn, called when "Save" is pressed + * @type {React.MutableRefObject} + */ const imageRef = useRef(null); const [isFirstCropChange, setIsFirstCropChange] = useState(true); const [crop, setCrop] = useState({unit: "px", width: 250, aspect: 1}); From 617c05df38bf3b4a36bb29217b3cde0919b98dc8 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Tue, 3 Dec 2024 15:09:05 +0200 Subject: [PATCH 013/127] feat(topics): add secondary image cropper --- static/js/AdminEditor.jsx | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/static/js/AdminEditor.jsx b/static/js/AdminEditor.jsx index 0aade1c9e4..f52aebf4f8 100644 --- a/static/js/AdminEditor.jsx +++ b/static/js/AdminEditor.jsx @@ -123,7 +123,7 @@ const validateMarkdownLinks = async (input) => { return true; } -const AdminEditor = ({title, data, close, catMenu, pictureUploader, updateData, savingStatus, +const AdminEditor = ({title, data, close, catMenu, pictureUploader, secondaryPictureCropper, updateData, savingStatus, validate, deleteObj, items = [], isNew = true, extras = [], path = []}) => { const [validatingLinks, setValidatingLinks] = useState(false); @@ -213,6 +213,8 @@ const AdminEditor = ({title, data, close, catMenu, pictureUploader, updateData, return catMenu; } else if (x === "Picture Uploader") { return pictureUploader; + } else if (x === "Secondary Picture Cropper") { + return secondaryPictureCropper; } else { return item({...options_for_form[x]}); From d84e3995a1b76dcc1da5030779060cab4e47086b Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Tue, 3 Dec 2024 15:09:20 +0200 Subject: [PATCH 014/127] refactor(topics): refactor out small blue button --- static/js/Misc.jsx | 20 +++++++++++++------- static/js/TopicEditor.jsx | 8 ++++++++ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/static/js/Misc.jsx b/static/js/Misc.jsx index 595096c1aa..975148a2ee 100644 --- a/static/js/Misc.jsx +++ b/static/js/Misc.jsx @@ -1432,7 +1432,15 @@ FollowButton.propTypes = { }; -const TopicPictureUploader = ({slug, callback, old_filename, caption}) => { +const SmallBlueButton = ({onClick, tabIndex, text}) => { + return ( +
+ {text} +
+ ); +}; + +const TopicPictureUploader = ({title, slug, callback, old_filename, caption}) => { /* `old_filename` is passed to API so that if it exists, it is deleted */ @@ -1500,16 +1508,14 @@ const TopicPictureUploader = ({slug, callback, old_filename, caption}) => {
e.stopPropagation()} id="addImageButton">
{old_filename !== "" &&

-
- Remove Picture -
+
+ + } } diff --git a/static/js/TopicEditor.jsx b/static/js/TopicEditor.jsx index 9680617df1..8387b4b6d3 100644 --- a/static/js/TopicEditor.jsx +++ b/static/js/TopicEditor.jsx @@ -3,9 +3,15 @@ import {InterfaceText, TopicPictureUploader} from "./Misc"; import $ from "./sefaria/sefariaJquery"; import {AdminEditor} from "./AdminEditor"; import {Reorder} from "./CategoryEditor"; +import {ImageCropper} from "./ImageCropper"; import React, {useState, useEffect} from "react"; +const TopicPictureCropper = ({}) => { + return (
hello
); +} + + const TopicEditor = ({origData, onCreateSuccess, close, origWasCat}) => { const [data, setData] = useState({...origData, catSlug: origData.origCatSlug || "", enTitle: origData.origEnTitle, heTitle: origData.origHeTitle || "", @@ -235,10 +241,12 @@ const TopicEditor = ({origData, onCreateSuccess, close, origWasCat}) => { items.push("Picture Uploader"); items.push("English Caption"); items.push("Hebrew Caption"); + items.push("Secondary Picture Cropper") return } + secondaryPictureCropper={} extras={ [isNew ? null : Date: Tue, 3 Dec 2024 15:44:41 +0200 Subject: [PATCH 015/127] feat(topics): basic image cropping ui works --- static/js/Misc.jsx | 83 +-------------------------------- static/js/TopicEditor.jsx | 97 +++++++++++++++++++++++++++++++++++++-- 2 files changed, 94 insertions(+), 86 deletions(-) diff --git a/static/js/Misc.jsx b/static/js/Misc.jsx index 975148a2ee..13f1193e3c 100644 --- a/static/js/Misc.jsx +++ b/static/js/Misc.jsx @@ -1440,85 +1440,6 @@ const SmallBlueButton = ({onClick, tabIndex, text}) => { ); }; -const TopicPictureUploader = ({title, slug, callback, old_filename, caption}) => { - /* - `old_filename` is passed to API so that if it exists, it is deleted - */ - const fileInput = useRef(null); - - const uploadImage = function(imageData, type="POST") { - const formData = new FormData(); - formData.append('file', imageData.replace(/data:image\/(jpe?g|png|gif);base64,/, "")); - if (old_filename !== "") { - formData.append('old_filename', old_filename); - } - const request = new Request( - `${Sefaria.apiHost}/api/topics/images/${slug}`, - {headers: {'X-CSRFToken': Cookies.get('csrftoken')}} - ); - fetch(request, { - method: 'POST', - mode: 'same-origin', - credentials: 'same-origin', - body: formData - }).then(response => { - if (!response.ok) { - response.text().then(resp_text=> { - alert(resp_text); - }) - }else{ - response.json().then(resp_json=>{ - callback(resp_json.url); - }); - } - }).catch(error => { - alert(error); - })}; - const onFileSelect = (e) => { - const file = fileInput.current.files[0]; - if (file == null) - return; - if (/\.(jpe?g|png|gif)$/i.test(file.name)) { - const reader = new FileReader(); - - reader.addEventListener("load", function() { - uploadImage(reader.result); - }, false); - - reader.addEventListener("onerror", function() { - alert(reader.error); - }, false); - - reader.readAsDataURL(file); - } else { - alert('The file is not an image'); - } - } - const deleteImage = () => { - const old_filename_wout_url = old_filename.split("/").slice(-1); - const url = `${Sefaria.apiHost}/api/topics/images/${slug}?old_filename=${old_filename_wout_url}`; - Sefaria.adminEditorApiRequest(url, null, null, "DELETE").then(() => alert("Deleted image.")); - callback(""); - fileInput.current.value = ""; - } - return
- - -
e.stopPropagation()} id="addImageButton"> - -
- {old_filename !== "" &&
-
-
- -
- } -
- } const CategoryColorLine = ({category}) =>
; @@ -3320,9 +3241,9 @@ export { CategoryChooser, TitleVariants, OnInView, - TopicPictureUploader, ImageWithCaption, handleAnalyticsOnMarkdown, LangSelectInterface, - PencilSourceEditor + PencilSourceEditor, + SmallBlueButton, }; diff --git a/static/js/TopicEditor.jsx b/static/js/TopicEditor.jsx index 8387b4b6d3..e8bbac14fb 100644 --- a/static/js/TopicEditor.jsx +++ b/static/js/TopicEditor.jsx @@ -1,14 +1,101 @@ import Sefaria from "./sefaria/sefaria"; -import {InterfaceText, TopicPictureUploader} from "./Misc"; +import {InterfaceText, SmallBlueButton, ImageWithCaption} from "./Misc"; import $ from "./sefaria/sefariaJquery"; import {AdminEditor} from "./AdminEditor"; import {Reorder} from "./CategoryEditor"; import {ImageCropper} from "./ImageCropper"; -import React, {useState, useEffect} from "react"; +import React, {useState, useRef} from "react"; -const TopicPictureCropper = ({}) => { - return (
hello
); +const TopicPictureUploader = ({slug, callback, old_filename, caption}) => { + /* + `old_filename` is passed to API so that if it exists, it is deleted + */ + const fileInput = useRef(null); + + const uploadImage = function(imageData, type="POST") { + const formData = new FormData(); + formData.append('file', imageData.replace(/data:image\/(jpe?g|png|gif);base64,/, "")); + if (old_filename !== "") { + formData.append('old_filename', old_filename); + } + const request = new Request( + `${Sefaria.apiHost}/api/topics/images/${slug}`, + {headers: {'X-CSRFToken': Cookies.get('csrftoken')}} + ); + fetch(request, { + method: 'POST', + mode: 'same-origin', + credentials: 'same-origin', + body: formData + }).then(response => { + if (!response.ok) { + response.text().then(resp_text=> { + alert(resp_text); + }) + }else{ + response.json().then(resp_json=>{ + callback(resp_json.url); + }); + } + }).catch(error => { + alert(error); + })}; + const onFileSelect = (e) => { + const file = fileInput.current.files[0]; + if (file == null) + return; + if (/\.(jpe?g|png|gif)$/i.test(file.name)) { + const reader = new FileReader(); + + reader.addEventListener("load", function() { + uploadImage(reader.result); + }, false); + + reader.addEventListener("onerror", function() { + alert(reader.error); + }, false); + + reader.readAsDataURL(file); + } else { + alert('The file is not an image'); + } + } + const deleteImage = () => { + const old_filename_wout_url = old_filename.split("/").slice(-1); + const url = `${Sefaria.apiHost}/api/topics/images/${slug}?old_filename=${old_filename_wout_url}`; + Sefaria.adminEditorApiRequest(url, null, null, "DELETE").then(() => alert("Deleted image.")); + callback(""); + fileInput.current.value = ""; + } + return
+ + +
e.stopPropagation()} id="addImageButton"> + +
+ {old_filename !== "" &&
+
+
+ +
+ } +
+} + + +const TopicPictureCropper = ({image_uri}) => { + const [imageToCrop, setImageToCrop] = useState(null); + return ( +
+ setImageToCrop(image_uri)} text="Upload Secondary Picture" /> + setImageToCrop(null)}/> +
+ ); } @@ -246,7 +333,7 @@ const TopicEditor = ({origData, onCreateSuccess, close, origWasCat}) => { validate={validate} deleteObj={deleteObj} updateData={updateData} isNew={isNew} items={items} pictureUploader={} - secondaryPictureCropper={} + secondaryPictureCropper={} extras={ [isNew ? null : Date: Tue, 3 Dec 2024 15:59:12 +0200 Subject: [PATCH 016/127] chore(topics): change text to secondary picture --- static/js/TopicEditor.jsx | 1 + 1 file changed, 1 insertion(+) diff --git a/static/js/TopicEditor.jsx b/static/js/TopicEditor.jsx index e8bbac14fb..8554af80eb 100644 --- a/static/js/TopicEditor.jsx +++ b/static/js/TopicEditor.jsx @@ -92,6 +92,7 @@ const TopicPictureCropper = ({image_uri}) => { const [imageToCrop, setImageToCrop] = useState(null); return (
+ setImageToCrop(image_uri)} text="Upload Secondary Picture" /> setImageToCrop(null)}/>
From 6c46f2f293583acc4951edad953f819e2d94fd1a Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Tue, 3 Dec 2024 16:33:33 +0200 Subject: [PATCH 017/127] refactor(topics): change param to slug --- reader/views.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/reader/views.py b/reader/views.py index b8eab6c121..85a0989df8 100644 --- a/reader/views.py +++ b/reader/views.py @@ -3638,7 +3638,7 @@ def profile_follow_api(request, ftype, slug): return jsonResponse({"error": "Unsupported HTTP method."}) @staff_member_required -def topic_upload_photo(request, topic): +def topic_upload_photo(request, slug): from io import BytesIO import uuid import base64 @@ -3648,7 +3648,7 @@ def topic_upload_photo(request, topic): return jsonResponse({"error": "You cannot remove an image as you haven't selected one yet."}) old_filename = f"topics/{old_filename.split('/')[-1]}" GoogleStorageManager.delete_filename(old_filename, GoogleStorageManager.TOPICS_BUCKET) - topic = Topic.init(topic) + topic = Topic.init(slug) if hasattr(topic, "image"): del topic.image topic.save() @@ -3661,7 +3661,7 @@ def topic_upload_photo(request, topic): img_file_in_mem = BytesIO(base64.b64decode(file)) img_url = GoogleStorageManager.upload_file(img_file_in_mem, f"topics/{request.user.id}-{uuid.uuid1()}.gif", GoogleStorageManager.TOPICS_BUCKET, old_filename=old_filename) - topic = Topic.init(topic) + topic = Topic.init(slug) if not hasattr(topic, "image"): topic.image = {"image_uri": img_url, "image_caption": {"en": "", "he": ""}} else: From feb6db616b1ece08679005942331f6b7f26345df Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Tue, 3 Dec 2024 20:05:16 +0200 Subject: [PATCH 018/127] feat(topics): add secondary topic image api --- reader/views.py | 20 ++++++++++---------- sefaria/helper/topic.py | 37 ++++++++++++++++++++++++++++++------- sefaria/model/topic.py | 1 + sefaria/urls.py | 3 ++- 4 files changed, 43 insertions(+), 18 deletions(-) diff --git a/reader/views.py b/reader/views.py index 85a0989df8..ca1daa4432 100644 --- a/reader/views.py +++ b/reader/views.py @@ -3637,9 +3637,11 @@ def profile_follow_api(request, ftype, slug): return jsonResponse(response) return jsonResponse({"error": "Unsupported HTTP method."}) + @staff_member_required -def topic_upload_photo(request, slug): +def topic_upload_photo(request, slug, secondary=False): from io import BytesIO + from sefaria.helper.topic import add_image_to_topic, delete_image_from_topic, add_secondary_image_to_topic, delete_secondary_image_from_topic import uuid import base64 if request.method == "DELETE": @@ -3648,10 +3650,10 @@ def topic_upload_photo(request, slug): return jsonResponse({"error": "You cannot remove an image as you haven't selected one yet."}) old_filename = f"topics/{old_filename.split('/')[-1]}" GoogleStorageManager.delete_filename(old_filename, GoogleStorageManager.TOPICS_BUCKET) - topic = Topic.init(slug) - if hasattr(topic, "image"): - del topic.image - topic.save() + if secondary: + delete_secondary_image_from_topic(slug) + else: + delete_image_from_topic(slug) return jsonResponse({"success": "You have successfully removed the image."}) elif request.method == "POST": file = request.POST.get('file') @@ -3661,12 +3663,10 @@ def topic_upload_photo(request, slug): img_file_in_mem = BytesIO(base64.b64decode(file)) img_url = GoogleStorageManager.upload_file(img_file_in_mem, f"topics/{request.user.id}-{uuid.uuid1()}.gif", GoogleStorageManager.TOPICS_BUCKET, old_filename=old_filename) - topic = Topic.init(slug) - if not hasattr(topic, "image"): - topic.image = {"image_uri": img_url, "image_caption": {"en": "", "he": ""}} + if secondary: + add_secondary_image_to_topic(slug, img_url) else: - topic.image["image_uri"] = img_url - topic.save() + add_image_to_topic(slug, img_url) return jsonResponse({"url": img_url}) return jsonResponse({"error": "Unsupported HTTP method."}) diff --git a/sefaria/helper/topic.py b/sefaria/helper/topic.py index d6f8aa92bc..e03971ce60 100644 --- a/sefaria/helper/topic.py +++ b/sefaria/helper/topic.py @@ -1328,7 +1328,7 @@ def delete_ref_topic_link(tref, to_topic, link_type, lang): return {"error": f"Cannot delete link between {tref} and {to_topic}."} -def add_image_to_topic(topic_slug, image_uri, en_caption, he_caption): +def add_image_to_topic(topic_slug: str, image_uri: str, en_caption: str = "", he_caption: str =""): """ A function to add an image to a Topic in the database. Helper for data migration. This function queries the desired Topic, adds the image data, and then saves. @@ -1339,9 +1339,32 @@ def add_image_to_topic(topic_slug, image_uri, en_caption, he_caption): :param he_caption String: The Hebrew caption for a Topic image """ topic = Topic.init(topic_slug) - topic.image = {"image_uri": image_uri, - "image_caption": { - "en": en_caption, - "he": he_caption - }} - topic.save() \ No newline at end of file + if not hasattr(topic, "image"): + topic.image = {"image_uri": image_uri, "image_caption": {"en": en_caption, "he": he_caption}} + else: + topic.image["image_uri"] = image_uri + if en_caption: + topic.image["image_caption"]["en"] = en_caption + if he_caption: + topic.image["image_caption"]["he"] = he_caption + topic.save() + + +def add_secondary_image_to_topic(topic_slug: str, image_uri: str): + topic = Topic.init(topic_slug) + topic.secondary_image = image_uri + topic.save() + + +def delete_image_from_topic(topic_slug: str): + topic = Topic.init(topic_slug) + if hasattr(topic, "image"): + del topic.image + topic.save() + + +def delete_secondary_image_from_topic(topic_slug: str): + topic = Topic.init(topic_slug) + if hasattr(topic, "secondary_image"): + del topic.secondary_image + topic.save() diff --git a/sefaria/model/topic.py b/sefaria/model/topic.py index da67c64f55..92b7df8b3c 100644 --- a/sefaria/model/topic.py +++ b/sefaria/model/topic.py @@ -153,6 +153,7 @@ class Topic(abst.SluggedAbstractMongoRecord, AbstractTitledObject): 'isAmbiguous', # True if topic primary title can refer to multiple other topics "data_source", #any topic edited manually should display automatically in the TOC and this flag ensures this 'image', + 'secondary_image', "portal_slug", # slug to relevant Portal object ] diff --git a/sefaria/urls.py b/sefaria/urls.py index b73ae60733..23b4cf63be 100644 --- a/sefaria/urls.py +++ b/sefaria/urls.py @@ -103,7 +103,8 @@ url(r'^topics/b/(?P.+)$', reader_views.topic_page_b), url(r'^topics/(?P.+)$', reader_views.topic_page), url(r'^api/topic/completion/(?P.+)', reader_views.topic_completion_api), - url(r'^api/topics/images/(?P.+)$', reader_views.topic_upload_photo) + url(r'^_api/topics/images/secondary/(?P.+)$', reader_views.topic_upload_photo, {"secondary": True}), + url(r'^_api/topics/images/(?P.+)$', reader_views.topic_upload_photo) ] From 15955cfc14ab87d4bea72c8551a3626432cfec5a Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Tue, 3 Dec 2024 20:08:56 +0200 Subject: [PATCH 019/127] chore(topics): preparing code for secondary image upload --- static/js/TopicEditor.jsx | 65 ++++++++++++++++++++------------------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/static/js/TopicEditor.jsx b/static/js/TopicEditor.jsx index 8554af80eb..0322089af7 100644 --- a/static/js/TopicEditor.jsx +++ b/static/js/TopicEditor.jsx @@ -7,40 +7,43 @@ import {ImageCropper} from "./ImageCropper"; import React, {useState, useRef} from "react"; +const uploadTopicImage = function(imageData, slug, old_filename, topic_image_api="_api/topics/images") { + const formData = new FormData(); + formData.append('file', imageData.replace(/data:image\/(jpe?g|png|gif);base64,/, "")); + if (old_filename !== "") { + formData.append('old_filename', old_filename); + } + const request = new Request( + `${Sefaria.apiHost}/${topic_image_api}/${slug}`, + {headers: {'X-CSRFToken': Cookies.get('csrftoken')}} + ); + return fetch(request, { + method: 'POST', + mode: 'same-origin', + credentials: 'same-origin', + body: formData + }).then(response => { + if (!response.ok) { + response.text().then(resp_text=> { + alert(resp_text); + throw new Error(resp_text); + }) + } else { + return response.json().then(resp_json => resp_json.url); + } + }).catch(error => { + alert(error); + throw new Error(error); + }) +}; + + const TopicPictureUploader = ({slug, callback, old_filename, caption}) => { /* `old_filename` is passed to API so that if it exists, it is deleted */ const fileInput = useRef(null); - const uploadImage = function(imageData, type="POST") { - const formData = new FormData(); - formData.append('file', imageData.replace(/data:image\/(jpe?g|png|gif);base64,/, "")); - if (old_filename !== "") { - formData.append('old_filename', old_filename); - } - const request = new Request( - `${Sefaria.apiHost}/api/topics/images/${slug}`, - {headers: {'X-CSRFToken': Cookies.get('csrftoken')}} - ); - fetch(request, { - method: 'POST', - mode: 'same-origin', - credentials: 'same-origin', - body: formData - }).then(response => { - if (!response.ok) { - response.text().then(resp_text=> { - alert(resp_text); - }) - }else{ - response.json().then(resp_json=>{ - callback(resp_json.url); - }); - } - }).catch(error => { - alert(error); - })}; const onFileSelect = (e) => { const file = fileInput.current.files[0]; if (file == null) @@ -49,7 +52,7 @@ const TopicPictureUploader = ({slug, callback, old_filename, caption}) => { const reader = new FileReader(); reader.addEventListener("load", function() { - uploadImage(reader.result); + uploadTopicImage(reader.result).then(url => callback(url)); }, false); reader.addEventListener("onerror", function() { @@ -63,7 +66,7 @@ const TopicPictureUploader = ({slug, callback, old_filename, caption}) => { } const deleteImage = () => { const old_filename_wout_url = old_filename.split("/").slice(-1); - const url = `${Sefaria.apiHost}/api/topics/images/${slug}?old_filename=${old_filename_wout_url}`; + const url = `${Sefaria.apiHost}/_api/topics/images/${slug}?old_filename=${old_filename_wout_url}`; Sefaria.adminEditorApiRequest(url, null, null, "DELETE").then(() => alert("Deleted image.")); callback(""); fileInput.current.value = ""; @@ -94,7 +97,7 @@ const TopicPictureCropper = ({image_uri}) => {
setImageToCrop(image_uri)} text="Upload Secondary Picture" /> - setImageToCrop(null)}/> + setImageToCrop(null)} onSave={() => uploadTopicImage()}/>
); } From 078c6710f59ed9da359a05a4faf1ffc2d3f1bdbf Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Wed, 4 Dec 2024 10:41:55 +0200 Subject: [PATCH 020/127] refactor(topics): simplify file upload logic --- reader/views.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/reader/views.py b/reader/views.py index ca1daa4432..3dd53b3734 100644 --- a/reader/views.py +++ b/reader/views.py @@ -3640,10 +3640,8 @@ def profile_follow_api(request, ftype, slug): @staff_member_required def topic_upload_photo(request, slug, secondary=False): - from io import BytesIO from sefaria.helper.topic import add_image_to_topic, delete_image_from_topic, add_secondary_image_to_topic, delete_secondary_image_from_topic import uuid - import base64 if request.method == "DELETE": old_filename = request.GET.get("old_filename") if old_filename is None: @@ -3656,12 +3654,11 @@ def topic_upload_photo(request, slug, secondary=False): delete_image_from_topic(slug) return jsonResponse({"success": "You have successfully removed the image."}) elif request.method == "POST": - file = request.POST.get('file') old_filename = request.POST.get('old_filename') # delete file from google storage if there is one there if old_filename: old_filename = f"topics/{old_filename.split('/')[-1]}" - img_file_in_mem = BytesIO(base64.b64decode(file)) - img_url = GoogleStorageManager.upload_file(img_file_in_mem, f"topics/{request.user.id}-{uuid.uuid1()}.gif", + + img_url = GoogleStorageManager.upload_file(request.FILES.get('file'), f"topics/{request.user.id}-{uuid.uuid1()}.gif", GoogleStorageManager.TOPICS_BUCKET, old_filename=old_filename) if secondary: add_secondary_image_to_topic(slug, img_url) From 93fd85974b0503869679d6245c8709c58f37e3d7 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Wed, 4 Dec 2024 10:42:26 +0200 Subject: [PATCH 021/127] chore(topics): remove unused import --- static/js/Misc.jsx | 1 - 1 file changed, 1 deletion(-) diff --git a/static/js/Misc.jsx b/static/js/Misc.jsx index 13f1193e3c..47ec202ad0 100644 --- a/static/js/Misc.jsx +++ b/static/js/Misc.jsx @@ -18,7 +18,6 @@ import {refSort} from "./TopicPage"; import {TopicEditor} from "./TopicEditor"; import {generateContentForModal, SignUpModalKind} from './sefaria/signupModalContent'; import {SourceEditor} from "./SourceEditor"; -import Cookies from "js-cookie"; import {EditTextInfo} from "./BookPage"; import ReactMarkdown from 'react-markdown'; import TrackG4 from "./sefaria/trackG4"; From ec1481a4966c128b52ed7722f89c4cacbd8972a6 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Wed, 4 Dec 2024 10:42:48 +0200 Subject: [PATCH 022/127] fix(topics): allow cross origin images in ImageCropper.jsx --- static/js/ImageCropper.jsx | 1 + 1 file changed, 1 insertion(+) diff --git a/static/js/ImageCropper.jsx b/static/js/ImageCropper.jsx index 64190b69c0..2ec43e284c 100644 --- a/static/js/ImageCropper.jsx +++ b/static/js/ImageCropper.jsx @@ -95,6 +95,7 @@ export const ImageCropper = ({loading, error, src, onClose, onSave}) => { onImageLoaded={onImageLoaded} onComplete={onCropComplete} onChange={onCropChange} + crossorigin={"anonymous"} />) : (
{ error }
) }
From 75aeb0c0ba6fb536584de3d56424504f1ca9b52b Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Wed, 4 Dec 2024 11:56:43 +0200 Subject: [PATCH 023/127] feat(topics): working secondary image upload --- static/js/TopicEditor.jsx | 37 ++++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/static/js/TopicEditor.jsx b/static/js/TopicEditor.jsx index 0322089af7..2e438d9e3c 100644 --- a/static/js/TopicEditor.jsx +++ b/static/js/TopicEditor.jsx @@ -4,17 +4,18 @@ import $ from "./sefaria/sefariaJquery"; import {AdminEditor} from "./AdminEditor"; import {Reorder} from "./CategoryEditor"; import {ImageCropper} from "./ImageCropper"; +import Cookies from "js-cookie"; import React, {useState, useRef} from "react"; -const uploadTopicImage = function(imageData, slug, old_filename, topic_image_api="_api/topics/images") { +const uploadTopicImage = function(imageBlob, old_filename, topic_image_api) { const formData = new FormData(); - formData.append('file', imageData.replace(/data:image\/(jpe?g|png|gif);base64,/, "")); + formData.append('file', imageBlob); if (old_filename !== "") { formData.append('old_filename', old_filename); } const request = new Request( - `${Sefaria.apiHost}/${topic_image_api}/${slug}`, + `${Sefaria.apiHost}/${topic_image_api}`, {headers: {'X-CSRFToken': Cookies.get('csrftoken')}} ); return fetch(request, { @@ -49,17 +50,9 @@ const TopicPictureUploader = ({slug, callback, old_filename, caption}) => { if (file == null) return; if (/\.(jpe?g|png|gif)$/i.test(file.name)) { - const reader = new FileReader(); - - reader.addEventListener("load", function() { - uploadTopicImage(reader.result).then(url => callback(url)); - }, false); - - reader.addEventListener("onerror", function() { - alert(reader.error); - }, false); - - reader.readAsDataURL(file); + uploadTopicImage(file, old_filename, `_api/topics/images/${slug}`) + .then(url => callback(url)) + .catch(err => alert(err)); } else { alert('The file is not an image'); } @@ -91,13 +84,23 @@ const TopicPictureUploader = ({slug, callback, old_filename, caption}) => { } -const TopicPictureCropper = ({image_uri}) => { +const TopicPictureCropper = ({image_uri, slug, old_filename}) => { const [imageToCrop, setImageToCrop] = useState(null); + const onSave = (croppedImageBlob) => { + uploadTopicImage(croppedImageBlob, old_filename, `_api/topics/images/secondary/${slug}`) + .then((new_image_uri) => { + //TODO propagate new_image_uri to TopicEditor + setImageToCrop(null); + }); + } return (
setImageToCrop(image_uri)} text="Upload Secondary Picture" /> - setImageToCrop(null)} onSave={() => uploadTopicImage()}/> + setImageToCrop(null)} + onSave={onSave}/>
); } @@ -337,7 +340,7 @@ const TopicEditor = ({origData, onCreateSuccess, close, origWasCat}) => { validate={validate} deleteObj={deleteObj} updateData={updateData} isNew={isNew} items={items} pictureUploader={} - secondaryPictureCropper={} + secondaryPictureCropper={} extras={ [isNew ? null : Date: Wed, 4 Dec 2024 13:38:40 +0200 Subject: [PATCH 024/127] chore(topics): change filename to not include user ID and to .png. --- reader/views.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/reader/views.py b/reader/views.py index 3dd53b3734..10ffd6b2bb 100644 --- a/reader/views.py +++ b/reader/views.py @@ -3658,7 +3658,7 @@ def topic_upload_photo(request, slug, secondary=False): if old_filename: old_filename = f"topics/{old_filename.split('/')[-1]}" - img_url = GoogleStorageManager.upload_file(request.FILES.get('file'), f"topics/{request.user.id}-{uuid.uuid1()}.gif", + img_url = GoogleStorageManager.upload_file(request.FILES.get('file'), f"topics/{slug}-{uuid.uuid1()}.png", GoogleStorageManager.TOPICS_BUCKET, old_filename=old_filename) if secondary: add_secondary_image_to_topic(slug, img_url) From 9d3fba9d9438a8c5f7af3a004de67ec1e1e71b7c Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Wed, 4 Dec 2024 15:16:18 +0200 Subject: [PATCH 025/127] fix(topics): add secondary to secondary images --- reader/views.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/reader/views.py b/reader/views.py index 10ffd6b2bb..c949fc0c8e 100644 --- a/reader/views.py +++ b/reader/views.py @@ -3658,8 +3658,8 @@ def topic_upload_photo(request, slug, secondary=False): if old_filename: old_filename = f"topics/{old_filename.split('/')[-1]}" - img_url = GoogleStorageManager.upload_file(request.FILES.get('file'), f"topics/{slug}-{uuid.uuid1()}.png", - GoogleStorageManager.TOPICS_BUCKET, old_filename=old_filename) + to_filename = f"topics/{slug}-{'secondary-' if secondary else ''}{uuid.uuid1()}.png" + img_url = GoogleStorageManager.upload_file(request.FILES.get('file'), to_filename, GoogleStorageManager.TOPICS_BUCKET, old_filename=old_filename) if secondary: add_secondary_image_to_topic(slug, img_url) else: From 25e0ea067508f506062eabd4099c541e3ed5f4b2 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Wed, 4 Dec 2024 15:49:06 +0200 Subject: [PATCH 026/127] fix(topics): improve css for cropper --- static/css/s2.css | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/static/css/s2.css b/static/css/s2.css index f834d933f2..20383125de 100644 --- a/static/css/s2.css +++ b/static/css/s2.css @@ -7631,10 +7631,10 @@ But not to use a display block directive that might break continuous mode for ot } .profile-pic-cropper { } -.profile-page .profile-pic .profile-pic-cropper-modal .profile-pic-cropper-button { +#interruptingMessage.profile-pic-cropper-modal .profile-pic-cropper-button { display: inline-flex; } -.profile-page .profile-pic .profile-pic-cropper-desc { +.profile-pic-cropper-desc { margin-top: 9px; margin-bottom: 18px; } @@ -11561,7 +11561,8 @@ cursor: pointer; .profile-page .follow-header .follow-count { color: #999; } -.profile-page .resourcesLink { +.profile-page .resourcesLink, +.profile-pic-cropper-button.resourcesLink { min-height: 46px; height: 46px; overflow: visible; @@ -11584,7 +11585,8 @@ cursor: pointer; line-height: 1.5; } .profile-page .profile-summary .resourcesLink + .resourcesLink, -.profile-page .profile-summary .largeFollowButton + .resourcesLink { +.profile-page .profile-summary .largeFollowButton + .resourcesLink, +#interruptingMessage.profile-pic-cropper-modal .resourcesLink + .resourcesLink { margin: 0 0 0 10px; } .interface-hebrew .profile-page .profile-summary .largeFollowButton + .resourcesLink, From 6a26be7b8bbc95077f77db3d79a3149c2f301ae5 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Wed, 4 Dec 2024 15:51:23 +0200 Subject: [PATCH 027/127] fix(topics): improve css for cropper --- static/css/s2.css | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/static/css/s2.css b/static/css/s2.css index 20383125de..d9535e6897 100644 --- a/static/css/s2.css +++ b/static/css/s2.css @@ -7619,9 +7619,11 @@ But not to use a display block directive that might break continuous mode for ot margin-top: 17px; } .profile-pic-cropper-modal .ReactCrop__crop-selection { - border-radius: 50%; box-shadow: 0 0 0 9999em rgba(255, 255, 255, 0.6); } +.profile-page .profile-pic-cropper-modal .ReactCrop__crop-selection { + border-radius: 50%; +} .profile-pic-cropper-modal .ReactCrop__image { max-width: 50vw; max-height: 50vh; From e67e5bf787e3a79fa9d3d7a5db7ec00e4a866e9e Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Wed, 4 Dec 2024 22:04:35 +0200 Subject: [PATCH 028/127] feat(topics): use 4:3 ratio for crop box for topic images --- static/js/ImageCropper.jsx | 6 +++--- static/js/ProfilePic.jsx | 1 + static/js/TopicEditor.jsx | 5 +++++ 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/static/js/ImageCropper.jsx b/static/js/ImageCropper.jsx index 2ec43e284c..48dc7a6a94 100644 --- a/static/js/ImageCropper.jsx +++ b/static/js/ImageCropper.jsx @@ -4,7 +4,7 @@ import ReactCrop from 'react-image-crop'; import {LoadingRing} from "./Misc"; import 'react-image-crop/dist/ReactCrop.css'; -export const ImageCropper = ({loading, error, src, onClose, onSave}) => { +export const ImageCropper = ({loading, error, src, onClose, onSave, widthHeightRatio}) => { /** * loading - bool, is the image cropper loading data * error - str, error message @@ -15,7 +15,7 @@ export const ImageCropper = ({loading, error, src, onClose, onSave}) => { */ const imageRef = useRef(null); const [isFirstCropChange, setIsFirstCropChange] = useState(true); - const [crop, setCrop] = useState({unit: "px", width: 250, aspect: 1}); + const [crop, setCrop] = useState({unit: "px", width: 250, aspect: widthHeightRatio}); const [croppedImageBlob, setCroppedImageBlob] = useState(null); const onImageLoaded = (image) => {imageRef.current = image}; const onCropComplete = (crop) => { @@ -25,7 +25,7 @@ export const ImageCropper = ({loading, error, src, onClose, onSave}) => { if (isFirstCropChange) { const { clientWidth:width, clientHeight:height } = imageRef.current; crop.width = Math.min(width, height); - crop.height = crop.width; + crop.height = crop.width/widthHeightRatio; crop.x = (imageRef.current.width/2) - (crop.width/2); crop.y = (imageRef.current.height/2) - (crop.width/2); setCrop(crop); diff --git a/static/js/ProfilePic.jsx b/static/js/ProfilePic.jsx index 701e4b13bc..22ee188c07 100644 --- a/static/js/ProfilePic.jsx +++ b/static/js/ProfilePic.jsx @@ -106,6 +106,7 @@ export class ProfilePic extends Component { src={this.state.fileToCropSrc} onClose={this.onCloseCropper} onSave={this.upload} + widthHeightRatio={1} /> ); diff --git a/static/js/TopicEditor.jsx b/static/js/TopicEditor.jsx index 2e438d9e3c..54ff717f6e 100644 --- a/static/js/TopicEditor.jsx +++ b/static/js/TopicEditor.jsx @@ -86,11 +86,14 @@ const TopicPictureUploader = ({slug, callback, old_filename, caption}) => { const TopicPictureCropper = ({image_uri, slug, old_filename}) => { const [imageToCrop, setImageToCrop] = useState(null); + const [loading, setLoading] = useState(false); const onSave = (croppedImageBlob) => { + setLoading(true); uploadTopicImage(croppedImageBlob, old_filename, `_api/topics/images/secondary/${slug}`) .then((new_image_uri) => { //TODO propagate new_image_uri to TopicEditor setImageToCrop(null); + setLoading(false); }); } return ( @@ -98,8 +101,10 @@ const TopicPictureCropper = ({image_uri, slug, old_filename}) => { setImageToCrop(image_uri)} text="Upload Secondary Picture" /> setImageToCrop(null)} + widthHeightRatio={4/3} onSave={onSave}/> ); From 941b62478d6c8dbe763698953cf9713bd2766736 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Thu, 5 Dec 2024 09:35:10 +0200 Subject: [PATCH 029/127] refactor(topics): rename field to secondary_image_uri --- sefaria/helper/topic.py | 6 +++--- sefaria/model/topic.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/sefaria/helper/topic.py b/sefaria/helper/topic.py index e03971ce60..ba0c4fae50 100644 --- a/sefaria/helper/topic.py +++ b/sefaria/helper/topic.py @@ -1352,7 +1352,7 @@ def add_image_to_topic(topic_slug: str, image_uri: str, en_caption: str = "", he def add_secondary_image_to_topic(topic_slug: str, image_uri: str): topic = Topic.init(topic_slug) - topic.secondary_image = image_uri + topic.secondary_image_uri = image_uri topic.save() @@ -1365,6 +1365,6 @@ def delete_image_from_topic(topic_slug: str): def delete_secondary_image_from_topic(topic_slug: str): topic = Topic.init(topic_slug) - if hasattr(topic, "secondary_image"): - del topic.secondary_image + if hasattr(topic, "secondary_image_uri"): + del topic.secondary_image_uri topic.save() diff --git a/sefaria/model/topic.py b/sefaria/model/topic.py index 92b7df8b3c..5258cda71b 100644 --- a/sefaria/model/topic.py +++ b/sefaria/model/topic.py @@ -153,7 +153,7 @@ class Topic(abst.SluggedAbstractMongoRecord, AbstractTitledObject): 'isAmbiguous', # True if topic primary title can refer to multiple other topics "data_source", #any topic edited manually should display automatically in the TOC and this flag ensures this 'image', - 'secondary_image', + 'secondary_image_uri', "portal_slug", # slug to relevant Portal object ] From f04a009382872a04998b157d0506cecb85554899 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Thu, 5 Dec 2024 09:35:28 +0200 Subject: [PATCH 030/127] feat(topics): allow deleting and viewing secondary image --- static/js/TopicEditor.jsx | 66 ++++++++++++++++++++++++++++----------- 1 file changed, 47 insertions(+), 19 deletions(-) diff --git a/static/js/TopicEditor.jsx b/static/js/TopicEditor.jsx index 54ff717f6e..c3a900b918 100644 --- a/static/js/TopicEditor.jsx +++ b/static/js/TopicEditor.jsx @@ -39,6 +39,27 @@ const uploadTopicImage = function(imageBlob, old_filename, topic_image_api) { }; +const deleteTopicImage = (image_src, topic_image_api) => { + const old_filename_wout_url = image_src.split("/").slice(-1); + const url = `${Sefaria.apiHost}/${topic_image_api}?old_filename=${old_filename_wout_url}`; + return Sefaria.adminEditorApiRequest(url, null, null, "DELETE").then(() => alert("Deleted image.")); +} + +const CurrImageThumbnail = ({image_src, caption, deleteImage, removeButtonText}) => { + if (!image_src) { + return null; + } + return ( +
+
+ +
+ +
+ ); +}; + + const TopicPictureUploader = ({slug, callback, old_filename, caption}) => { /* `old_filename` is passed to API so that if it exists, it is deleted @@ -57,13 +78,14 @@ const TopicPictureUploader = ({slug, callback, old_filename, caption}) => { alert('The file is not an image'); } } + const deleteImage = () => { - const old_filename_wout_url = old_filename.split("/").slice(-1); - const url = `${Sefaria.apiHost}/_api/topics/images/${slug}?old_filename=${old_filename_wout_url}`; - Sefaria.adminEditorApiRequest(url, null, null, "DELETE").then(() => alert("Deleted image.")); - callback(""); - fileInput.current.value = ""; + deleteTopicImage(old_filename, `_api/topics/images/${slug}`).then(() => { + callback(""); + fileInput.current.value = ""; + }) } + return
- {old_filename !== "" &&
-
-
- -
- } + } -const TopicPictureCropper = ({image_uri, slug, old_filename}) => { +const TopicPictureCropper = ({slug, callback, old_filename, image_uri}) => { const [imageToCrop, setImageToCrop] = useState(null); const [loading, setLoading] = useState(false); + const onSave = (croppedImageBlob) => { setLoading(true); uploadTopicImage(croppedImageBlob, old_filename, `_api/topics/images/secondary/${slug}`) .then((new_image_uri) => { - //TODO propagate new_image_uri to TopicEditor + callback(new_image_uri); setImageToCrop(null); setLoading(false); }); } + + const deleteImage = () => { + deleteTopicImage(old_filename, `_api/topics/images/secondary/${slug}`).then(() => { + callback(""); + }) + } + return (
@@ -106,6 +131,7 @@ const TopicPictureCropper = ({image_uri, slug, old_filename}) => { onClose={() => setImageToCrop(null)} widthHeightRatio={4/3} onSave={onSave}/> +
); } @@ -126,7 +152,8 @@ const TopicEditor = ({origData, onCreateSuccess, close, origWasCat}) => { deathPlace: origData.origDeathPlace || "", enImgCaption: origData?.origImage?.image_caption?.en || "", heImgCaption: origData?.origImage?.image_caption?.he || "", - image_uri: origData?.origImage?.image_uri || "" + image_uri: origData?.origImage?.image_uri || "", + secondary_image_uri: origData?.secondary_image_uri || "", }); const isNew = !('origSlug' in origData); const [savingStatus, setSavingStatus] = useState(false); @@ -246,8 +273,8 @@ const TopicEditor = ({origData, onCreateSuccess, close, origWasCat}) => { }; const prepData = () => { - // always add category, title, heTitle, altTitles - let postData = { category: data.catSlug, titles: []}; + // always add category, title, heTitle, altTitles, secondary_img_uri + let postData = { category: data.catSlug, titles: [], secondary_image_uri: data.secondary_image_uri}; //convert title and altTitles to the database format, including extraction of disambiguation from title string postData['titles'].push(createPrimaryTitleObj(data.enTitle, 'en')); @@ -318,8 +345,9 @@ const TopicEditor = ({origData, onCreateSuccess, close, origWasCat}) => { alert("Unfortunately, there may have been an error saving this topic information: " + errorThrown.toString()); }); } - const handlePictureChange = (url) => { - data["image_uri"] = url; + const handlePictureChange = (url, secondary) => { + const key = secondary ? "secondary_image_uri" : "image_uri"; + data[key] = url; setChangedPicture(true); updateData({...data}); } @@ -345,7 +373,7 @@ const TopicEditor = ({origData, onCreateSuccess, close, origWasCat}) => { validate={validate} deleteObj={deleteObj} updateData={updateData} isNew={isNew} items={items} pictureUploader={} - secondaryPictureCropper={} + secondaryPictureCropper={ handlePictureChange(uri, true)} slug={data.origSlug} old_filename={data.secondary_image_uri} />} extras={ [isNew ? null : Date: Thu, 5 Dec 2024 09:45:58 +0200 Subject: [PATCH 031/127] fix(topics): pass secondary image to TopicEditor.jsx and default value for caption --- static/js/Misc.jsx | 2 +- static/js/TopicEditor.jsx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/static/js/Misc.jsx b/static/js/Misc.jsx index 47ec202ad0..a04a1bdebd 100644 --- a/static/js/Misc.jsx +++ b/static/js/Misc.jsx @@ -1021,7 +1021,7 @@ const EditorForExistingTopic = ({ toggle, data }) => { origDeathYear: data?.properties?.deathYear?.value, origEra: data?.properties?.era?.value, origImage: data?.image, - + origSecondaryImageUri: data?.secondary_image_uri, }; const origWasCat = "displays-above" in data?.links; diff --git a/static/js/TopicEditor.jsx b/static/js/TopicEditor.jsx index c3a900b918..1a722f0993 100644 --- a/static/js/TopicEditor.jsx +++ b/static/js/TopicEditor.jsx @@ -52,7 +52,7 @@ const CurrImageThumbnail = ({image_src, caption, deleteImage, removeButtonText}) return (

- +
@@ -153,7 +153,7 @@ const TopicEditor = ({origData, onCreateSuccess, close, origWasCat}) => { enImgCaption: origData?.origImage?.image_caption?.en || "", heImgCaption: origData?.origImage?.image_caption?.he || "", image_uri: origData?.origImage?.image_uri || "", - secondary_image_uri: origData?.secondary_image_uri || "", + secondary_image_uri: origData?.origSecondaryImageUri || "", }); const isNew = !('origSlug' in origData); const [savingStatus, setSavingStatus] = useState(false); From 6bd4c2cd84a5a8a2c140956d6659c61a1c4ee15b Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Sat, 7 Dec 2024 21:19:40 +0200 Subject: [PATCH 032/127] chore(topics): fix typing --- static/js/TopicEditor.jsx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/static/js/TopicEditor.jsx b/static/js/TopicEditor.jsx index 1a722f0993..a2af93250b 100644 --- a/static/js/TopicEditor.jsx +++ b/static/js/TopicEditor.jsx @@ -105,6 +105,11 @@ const TopicPictureCropper = ({slug, callback, old_filename, image_uri}) => { const [imageToCrop, setImageToCrop] = useState(null); const [loading, setLoading] = useState(false); + if (!image_uri) { + // no primary image so nothing to crop + return null; + } + const onSave = (croppedImageBlob) => { setLoading(true); uploadTopicImage(croppedImageBlob, old_filename, `_api/topics/images/secondary/${slug}`) From 7a94f5ea9c50140ef063c8b0ac0ed2833b4ca2e8 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Sat, 7 Dec 2024 21:22:31 +0200 Subject: [PATCH 033/127] chore(topics): update secondary image copy --- static/js/TopicEditor.jsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/static/js/TopicEditor.jsx b/static/js/TopicEditor.jsx index a2af93250b..c52fe820fd 100644 --- a/static/js/TopicEditor.jsx +++ b/static/js/TopicEditor.jsx @@ -129,7 +129,8 @@ const TopicPictureCropper = ({slug, callback, old_filename, image_uri}) => { return (
- setImageToCrop(image_uri)} text="Upload Secondary Picture" /> + This version of the topic's image will be shown on Topics Landing. + setImageToCrop(image_uri)} text="Edit Secondary Picture" /> Date: Sat, 7 Dec 2024 21:33:25 +0200 Subject: [PATCH 034/127] refactor(topics): use object spreading to modify crop which is more functional --- static/js/ImageCropper.jsx | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/static/js/ImageCropper.jsx b/static/js/ImageCropper.jsx index 48dc7a6a94..b94b8dc8c0 100644 --- a/static/js/ImageCropper.jsx +++ b/static/js/ImageCropper.jsx @@ -24,11 +24,13 @@ export const ImageCropper = ({loading, error, src, onClose, onSave, widthHeightR const onCropChange = (crop, percentCrop) => { if (isFirstCropChange) { const { clientWidth:width, clientHeight:height } = imageRef.current; - crop.width = Math.min(width, height); - crop.height = crop.width/widthHeightRatio; - crop.x = (imageRef.current.width/2) - (crop.width/2); - crop.y = (imageRef.current.height/2) - (crop.width/2); - setCrop(crop); + setCrop({ + ...crop, + width: Math.min(width, height), + height: crop.width/widthHeightRatio, + x: (imageRef.current.width/2) - (crop.width/2), + y: (imageRef.current.height/2) - (crop.width/2), + }); setIsFirstCropChange(false); } else { setCrop(crop); From 583ac53c74584870cb1d9330678d833e14cdee2e Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Sat, 7 Dec 2024 21:42:26 +0200 Subject: [PATCH 035/127] chore(topics): Revert using object spread for modifying crop since it skewed aspect ratio --- static/js/ImageCropper.jsx | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/static/js/ImageCropper.jsx b/static/js/ImageCropper.jsx index b94b8dc8c0..48dc7a6a94 100644 --- a/static/js/ImageCropper.jsx +++ b/static/js/ImageCropper.jsx @@ -24,13 +24,11 @@ export const ImageCropper = ({loading, error, src, onClose, onSave, widthHeightR const onCropChange = (crop, percentCrop) => { if (isFirstCropChange) { const { clientWidth:width, clientHeight:height } = imageRef.current; - setCrop({ - ...crop, - width: Math.min(width, height), - height: crop.width/widthHeightRatio, - x: (imageRef.current.width/2) - (crop.width/2), - y: (imageRef.current.height/2) - (crop.width/2), - }); + crop.width = Math.min(width, height); + crop.height = crop.width/widthHeightRatio; + crop.x = (imageRef.current.width/2) - (crop.width/2); + crop.y = (imageRef.current.height/2) - (crop.width/2); + setCrop(crop); setIsFirstCropChange(false); } else { setCrop(crop); From 84ff34d82123749b4d057bf848967c44091dcc65 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Sat, 7 Dec 2024 21:43:29 +0200 Subject: [PATCH 036/127] chore(topics): add div to make new line --- static/js/TopicEditor.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/static/js/TopicEditor.jsx b/static/js/TopicEditor.jsx index c52fe820fd..7d447623b0 100644 --- a/static/js/TopicEditor.jsx +++ b/static/js/TopicEditor.jsx @@ -129,7 +129,7 @@ const TopicPictureCropper = ({slug, callback, old_filename, image_uri}) => { return (
- This version of the topic's image will be shown on Topics Landing. +
This version of the topic's image will be shown on Topics Landing.
setImageToCrop(image_uri)} text="Edit Secondary Picture" /> Date: Sun, 8 Dec 2024 13:56:36 +0200 Subject: [PATCH 037/127] chore(topics): remove console logs --- static/js/ProfilePic.jsx | 3 --- 1 file changed, 3 deletions(-) diff --git a/static/js/ProfilePic.jsx b/static/js/ProfilePic.jsx index 22ee188c07..ec4adadbcf 100644 --- a/static/js/ProfilePic.jsx +++ b/static/js/ProfilePic.jsx @@ -40,7 +40,6 @@ export class ProfilePic extends Component { } const reader = new FileReader(); reader.addEventListener("load", () => this.setState({fileToCropSrc: reader.result})); - console.log("FILE", e.target.files[0]); reader.readAsDataURL(e.target.files[0]); } } @@ -51,10 +50,8 @@ export class ProfilePic extends Component { const formData = new FormData(); formData.append('file', croppedImageBlob); this.setState({ uploading: true }); - console.log("uploading") try { const response = await Sefaria.uploadProfilePhoto(formData); - console.log('responsse', response) if (response.error) { throw new Error(response.error); } else { From 8d1db737aa7c2afd59df5eb37127f04c4d14bf76 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Sun, 8 Dec 2024 22:15:05 +0200 Subject: [PATCH 038/127] fix(topics): don't allow aspect ratio to differ from specified aspect ratio --- static/js/ImageCropper.jsx | 38 +++++++++++++++++++++++++------------- 1 file changed, 25 insertions(+), 13 deletions(-) diff --git a/static/js/ImageCropper.jsx b/static/js/ImageCropper.jsx index 48dc7a6a94..d484b9f1de 100644 --- a/static/js/ImageCropper.jsx +++ b/static/js/ImageCropper.jsx @@ -17,6 +17,7 @@ export const ImageCropper = ({loading, error, src, onClose, onSave, widthHeightR const [isFirstCropChange, setIsFirstCropChange] = useState(true); const [crop, setCrop] = useState({unit: "px", width: 250, aspect: widthHeightRatio}); const [croppedImageBlob, setCroppedImageBlob] = useState(null); + const [internalError, setInternalError] = useState(null); const onImageLoaded = (image) => {imageRef.current = image}; const onCropComplete = (crop) => { makeClientCrop(crop); @@ -50,6 +51,13 @@ export const ImageCropper = ({loading, error, src, onClose, onSave, widthHeightR const scaleY = image.naturalHeight / image.height; canvas.width = crop.width * scaleX; canvas.height = crop.height * scaleY; + + const actualAspectRatio = canvas.width / canvas.height; + if (Math.abs(actualAspectRatio - widthHeightRatio) > 0.01) { + // in rare circumstances ReactCrop doesn't enforce aspect ratio properly + // catch these cases and inform user + setInternalError("Aspect ratio of image doesn't match allowed value. When this happens, refresh the page and try again."); + } const ctx = canvas.getContext("2d"); ctx.drawImage( image, @@ -78,15 +86,17 @@ export const ImageCropper = ({loading, error, src, onClose, onSave, widthHeightR setCrop({unit: "px", width: 250, aspect: 1}); setIsFirstCropChange(true); setCroppedImageBlob(null); + setInternalError(null); onClose(); } + const displayError = error || internalError; return (<> - { (src || !!error) && ( + { (src || displayError) && (
- { src ? + { displayError ? (
{ displayError }
) : () : (
{ error }
) + />) }
{ (loading || isFirstCropChange) ? (
) : ( @@ -105,16 +115,18 @@ export const ImageCropper = ({loading, error, src, onClose, onSave, widthHeightR Drag corners to crop image לחיתוך התמונה, גרור את הפינות
- + { !displayError ? ( + + ) : null}
) } From 7d0ebd5ec95e68e802620dc656c0f7d3dd60c6e7 Mon Sep 17 00:00:00 2001 From: Skyler Cohen Date: Mon, 9 Dec 2024 01:23:13 -0500 Subject: [PATCH 039/127] feat(newsletter subscriptions): Add ability for sidebar ads to have a sign-up form for newsletters and provide the option for additional newsletters to be chosen for a specific sidebar ad besides the default ones --- static/js/NewsletterSignUpForm.jsx | 5 +- static/js/Promotions.jsx | 81 +++++++++++++++++------------- static/js/context.js | 8 +++ static/js/sefaria/sefaria.js | 3 +- static/js/sefaria/strings.js | 1 + static/js/sefaria/util.js | 13 ----- 6 files changed, 61 insertions(+), 50 deletions(-) diff --git a/static/js/NewsletterSignUpForm.jsx b/static/js/NewsletterSignUpForm.jsx index 535384a001..b55572744e 100644 --- a/static/js/NewsletterSignUpForm.jsx +++ b/static/js/NewsletterSignUpForm.jsx @@ -6,6 +6,7 @@ export function NewsletterSignUpForm({ includeEducatorOption = true, emailPlaceholder = {en: 'Sign up for Newsletter', he: "הרשמו לניוזלטר"}, subscribe=Sefaria.subscribeSefariaNewsletter, // function which sends form data to API to subscribe + additionalNewsletterMailingLists = [], }) { const [email, setEmail] = useState(''); const [firstName, setFirstName] = useState(''); @@ -24,7 +25,7 @@ export function NewsletterSignUpForm({ if (showNameInputs === true) { // submit if (firstName.length > 0 && lastName.length > 0) { setSubscribeMessage("Subscribing..."); - subscribe(firstName, lastName, email, educatorCheck).then(res => { + subscribe(firstName, lastName, email, educatorCheck, additionalNewsletterMailingLists).then(res => { setSubscribeMessage("Subscribed! Welcome to our list."); Sefaria.track.event("Newsletter", "Subscribe from " + contextName, ""); }).catch(error => { @@ -32,7 +33,7 @@ export function NewsletterSignUpForm({ setShowNameInputs(false); }); } else { - setSubscribeMessage("Please enter a valid first and last name");// get he copy + setSubscribeMessage("Please enter a valid first and last name"); } } else if (Sefaria.util.isValidEmailAddress(email)) { setShowNameInputs(true); diff --git a/static/js/Promotions.jsx b/static/js/Promotions.jsx index 508fb24cf9..a3dd6c1e4f 100644 --- a/static/js/Promotions.jsx +++ b/static/js/Promotions.jsx @@ -4,6 +4,7 @@ import classNames from "classnames"; import Sefaria from "./sefaria/sefaria"; import {EnglishText, HebrewText, InterfaceText, OnInView} from "./Misc"; import $ from "./sefaria/sefariaJquery"; +import { NewsletterSignUpForm } from "./NewsletterSignUpForm"; const Promotions = () => { const [inAppAds, setInAppAds] = useState(Sefaria._inAppAds); // local cache @@ -36,6 +37,11 @@ const Promotions = () => { buttonIcon: sidebarAd.buttonIcon, buttonLocation: sidebarAd.buttonAboveOrBelow, hasBlueBackground: sidebarAd.hasBlueBackground, + isNewsletterSubscriptionInputForm: sidebarAd.isNewsletterSubscriptionInputForm, + mailingLists: + sidebarAd.newsletterMailingLists?.data.map( + (mailingLists) => mailingLists.attributes.newsletterName + ) ?? [], trigger: { showTo: sidebarAd.showTo, interfaceLang: "english", @@ -209,40 +215,47 @@ const SidebarAd = React.memo(({ context, matchingAd }) => { ); } - return ( - trackSidebarAdImpression(matchingAd)}> -
-

- {matchingAd.title} -

- {matchingAd.buttonLocation === "below" ? ( - <> -

- {matchingAd.bodyText} -

- {getButton()} - - ) : ( - <> - {getButton()} -

- {matchingAd.bodyText} -

- - )} -
-
- ); + const isHebrew = context.interfaceLang === "hebrew"; + const getLanguageClass = () => (isHebrew ? "int-he" : "int-en"); + + return ( + trackSidebarAdImpression(matchingAd)}> +
+

{matchingAd.title}

+ {matchingAd.buttonLocation === "below" ? ( + matchingAd.isNewsletterSubscriptionInputForm ? ( + <> +

{matchingAd.bodyText}

+ + + ) : ( + <> +

{matchingAd.bodyText}

+ {getButton()} + + ) + ) : matchingAd.isNewsletterSubscriptionInputForm ? ( + <> + +

{matchingAd.bodyText}

+ + ) : ( + <> + {getButton()} +

{matchingAd.bodyText}

+ + )} +
+
+ ); }); export { Promotions, GDocAdvertBox }; diff --git a/static/js/context.js b/static/js/context.js index 129b99a4be..36f9c2ee05 100644 --- a/static/js/context.js +++ b/static/js/context.js @@ -163,6 +163,14 @@ function StrapiDataProvider({ children }) { showTo startTime updatedAt + isNewsletterSubscriptionInputForm + newsletterMailingLists { + data { + attributes { + newsletterName + } + } + } } } } diff --git a/static/js/sefaria/sefaria.js b/static/js/sefaria/sefaria.js index be2da1ea30..4096bf5fd1 100644 --- a/static/js/sefaria/sefaria.js +++ b/static/js/sefaria/sefaria.js @@ -654,12 +654,13 @@ Sefaria = extend(Sefaria, { Sefaria._portals[portalSlug] = response; return response; }, - subscribeSefariaNewsletter: async function(firstName, lastName, email, educatorCheck) { + subscribeSefariaNewsletter: async function(firstName, lastName, email, educatorCheck, lists = []) { const payload = { language: Sefaria.interfaceLang === "hebrew" ? "he" : "en", educator: educatorCheck, firstName: firstName, lastName: lastName, + ...(lists?.length && { lists }), }; return await Sefaria.apiRequestWithBody(`/api/subscribe/${email}`, null, payload); }, diff --git a/static/js/sefaria/strings.js b/static/js/sefaria/strings.js index e99b29c75f..e2a958751b 100644 --- a/static/js/sefaria/strings.js +++ b/static/js/sefaria/strings.js @@ -500,6 +500,7 @@ const Strings = { "Please enter a valid email address.": 'כתובת הדוא"ל שהוזנה אינה תקינה.', "Subscribed! Welcome to our list.": "הרשמה בוצעה בהצלחה!", "Sorry, there was an error.": "סליחה, ארעה שגיאה", + "Please enter a valid first and last name.": "נא להוסיף שם פרטי ושם משפחה.", // Footer "Connect": "צרו קשר", diff --git a/static/js/sefaria/util.js b/static/js/sefaria/util.js index 31c5406d80..d9fe5527cf 100644 --- a/static/js/sefaria/util.js +++ b/static/js/sefaria/util.js @@ -112,19 +112,6 @@ class Util { }; const postData = {json: JSON.stringify(feedback)}; $.post('/api/send_feedback', postData); - } - static subscribeToNbList(email, lists) { - if (Sefaria.util.isValidEmailAddress(email)) { - $.post("/api/subscribe/" + email + "?lists=" + lists, function(data) { - if ("error" in data) { - console.log(data.error); - } else { - console.log("Subscribed! Welcome to our list."); - } - }).error(data => console.log("Sorry, there was an error.")); - } else { - console.log("not valid email address") - } } static naturalTimePlural(n, singular, plural) { return n <= 1 ? singular : plural; From b55098ef56c5f5280c240c71c5fd0f9a6b76d430 Mon Sep 17 00:00:00 2001 From: Skyler Cohen Date: Mon, 9 Dec 2024 02:07:30 -0500 Subject: [PATCH 040/127] fix(newsletter subscriptions): Fixes incorrect naming of property so data can flow properly to the sidebar ads for the new newsletter list --- static/js/Promotions.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/static/js/Promotions.jsx b/static/js/Promotions.jsx index a3dd6c1e4f..cce14cdfc6 100644 --- a/static/js/Promotions.jsx +++ b/static/js/Promotions.jsx @@ -38,7 +38,7 @@ const Promotions = () => { buttonLocation: sidebarAd.buttonAboveOrBelow, hasBlueBackground: sidebarAd.hasBlueBackground, isNewsletterSubscriptionInputForm: sidebarAd.isNewsletterSubscriptionInputForm, - mailingLists: + newsletterMailingLists: sidebarAd.newsletterMailingLists?.data.map( (mailingLists) => mailingLists.attributes.newsletterName ) ?? [], From 21b898e3ec6883ebabb179529d8fbdec750d8296 Mon Sep 17 00:00:00 2001 From: saengel Date: Tue, 10 Dec 2024 13:35:37 +0200 Subject: [PATCH 041/127] fix(bulktext): Fix API and ensure no broken topics --- sefaria/views.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/sefaria/views.py b/sefaria/views.py index 71bf51d404..5784da3fd1 100644 --- a/sefaria/views.py +++ b/sefaria/views.py @@ -401,13 +401,13 @@ def title_regex_api(request, titles, json_response=True): return jsonResponse({"error": "Unsupported HTTP method."}) if json_response else {"error": "Unsupported HTTP method."} -def bundle_many_texts(refs, useTextFamily=False, as_sized_string=False, min_char=None, max_char=None, translation_language_preference=None, english_version=None, hebrew_version=None): +def bundle_many_texts(refs, useTextFamily=0, as_sized_string=False, min_char=None, max_char=None, translation_language_preference=None, english_version=None, hebrew_version=None): res = {} for tref in refs: try: oref = model.Ref(tref) lang = "he" if has_hebrew(tref) else "en" - if useTextFamily: + if useTextFamily == 1: text_fam = model.TextFamily(oref, commentary=0, context=0, pad=False, translationLanguagePreference=translation_language_preference, stripItags=True, lang="he", version=hebrew_version, lang2="en", version2=english_version) @@ -474,7 +474,8 @@ def bulktext_api(request, refs): g = lambda x: request.GET.get(x, None) min_char = int(g("minChar")) if g("minChar") else None max_char = int(g("maxChar")) if g("maxChar") else None - res = bundle_many_texts(refs, g("useTextFamily"), g("asSizedString"), min_char, max_char, g("transLangPref"), g("ven"), g("vhe")) + useTextFamily = int(g("useTextFamily")) if g("useTextFamily") else None + res = bundle_many_texts(refs, useTextFamily, g("asSizedString"), min_char, max_char, g("transLangPref"), g("ven"), g("vhe")) resp = jsonResponse(res, cb) return resp From 4ace72e514eaeef1d1af853e8c7627b92c1bc155 Mon Sep 17 00:00:00 2001 From: saengel Date: Tue, 10 Dec 2024 14:08:59 +0200 Subject: [PATCH 042/127] chore(license): Add a license.md file --- static/LICENSE.md | 674 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 static/LICENSE.md diff --git a/static/LICENSE.md b/static/LICENSE.md new file mode 100644 index 0000000000..e72bfddabc --- /dev/null +++ b/static/LICENSE.md @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file From c0a2cf271654e5b24122e0bd1f43f56c69478048 Mon Sep 17 00:00:00 2001 From: saengel Date: Tue, 10 Dec 2024 19:14:09 +0200 Subject: [PATCH 043/127] fix(api): revert default param to None --- sefaria/views.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sefaria/views.py b/sefaria/views.py index 5784da3fd1..56f07a1281 100644 --- a/sefaria/views.py +++ b/sefaria/views.py @@ -401,7 +401,7 @@ def title_regex_api(request, titles, json_response=True): return jsonResponse({"error": "Unsupported HTTP method."}) if json_response else {"error": "Unsupported HTTP method."} -def bundle_many_texts(refs, useTextFamily=0, as_sized_string=False, min_char=None, max_char=None, translation_language_preference=None, english_version=None, hebrew_version=None): +def bundle_many_texts(refs, useTextFamily=None, as_sized_string=False, min_char=None, max_char=None, translation_language_preference=None, english_version=None, hebrew_version=None): res = {} for tref in refs: try: From e5a7f91cc291f9dcf2e5a10928d262e1a6a8f249 Mon Sep 17 00:00:00 2001 From: saengel Date: Wed, 11 Dec 2024 09:47:18 +0200 Subject: [PATCH 044/127] fix(api): Cleaner approach --- sefaria/views.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/sefaria/views.py b/sefaria/views.py index 56f07a1281..57e209005d 100644 --- a/sefaria/views.py +++ b/sefaria/views.py @@ -401,13 +401,13 @@ def title_regex_api(request, titles, json_response=True): return jsonResponse({"error": "Unsupported HTTP method."}) if json_response else {"error": "Unsupported HTTP method."} -def bundle_many_texts(refs, useTextFamily=None, as_sized_string=False, min_char=None, max_char=None, translation_language_preference=None, english_version=None, hebrew_version=None): +def bundle_many_texts(refs, use_text_family=False, as_sized_string=False, min_char=None, max_char=None, translation_language_preference=None, english_version=None, hebrew_version=None): res = {} for tref in refs: try: oref = model.Ref(tref) lang = "he" if has_hebrew(tref) else "en" - if useTextFamily == 1: + if use_text_family: text_fam = model.TextFamily(oref, commentary=0, context=0, pad=False, translationLanguagePreference=translation_language_preference, stripItags=True, lang="he", version=hebrew_version, lang2="en", version2=english_version) @@ -474,8 +474,8 @@ def bulktext_api(request, refs): g = lambda x: request.GET.get(x, None) min_char = int(g("minChar")) if g("minChar") else None max_char = int(g("maxChar")) if g("maxChar") else None - useTextFamily = int(g("useTextFamily")) if g("useTextFamily") else None - res = bundle_many_texts(refs, useTextFamily, g("asSizedString"), min_char, max_char, g("transLangPref"), g("ven"), g("vhe")) + use_text_family = True if g("useTextFamily") == "1" else False + res = bundle_many_texts(refs, use_text_family, g("asSizedString"), min_char, max_char, g("transLangPref"), g("ven"), g("vhe")) resp = jsonResponse(res, cb) return resp From c87edbcd5265988bce91acba1f5f310247c7516b Mon Sep 17 00:00:00 2001 From: YishaiGlasner Date: Wed, 11 Dec 2024 15:57:10 +0200 Subject: [PATCH 045/127] feat(link): add helper function remove_links_from_csv. --- sefaria/helper/link.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/sefaria/helper/link.py b/sefaria/helper/link.py index 85a591f322..340d63936c 100644 --- a/sefaria/helper/link.py +++ b/sefaria/helper/link.py @@ -554,6 +554,32 @@ def add_links_from_csv(file, linktype, generated_by, uid): logger.error(e) return {'message': f'{success} links succefully saved', 'errors': output.getvalue()} + +def remove_links_from_csv(file, uid): + csv.field_size_limit(sys.maxsize) + reader = csv.DictReader(StringIO(file.read().decode())) + success = 0 + output = StringIO() + errors_writer = csv.DictWriter(output, fieldnames=['ref1', 'ref2']) + errors_writer.writeheader() + for row in reader: + refs = list(row.values()) + try: + link = Link().load({'refs': refs}) + tracker.delete(uid, Link, link._id) + success += 1 + except Exception as e: + print(e, refs) + errors_writer.writerow({'ref1': refs[0], 'ref2': refs[1]}) + try: + if USE_VARNISH: + for ref in refs: + invalidate_ref(Ref(ref), purge=True) + except Exception as e: + logger.error(e) + return {'message': f'{success} links succefully removed', 'errors': output.getvalue()} + + def make_link_query(trefs, **additional_query): query = additional_query if trefs[1] == 'all': From 0cabb101032012da856a961d801d39852369b580 Mon Sep 17 00:00:00 2001 From: YishaiGlasner Date: Wed, 11 Dec 2024 15:57:48 +0200 Subject: [PATCH 046/127] feat(modtools): add option for removing links to links_upload_api. --- sefaria/views.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/sefaria/views.py b/sefaria/views.py index 71bf51d404..666254ca51 100644 --- a/sefaria/views.py +++ b/sefaria/views.py @@ -61,7 +61,7 @@ from sefaria.google_storage_manager import GoogleStorageManager from sefaria.sheets import get_sheet_categorization_info from reader.views import base_props, render_template -from sefaria.helper.link import add_links_from_csv, delete_links_from_text, get_csv_links_by_refs +from sefaria.helper.link import add_links_from_csv, delete_links_from_text, get_csv_links_by_refs, remove_links_from_csv if USE_VARNISH: from sefaria.system.varnish.wrapper import invalidate_index, invalidate_title, invalidate_ref, invalidate_counts, invalidate_all @@ -1363,14 +1363,19 @@ def links_upload_api(request): if request.method != "POST": return jsonResponse({"error": "Unsupported Method: {}".format(request.method)}) file = request.FILES['csv_file'] - linktype = request.POST.get("linkType") - generated_by = request.POST.get("projectName") + ' csv upload' uid = request.user.id + if request.POST.get('action') == "DELETE": + func = remove_links_from_csv + args = (file, uid) + else: + linktype = request.POST.get("linkType") + generated_by = request.POST.get("projectName") + ' csv upload' + func = add_links_from_csv + args = (file, linktype, generated_by, uid) try: - res = add_links_from_csv(file, linktype, generated_by, uid) + return jsonResponse({"status": "ok", "data": func(*args)}) except Exception as e: return HttpResponseBadRequest(e) - return jsonResponse({"status": "ok", "data": res}) def get_csv_links_by_refs_api(request, tref1, tref2, by_segment=False): try: From caf6f11692f391b3de679071071e9de9858fee1c Mon Sep 17 00:00:00 2001 From: YishaiGlasner Date: Wed, 11 Dec 2024 15:58:01 +0200 Subject: [PATCH 047/127] feat(modtools): add tool for removing links. --- static/js/ModeratorToolsPanel.jsx | 70 ++++++++++++++++++++++++++++++- 1 file changed, 69 insertions(+), 1 deletion(-) diff --git a/static/js/ModeratorToolsPanel.jsx b/static/js/ModeratorToolsPanel.jsx index 1791d14fde..98690a23f2 100644 --- a/static/js/ModeratorToolsPanel.jsx +++ b/static/js/ModeratorToolsPanel.jsx @@ -158,8 +158,13 @@ class ModeratorToolsPanel extends Component {
); + const removeLinksFromCsv = ( +
+ +
+ ); return (Sefaria.is_moderator)? -
{downloadSection}{uploadForm}{wflowyUpl}{uploadLinksFromCSV}{getLinks}
: +
{downloadSection}{uploadForm}{wflowyUpl}{uploadLinksFromCSV}{getLinks}{removeLinksFromCsv}
:
Tools are only available to logged in moderators.
; } } @@ -396,6 +401,69 @@ class UploadLinksFromCSV extends Component{ } } +const RemoveLinksFromCsv = () => { + const [hasFile, setHasFile] = useState(false); + const [uploadMessage, setUploadMessage] = useState(null); + const [errorMessage, setErrorMessage] = useState(null); + const handleFileChange = (event) => { + setHasFile(!!event.target.files[0]); + } + const handleSubmit = (event) => { + event.preventDefault(); + setUploadMessage("Uploading..."); + const data = new FormData(event.target); + data.append('action', 'DELETE'); + const request = new Request( + '/modtools/links', + {headers: {'X-CSRFToken': Cookies.get('csrftoken')}} + ); + fetch(request, { + method: 'POST', + mode: 'same-origin', + credentials: 'same-origin', + body: data + }).then(response => { + if (!response.ok) { + response.text().then(resp_text => { + setUploadMessage(null); + setErrorMessage(resp_text); + }) + } else { + response.json().then(resp_json => { + setUploadMessage(resp_json.data.message); + setErrorMessage(null); + if (resp_json.data.errors) { + let blob = new Blob([resp_json.data.errors], {type: "text/plain;charset=utf-8"}); + saveAs(blob, 'errors.csv'); + } + }); + } + }).catch(error => { + setUploadMessage(error.message); + setErrorMessage(null); + }); + }; + return ( +
+
Remove links
+ + {uploadMessage &&
{uploadMessage}
} + {errorMessage &&
} +
+ ); +}; + const InputRef = ({ id, value, handleChange, handleBlur, error }) => (
From 8029a1433ff2b8cb2c1c0c7de1b5b98adfdab774 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Wed, 11 Dec 2024 21:15:26 +0200 Subject: [PATCH 049/127] chore(topics): add analytics to topic toc --- static/js/NavSidebar.jsx | 18 ++++++++++-------- static/js/ReaderPanel.jsx | 12 +++++++++--- static/js/TopicPage.jsx | 17 ++++++++++++++--- static/js/TopicsPage.jsx | 18 +++++++++++++++--- static/js/analyticsEventTracker.js | 2 +- 5 files changed, 49 insertions(+), 18 deletions(-) diff --git a/static/js/NavSidebar.jsx b/static/js/NavSidebar.jsx index 38d0355549..ae37608165 100644 --- a/static/js/NavSidebar.jsx +++ b/static/js/NavSidebar.jsx @@ -590,14 +590,16 @@ const AboutTopics = ({hideTitle}) => ( const TrendingTopics = () => ( - - Trending Topics - {Sefaria.trendingTopics.map((topic, i) => -
- -
- )} -
+
+ + Trending Topics + {Sefaria.trendingTopics.map((topic, i) => +
+ +
+ )} +
+
); diff --git a/static/js/ReaderPanel.jsx b/static/js/ReaderPanel.jsx index 8197774615..d87d136218 100644 --- a/static/js/ReaderPanel.jsx +++ b/static/js/ReaderPanel.jsx @@ -618,15 +618,21 @@ class ReaderPanel extends Component { highlighted.click(); } getPanelType() { - const {menuOpen, tab} = this.state; + const {menuOpen, tab, navigationTopic, navigationTopicCategory} = this.state; if (menuOpen === "topics") { - return `${menuOpen}_${tab}`; + if (navigationTopicCategory) { + return "Topic Navigation"; + } else if (navigationTopic) { + return `${menuOpen}_${tab}`; + } else { + return "Topic Landing"; + } } } getPanelName() { const {menuOpen, navigationTopic, navigationTopicCategory} = this.state; if (menuOpen === "topics") { - return navigationTopicCategory || navigationTopic; + return navigationTopicCategory || navigationTopic || "Explore by Topic"; } } getPanelNumber() { diff --git a/static/js/TopicPage.jsx b/static/js/TopicPage.jsx index 198b974f22..b4455b794f 100644 --- a/static/js/TopicPage.jsx +++ b/static/js/TopicPage.jsx @@ -247,6 +247,9 @@ const TopicCategory = ({topic, topicTitle, setTopic, setNavTopic, compare, initi return (
@@ -272,10 +275,14 @@ const TopicCategory = ({topic, topicTitle, setTopic, setNavTopic, compare, initi } return ( -
+
-
+

@@ -546,11 +553,15 @@ const PortalNavSideBar = ({portal, entriesToDisplayList}) => { ) }; +const getPanelCategory = (slug) => { + return Sefaria.topicTocCategories(slug)?.map(({slug}) => slug)?.join('|'); +} + const getTopicPageAnalyticsData = (slug, langPref) => { return { project: "topics", content_lang: langPref || "bilingual", - panel_category: Sefaria.topicTocCategories(slug)?.map(({slug}) => slug)?.join('|'), + panel_category: getPanelCategory(slug), }; }; diff --git a/static/js/TopicsPage.jsx b/static/js/TopicsPage.jsx index c1b2b4fdfd..2a9e4d0c2d 100644 --- a/static/js/TopicsPage.jsx +++ b/static/js/TopicsPage.jsx @@ -18,7 +18,14 @@ const TopicsPage = ({setNavTopic, multiPanel, initialWidth}) => { const openCat = e => {e.preventDefault(); setNavTopic(cat.slug, {en: cat.en, he: cat.he})}; return (
- +
@@ -57,10 +64,15 @@ const TopicsPage = ({setNavTopic, multiPanel, initialWidth}) => { return ( -
+
-
+

Explore by Topic

diff --git a/static/js/analyticsEventTracker.js b/static/js/analyticsEventTracker.js index 5e0a43b925..3a4b622043 100644 --- a/static/js/analyticsEventTracker.js +++ b/static/js/analyticsEventTracker.js @@ -3,7 +3,7 @@ const AnalyticsEventTracker = (function() { 'project', 'panel_type', 'panel_number', 'item_id', 'version', 'content_lang', 'content_id', 'content_type', 'panel_name', 'panel_category', 'position', 'ai', 'text', 'experiment', 'feature_name', 'from', 'to', 'action', 'engagement_value', - 'engagement_type', 'logged_in', 'site_lang', 'traffic_type', 'promotion_name' + 'engagement_type', 'logged_in', 'site_lang', 'traffic_type', 'promotion_name', 'link_type', ]); const EVENT_ATTR = 'data-anl-event'; const FIELD_ATTR_PREFIX = 'data-anl-'; From dec37744143de781580b5208242e482f9a6d2f09 Mon Sep 17 00:00:00 2001 From: YishaiGlasner Date: Thu, 12 Dec 2024 10:37:57 +0200 Subject: [PATCH 050/127] fix(remove links modtool): sort refs before querying. --- sefaria/helper/link.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sefaria/helper/link.py b/sefaria/helper/link.py index 340d63936c..907353f9a1 100644 --- a/sefaria/helper/link.py +++ b/sefaria/helper/link.py @@ -563,7 +563,7 @@ def remove_links_from_csv(file, uid): errors_writer = csv.DictWriter(output, fieldnames=['ref1', 'ref2']) errors_writer.writeheader() for row in reader: - refs = list(row.values()) + refs = sorted(row.values()) try: link = Link().load({'refs': refs}) tracker.delete(uid, Link, link._id) From e8fd443a46c1588d5371c171e8159e62283a0dd4 Mon Sep 17 00:00:00 2001 From: YishaiGlasner Date: Thu, 12 Dec 2024 10:38:35 +0200 Subject: [PATCH 051/127] fix(remove links modtool): typos in message. --- sefaria/helper/link.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sefaria/helper/link.py b/sefaria/helper/link.py index 907353f9a1..d96556ad6f 100644 --- a/sefaria/helper/link.py +++ b/sefaria/helper/link.py @@ -552,7 +552,7 @@ def add_links_from_csv(file, linktype, generated_by, uid): invalidate_ref(Ref(ref), purge=True) except Exception as e: logger.error(e) - return {'message': f'{success} links succefully saved', 'errors': output.getvalue()} + return {'message': f'{success} links successfully saved', 'errors': output.getvalue()} def remove_links_from_csv(file, uid): @@ -577,7 +577,7 @@ def remove_links_from_csv(file, uid): invalidate_ref(Ref(ref), purge=True) except Exception as e: logger.error(e) - return {'message': f'{success} links succefully removed', 'errors': output.getvalue()} + return {'message': f'{success} links successfully removed', 'errors': output.getvalue()} def make_link_query(trefs, **additional_query): From 5a255bd4e76184c604b7977ca661a5327dfc0f6f Mon Sep 17 00:00:00 2001 From: YishaiGlasner Date: Thu, 12 Dec 2024 10:41:24 +0200 Subject: [PATCH 052/127] fix(modtools): mistake in UI string. --- static/js/ModeratorToolsPanel.jsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/static/js/ModeratorToolsPanel.jsx b/static/js/ModeratorToolsPanel.jsx index 403224448c..5d1b0840bb 100644 --- a/static/js/ModeratorToolsPanel.jsx +++ b/static/js/ModeratorToolsPanel.jsx @@ -137,7 +137,7 @@ class ModeratorToolsPanel extends Component {
Bulk Upload CSV - הורדת הטקסט + העלאה מ-CSV
From 1b9b83c70675242603171764d402d311d273b2f5 Mon Sep 17 00:00:00 2001 From: YishaiGlasner Date: Thu, 12 Dec 2024 10:57:39 +0200 Subject: [PATCH 053/127] feat(modtools): change returned errors file's name. --- static/js/ModeratorToolsPanel.jsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/static/js/ModeratorToolsPanel.jsx b/static/js/ModeratorToolsPanel.jsx index 5d1b0840bb..0a06946f1a 100644 --- a/static/js/ModeratorToolsPanel.jsx +++ b/static/js/ModeratorToolsPanel.jsx @@ -402,11 +402,11 @@ class UploadLinksFromCSV extends Component{ } const RemoveLinksFromCsv = () => { - const [hasFile, setHasFile] = useState(false); + const [fileName, setFileName] = useState(false); const [uploadMessage, setUploadMessage] = useState(null); const [errorMessage, setErrorMessage] = useState(null); const handleFileChange = (event) => { - setHasFile(!!event.target.files[0]); + setFileName(event.target.files[0] || null); } const handleSubmit = (event) => { event.preventDefault(); @@ -434,7 +434,7 @@ const RemoveLinksFromCsv = () => { setErrorMessage(null); if (resp_json.data.errors) { let blob = new Blob([resp_json.data.errors], {type: "text/plain;charset=utf-8"}); - saveAs(blob, 'errors.csv'); + saveAs(blob, `${fileName.name.split('.')[0]} - error report - undeleted links.csv`); } }); } @@ -456,7 +456,7 @@ const RemoveLinksFromCsv = () => { Please note that it should be the exact ref, so 'Genesis 1' is different than 'Genesis 1:1-31'
- + {uploadMessage &&
{uploadMessage}
} {errorMessage &&
} From 23bd030ff2a274dfeaf73aafbad8594a50eed85f Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Sat, 14 Dec 2024 22:10:08 +0200 Subject: [PATCH 054/127] fix(topics): keep track of categories for all topics in toc, not just leaves --- static/js/sefaria/sefaria.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/static/js/sefaria/sefaria.js b/static/js/sefaria/sefaria.js index aae230fedd..520fde8d89 100644 --- a/static/js/sefaria/sefaria.js +++ b/static/js/sefaria/sefaria.js @@ -2785,8 +2785,8 @@ _media: {}, this._topicTocCategory = this.topic_toc.reduce(this._initTopicTocCategoryReducer, {}); }, _initTopicTocCategoryReducer: function(a,c) { + a[c.slug] = c.parents; if (!c.children) { - a[c.slug] = c.parents; return a; } if (!c.parents) { From 1a4e5ac4f5d529a897ef616c4b434765480d77d4 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Sat, 14 Dec 2024 22:21:01 +0200 Subject: [PATCH 055/127] chore(topics): track clicks on trending topics --- static/js/NavSidebar.jsx | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/static/js/NavSidebar.jsx b/static/js/NavSidebar.jsx index ae37608165..920bab3535 100644 --- a/static/js/NavSidebar.jsx +++ b/static/js/NavSidebar.jsx @@ -590,12 +590,18 @@ const AboutTopics = ({hideTitle}) => ( const TrendingTopics = () => ( -
+
Trending Topics {Sefaria.trendingTopics.map((topic, i) => )} From 81decc6109ae88622d767fc5dab161d01b936bb8 Mon Sep 17 00:00:00 2001 From: Ephraim Date: Mon, 16 Dec 2024 17:59:01 +0200 Subject: [PATCH 056/127] ci: Only run pytests when pythin files are changed This adds a workflow library that filters files and checks before deploying a pytest sandbox to see if the PR even contains python changes This should hopefully allow client side changes to move through the CI piepline more easily --- .github/workflows/continuous.yaml | 56 ++++++++++++++++++++++++------- 1 file changed, 44 insertions(+), 12 deletions(-) diff --git a/.github/workflows/continuous.yaml b/.github/workflows/continuous.yaml index f2bfc417a8..bc09afdb55 100644 --- a/.github/workflows/continuous.yaml +++ b/.github/workflows/continuous.yaml @@ -178,13 +178,33 @@ jobs: - name: Handle Jest Test Results run: cat /home/runner/jestResults.json; STATUS=`jq ".numFailedTestSuites" /home/runner/jestResults.json`; exit $STATUS if: ${{ always() }} + check-python-files: + runs-on: ubuntu-latest + outputs: + python_files_changed: ${{ steps.check-python-files.outputs.python_files_changed }} + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Check for Python file changes + id: check-python-files + uses: dorny/paths-filter@v2 + with: + filters: | + python_files_changed: + - added|modified: + - '**/*.py' + - 'requirements.txt' + - 'setup.py' + - 'pyproject.toml' sandbox-deploy: name: "Continuous Testing: Sandbox Deploy" concurrency: group: dev-mongo cancel-in-progress: false - needs: [ build-derived ] - if: github.event.pull_request.draft == false + needs: [ build-derived, check-python-files ] + if: > + github.event.pull_request.draft == false && + needs.check-python-files.outputs.python_files_changed == 'true' runs-on: ubuntu-latest permissions: contents: 'read' @@ -236,7 +256,9 @@ jobs: PROJECT_ID: "${{ secrets.DEV_PROJECT }}" NAMESPACE: "${{secrets.DEV_SANDBOX_NAMESPACE}}" sandbox-ready: - if: github.event.pull_request.draft == false + if: > + github.event.pull_request.draft == false && + needs.check-python-files.outputs.python_files_changed == 'true' needs: sandbox-deploy runs-on: ubuntu-latest steps: @@ -256,8 +278,10 @@ jobs: concurrency: group: dev-mongo cancel-in-progress: false - needs: [ sandbox-ready ] - if: github.event.pull_request.draft == false + needs: [ sandbox-ready, check-python-files ] + if: > + github.event.pull_request.draft == false && + needs.check-python-files.outputs.python_files_changed == 'true' permissions: contents: 'read' id-token: 'write' @@ -376,11 +400,17 @@ jobs: run: helm delete sandbox-${{ steps.get-sha.outputs.sha_short }} -n ${{ secrets.DEV_SANDBOX_NAMESPACE }} --debug --timeout 10m0s if: steps.get-helm.outputs.count > 0 continuous-branch-protection: - needs: [ build-generic, build-derived, sandbox-deploy, sandbox-ready, pytest-job ] + needs: + - build-generic + - build-derived + - check-python-files + - sandbox-deploy + - sandbox-ready + - pytest-job runs-on: ubuntu-latest if: always() steps: - - name: + - name: run: | if [ "${{ github.event_name }}" == "merge_group" ]; then exit 0 @@ -391,10 +421,12 @@ jobs: exit 1 fi if [ "${{ github.event.pull_request.draft }}" == "false" ]; then - if [ "${{ needs.sandbox-deploy.result }}" != "success" ] || \ - [ "${{ needs.sandbox-ready.result }}" != "success" ] || \ - [ "${{ needs.pytest-job.result }}" != "success" ]; then - echo "One or more test jobs failed" - exit 1 + if [ "${{ needs.check-python-files.outputs.python_files_changed }}" == "true" ]; then + if [ "${{ needs.sandbox-deploy.result }}" != "success" ] || \ + [ "${{ needs.sandbox-ready.result }}" != "success" ] || \ + [ "${{ needs.pytest-job.result }}" != "success" ]; then + echo "One or more Python-related test jobs failed" + exit 1 + fi fi fi From 3cde51ee1c920395083227d55d973477d68ba7d9 Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Tue, 17 Dec 2024 10:46:18 +0200 Subject: [PATCH 057/127] test(topics): fix topic tests by using pytest django fixtures --- requirements.txt | 2 +- sefaria/model/tests/topic_test.py | 26 +++++++++++++++++++------- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/requirements.txt b/requirements.txt index c1219d9635..816901a128 100644 --- a/requirements.txt +++ b/requirements.txt @@ -69,7 +69,7 @@ undecorated==0.3.0 unicodecsv==0.14.1 unidecode==1.1.1 user-agents==2.2.0 - +pytest-django==4.9.* #opentelemetry-distro #opentelemetry-exporter-otlp diff --git a/sefaria/model/tests/topic_test.py b/sefaria/model/tests/topic_test.py index 47c8ceb5e5..d5d56c6b87 100644 --- a/sefaria/model/tests/topic_test.py +++ b/sefaria/model/tests/topic_test.py @@ -1,9 +1,11 @@ import pytest + from sefaria.model.topic import Topic, TopicSet, IntraTopicLink, RefTopicLink, TopicLinkHelper, IntraTopicLinkSet, RefTopicLinkSet from sefaria.model.text import Ref -from sefaria.system.database import db +from sefaria.system.database import db as mongo_db from sefaria.system.exceptions import SluggedMongoRecordMissingError from django_topics.models import Topic as DjangoTopic, TopicPool +from django_topics.models.pool import PoolType def make_topic(slug): @@ -42,8 +44,15 @@ def clean_links(a): ls.delete() -@pytest.fixture(scope='module') -def topic_graph(): +@pytest.fixture(autouse=True) +def topic_pools(db): + TopicPool.objects.create(name=PoolType.LIBRARY.value) + TopicPool.objects.create(name=PoolType.SHEETS.value) + + + +@pytest.fixture() +def topic_graph(db): isa_links = [ (1, 2), (2, 3), @@ -68,8 +77,8 @@ def topic_graph(): v.delete() -@pytest.fixture(scope='module') -def topic_graph_to_merge(): +@pytest.fixture +def topic_graph_to_merge(db): isa_links = [ (10, 20), (20, 30), @@ -87,7 +96,7 @@ def topic_graph_to_merge(): }, 'links': [make_it_link(str(a), str(b), 'is-a') for a, b in isa_links] + [make_rt_link('10', r) for r in trefs] + [make_rt_link('20', r) for r in trefs1] + [make_rt_link('40', r) for r in trefs2] } - db.sheets.insert_one({ + mongo_db.sheets.insert_one({ "id": 1234567890, "topics": [ {"slug": '20', 'asTyped': 'twenty'}, @@ -102,7 +111,7 @@ def topic_graph_to_merge(): v.delete() for v in graph['links']: v.delete() - db.sheets.delete_one({"id": 1234567890}) + mongo_db.sheets.delete_one({"id": 1234567890}) @pytest.fixture(scope='module') @@ -114,6 +123,7 @@ def topic_pool(): class TestTopics(object): + @pytest.mark.django_db def test_graph_funcs(self, topic_graph): ts = topic_graph['topics'] assert ts['1'].get_types() == {'1', '2', '3', '4', '5'} @@ -143,6 +153,7 @@ def test_link_set(self, topic_graph): ls = ts['1'].link_set(_class=None) assert {getattr(l, 'ref', getattr(l, 'topic', None)) for l in ls} == (trefs | {'2'}) + @pytest.mark.django_db def test_merge(self, topic_graph_to_merge): ts = topic_graph_to_merge['topics'] ts['20'].merge(ts['40']) @@ -177,6 +188,7 @@ def test_change_title(self, topic_graph): dt1 = DjangoTopic.objects.get(slug=ts['1'].slug) assert dt1.en_title == ts['1'].get_primary_title('en') + @pytest.mark.django_db def test_pools(self, topic_graph, topic_pool): ts = topic_graph['topics'] t1 = ts['1'] From 043796abe8f711b7084b2482bec28576168b8fbc Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Tue, 17 Dec 2024 11:33:57 +0200 Subject: [PATCH 058/127] test(topics): use test slug prefix to guarentee that slugs don't collide with existing mongo slugs. In the past, this didn't matter because we could delete any slugs that collided. However, deleting now triggers django topics to be queried and these topics don't exist in django topics because django topics are fully encapsulated in tests. --- sefaria/model/tests/topic_test.py | 145 ++++++++++++++++-------------- 1 file changed, 78 insertions(+), 67 deletions(-) diff --git a/sefaria/model/tests/topic_test.py b/sefaria/model/tests/topic_test.py index d5d56c6b87..f27a902417 100644 --- a/sefaria/model/tests/topic_test.py +++ b/sefaria/model/tests/topic_test.py @@ -7,8 +7,20 @@ from django_topics.models import Topic as DjangoTopic, TopicPool from django_topics.models.pool import PoolType +TEST_SLUG_PREFIX = 'this-is-a-test-slug-' -def make_topic(slug): + +def _ms(slug_suffix): + """ + ms = make slug. makes full test slug. + @param slug_suffix: + @return: + """ + return TEST_SLUG_PREFIX+slug_suffix + + +def make_topic(slug_suffix): + slug = _ms(slug_suffix) ts = TopicSet({'slug': slug}) if ts.count() > 0: ts.delete() @@ -18,13 +30,13 @@ def make_topic(slug): def make_it_link(a, b, type): - l = IntraTopicLink({'fromTopic': a, 'toTopic': b, 'linkType': type, 'dataSource': 'sefaria'}) + l = IntraTopicLink({'fromTopic': _ms(a), 'toTopic': _ms(b), 'linkType': type, 'dataSource': 'sefaria'}) l.save() return l def make_rt_link(a, tref): - l = RefTopicLink({'toTopic': a, 'ref': tref, 'linkType': 'about', 'dataSource': 'sefaria'}) + l = RefTopicLink({'toTopic': _ms(a), 'ref': tref, 'linkType': 'about', 'dataSource': 'sefaria'}) l.save() return l @@ -35,11 +47,11 @@ def clean_links(a): :param a: :return: """ - ls = RefTopicLinkSet({'toTopic': a}) + ls = RefTopicLinkSet({'toTopic': _ms(a)}) if ls.count() > 0: ls.delete() - ls = IntraTopicLinkSet({"$or": [{"fromTopic": a}, {"toTopic": a}]}) + ls = IntraTopicLinkSet({"$or": [{"fromTopic": _ms(a)}, {"toTopic": _ms(a)}]}) if ls.count() > 0: ls.delete() @@ -99,10 +111,10 @@ def topic_graph_to_merge(db): mongo_db.sheets.insert_one({ "id": 1234567890, "topics": [ - {"slug": '20', 'asTyped': 'twenty'}, - {"slug": '40', 'asTyped': '4d'}, - {"slug": '20', 'asTyped': 'twent-e'}, - {"slug": '30', 'asTyped': 'thirty'} + {"slug": _ms('20'), 'asTyped': 'twenty'}, + {"slug": _ms('40'), 'asTyped': '4d'}, + {"slug": _ms('20'), 'asTyped': 'twent-e'}, + {"slug": _ms('30'), 'asTyped': 'thirty'} ] }) @@ -114,8 +126,8 @@ def topic_graph_to_merge(db): mongo_db.sheets.delete_one({"id": 1234567890}) -@pytest.fixture(scope='module') -def topic_pool(): +@pytest.fixture() +def topic_pool(db): pool = TopicPool.objects.create(name='test-pool') yield pool pool.delete() @@ -126,24 +138,24 @@ class TestTopics(object): @pytest.mark.django_db def test_graph_funcs(self, topic_graph): ts = topic_graph['topics'] - assert ts['1'].get_types() == {'1', '2', '3', '4', '5'} - assert ts['2'].get_types() == {'2', '3', '4', '5'} - assert ts['5'].get_types() == {'5'} + assert ts['1'].get_types() == {_ms(x) for x in {'1', '2', '3', '4', '5'}} + assert ts['2'].get_types() == {_ms(x) for x in {'2', '3', '4', '5'}} + assert ts['5'].get_types() == {_ms('5')} - assert ts['1'].has_types({'3', '8'}) - assert not ts['2'].has_types({'6'}) + assert ts['1'].has_types({_ms('3'), _ms('8')}) + assert not ts['2'].has_types({_ms('6')}) - assert {t.slug for t in ts['5'].topics_by_link_type_recursively(linkType='is-a', only_leaves=True)} == {'1', '6'} + assert {t.slug for t in ts['5'].topics_by_link_type_recursively(linkType='is-a', only_leaves=True)} == {_ms('1'), _ms('6')} assert ts['1'].topics_by_link_type_recursively(linkType='is-a', only_leaves=True) == [ts['1']] def test_link_set(self, topic_graph): ts = topic_graph['topics'] ls = ts['1'].link_set(_class='intraTopic') - assert list(ls)[0].topic == '2' + assert list(ls)[0].topic == _ms('2') assert ls.count() == 1 ls = ts['4'].link_set(_class='intraTopic') - assert {l.topic for l in ls} == {'2', '5'} + assert {l.topic for l in ls} == {_ms('2'), _ms('5')} trefs = {r.normal() for r in Ref('Genesis 1:1-10').range_list()} @@ -151,33 +163,33 @@ def test_link_set(self, topic_graph): assert {l.ref for l in ls} == trefs ls = ts['1'].link_set(_class=None) - assert {getattr(l, 'ref', getattr(l, 'topic', None)) for l in ls} == (trefs | {'2'}) + assert {getattr(l, 'ref', getattr(l, 'topic', None)) for l in ls} == (trefs | {_ms('2')}) @pytest.mark.django_db def test_merge(self, topic_graph_to_merge): ts = topic_graph_to_merge['topics'] ts['20'].merge(ts['40']) - t20 = Topic.init('20') - assert t20.slug == '20' + t20 = Topic.init(_ms('20')) + assert t20.slug == _ms('20') assert len(t20.titles) == 2 - assert t20.get_primary_title('en') == '20' + assert t20.get_primary_title('en') == _ms('20') ls = t20.link_set(_class='intraTopic') - assert {l.topic for l in ls} == {'10', '30', '50'} + assert {l.topic for l in ls} == {_ms(x) for x in {'10', '30', '50'}} - s = db.sheets.find_one({"id": 1234567890}) + s = mongo_db.sheets.find_one({"id": 1234567890}) assert s['topics'] == [ - {"slug": '20', 'asTyped': 'twenty'}, - {"slug": '20', 'asTyped': '4d'}, - {"slug": '20', 'asTyped': 'twent-e'}, - {"slug": '30', 'asTyped': 'thirty'} + {"slug": _ms('20'), 'asTyped': 'twenty'}, + {"slug": _ms('20'), 'asTyped': '4d'}, + {"slug": _ms('20'), 'asTyped': 'twent-e'}, + {"slug": _ms('30'), 'asTyped': 'thirty'} ] - t40 = Topic.init('40') + t40 = Topic.init(_ms('40')) assert t40 is None - DjangoTopic.objects.get(slug='20') + DjangoTopic.objects.get(slug=_ms('20')) with pytest.raises(DjangoTopic.DoesNotExist): - DjangoTopic.objects.get(slug='40') + DjangoTopic.objects.get(slug=_ms('40')) def test_change_title(self, topic_graph): ts = topic_graph['topics'] @@ -192,18 +204,17 @@ def test_change_title(self, topic_graph): def test_pools(self, topic_graph, topic_pool): ts = topic_graph['topics'] t1 = ts['1'] - assert len(t1.get_pools()) == 0 t1.add_pool(topic_pool.name) - assert t1.get_pools() == [topic_pool.name] + assert topic_pool.name in t1.get_pools() # dont add duplicates t1.add_pool(topic_pool.name) - assert t1.get_pools() == [topic_pool.name] + assert t1.get_pools().count(topic_pool.name) == 1 assert t1.has_pool(topic_pool.name) t1.remove_pool(topic_pool.name) - assert len(t1.get_pools()) == 0 - # dont error when removing non-existant pool + assert topic_pool.name not in t1.get_pools() + # dont error when removing non-existent pool t1.remove_pool(topic_pool.name) def test_sanitize(self): @@ -223,8 +234,8 @@ def test_sanitize(self): class TestTopicLinkHelper(object): def test_init_by_class(self, topic_graph): - l1 = db.topic_links.find_one({'fromTopic': '1', 'toTopic': '2', 'linkType': 'is-a'}) - l2 = db.topic_links.find_one({'toTopic': '1', 'ref': 'Genesis 1:1'}) + l1 = mongo_db.topic_links.find_one({'fromTopic': _ms('1'), 'toTopic': _ms('2'), 'linkType': 'is-a'}) + l2 = mongo_db.topic_links.find_one({'toTopic': _ms('1'), 'ref': 'Genesis 1:1'}) obj = TopicLinkHelper.init_by_class(l1) assert isinstance(obj, IntraTopicLink) @@ -232,12 +243,12 @@ def test_init_by_class(self, topic_graph): obj = TopicLinkHelper.init_by_class(l2) assert isinstance(obj, RefTopicLink) - obj = TopicLinkHelper.init_by_class(l1, context_slug='2') - assert obj.topic == '1' + obj = TopicLinkHelper.init_by_class(l1, context_slug=_ms('2')) + assert obj.topic == _ms('1') assert obj.is_inverse - obj = TopicLinkHelper.init_by_class(l1, context_slug='1') - assert obj.topic == '2' + obj = TopicLinkHelper.init_by_class(l1, context_slug=_ms('1')) + assert obj.topic == _ms('2') class TestIntraTopicLink(object): @@ -246,8 +257,8 @@ def test_validate(self, topic_graph): from sefaria.system.exceptions import DuplicateRecordError, InputError attrs = { - 'fromTopic': '1', - 'toTopic': '6', + 'fromTopic': _ms('1'), + 'toTopic': _ms('6'), 'linkType': 'is-a', 'dataSource': 'sefaria' } @@ -257,8 +268,8 @@ def test_validate(self, topic_graph): l.delete() attrs = { - 'fromTopic': '1', - 'toTopic': '2', + 'fromTopic': _ms('1'), + 'toTopic': _ms('2'), 'linkType': 'is-a', 'dataSource': 'sefaria' } @@ -266,10 +277,10 @@ def test_validate(self, topic_graph): with pytest.raises(DuplicateRecordError): l.save() - # non-existant datasource + # non-existent datasource attrs = { - 'fromTopic': '1', - 'toTopic': '2', + 'fromTopic': _ms('1'), + 'toTopic': _ms('2'), 'linkType': 'is-a', 'dataSource': 'blahblah' } @@ -277,10 +288,10 @@ def test_validate(self, topic_graph): with pytest.raises(SluggedMongoRecordMissingError): l.save() - # non-existant toTopic + # non-existent toTopic attrs = { - 'fromTopic': '1', - 'toTopic': '2222', + 'fromTopic': _ms('1'), + 'toTopic': _ms('2222'), 'linkType': 'is-a', 'dataSource': 'sefaria' } @@ -288,10 +299,10 @@ def test_validate(self, topic_graph): with pytest.raises(SluggedMongoRecordMissingError): l.save() - # non-existant fromTopic + # non-existent fromTopic attrs = { - 'fromTopic': '11111', - 'toTopic': '2', + 'fromTopic': _ms('11111'), + 'toTopic': _ms('2'), 'linkType': 'is-a', 'dataSource': 'sefaria' } @@ -299,10 +310,10 @@ def test_validate(self, topic_graph): with pytest.raises(SluggedMongoRecordMissingError): l.save() - # non-existant linkType + # non-existent linkType attrs = { - 'fromTopic': '11111', - 'toTopic': '2', + 'fromTopic': _ms('11111'), + 'toTopic': _ms('2'), 'linkType': 'is-aaaaaa', 'dataSource': 'sefaria' } @@ -312,15 +323,15 @@ def test_validate(self, topic_graph): # duplicate for symmetric linkType attrs = { - 'fromTopic': '1', - 'toTopic': '2', + 'fromTopic': _ms('1'), + 'toTopic': _ms('2'), 'linkType': 'related-to', 'dataSource': 'sefaria' } l1 = IntraTopicLink(attrs) l1.save() - attrs['fromTopic'] = '2' - attrs['toTopic'] = '1' + attrs['fromTopic'] = _ms('2') + attrs['toTopic'] = _ms('1') l2 = IntraTopicLink(attrs) with pytest.raises(DuplicateRecordError): l2.save() @@ -332,7 +343,7 @@ class TestRefTopicLink(object): def test_add_expanded_refs(self, topic_graph): attrs = { 'ref': 'Genesis 1:1', - 'toTopic': '6', + 'toTopic': _ms('6'), 'linkType': 'about', 'dataSource': 'sefaria' } @@ -344,7 +355,7 @@ def test_add_expanded_refs(self, topic_graph): attrs = { 'ref': 'Genesis 1:1-3', - 'toTopic': '6', + 'toTopic': _ms('6'), 'linkType': 'about', 'dataSource': 'sefaria' } @@ -355,7 +366,7 @@ def test_add_expanded_refs(self, topic_graph): attrs = { 'ref': 'Genesis 1-2', - 'toTopic': '6', + 'toTopic': _ms('6'), 'linkType': 'about', 'dataSource': 'sefaria' } @@ -370,7 +381,7 @@ def test_duplicate(self, topic_graph): attrs = { 'ref': 'Genesis 1:1', - 'toTopic': '6', + 'toTopic': _ms('6'), 'linkType': 'about', 'dataSource': 'sefaria' } From 678e116c9e1f9f49a34e659bda6ce168f6a5b71a Mon Sep 17 00:00:00 2001 From: nsantacruz Date: Tue, 17 Dec 2024 11:59:26 +0200 Subject: [PATCH 059/127] test(topics): use django_db_blocker.unblock() to make fixutes scope module again --- sefaria/model/tests/topic_test.py | 159 +++++++++++++++--------------- 1 file changed, 77 insertions(+), 82 deletions(-) diff --git a/sefaria/model/tests/topic_test.py b/sefaria/model/tests/topic_test.py index f27a902417..f7e9e97e9b 100644 --- a/sefaria/model/tests/topic_test.py +++ b/sefaria/model/tests/topic_test.py @@ -7,8 +7,6 @@ from django_topics.models import Topic as DjangoTopic, TopicPool from django_topics.models.pool import PoolType -TEST_SLUG_PREFIX = 'this-is-a-test-slug-' - def _ms(slug_suffix): """ @@ -16,7 +14,7 @@ def _ms(slug_suffix): @param slug_suffix: @return: """ - return TEST_SLUG_PREFIX+slug_suffix + return 'this-is-a-test-slug-'+slug_suffix def make_topic(slug_suffix): @@ -56,86 +54,88 @@ def clean_links(a): ls.delete() -@pytest.fixture(autouse=True) -def topic_pools(db): - TopicPool.objects.create(name=PoolType.LIBRARY.value) - TopicPool.objects.create(name=PoolType.SHEETS.value) - - - -@pytest.fixture() -def topic_graph(db): - isa_links = [ - (1, 2), - (2, 3), - (2, 4), - (4, 5), - (6, 5), - ] - trefs = [r.normal() for r in Ref('Genesis 1:1-10').range_list()] - for a, b in isa_links: - clean_links(str(a)) - clean_links(str(b)) - graph = { - 'topics': { - str(i): make_topic(str(i)) for i in range(1, 10) - }, - 'links': [make_it_link(str(a), str(b), 'is-a') for a, b in isa_links] + [make_rt_link('1', r) for r in trefs] - } - yield graph - for k, v in graph['topics'].items(): - v.delete() - for v in graph['links']: - v.delete() - - -@pytest.fixture -def topic_graph_to_merge(db): - isa_links = [ - (10, 20), - (20, 30), - (20, 40), - (40, 50), - (60, 50), - ] - trefs = [r.normal() for r in Ref('Genesis 1:1-10').range_list()] - trefs1 = [r.normal() for r in Ref('Exodus 1:1-10').range_list()] - trefs2 = [r.normal() for r in Ref('Leviticus 1:1-10').range_list()] - - graph = { - 'topics': { - str(i): make_topic(str(i)) for i in range(10, 100, 10) - }, - 'links': [make_it_link(str(a), str(b), 'is-a') for a, b in isa_links] + [make_rt_link('10', r) for r in trefs] + [make_rt_link('20', r) for r in trefs1] + [make_rt_link('40', r) for r in trefs2] - } - mongo_db.sheets.insert_one({ - "id": 1234567890, - "topics": [ - {"slug": _ms('20'), 'asTyped': 'twenty'}, - {"slug": _ms('40'), 'asTyped': '4d'}, - {"slug": _ms('20'), 'asTyped': 'twent-e'}, - {"slug": _ms('30'), 'asTyped': 'thirty'} - ] - }) - - yield graph - for k, v in graph['topics'].items(): - v.delete() - for v in graph['links']: - v.delete() - mongo_db.sheets.delete_one({"id": 1234567890}) +@pytest.fixture(scope='module', autouse=True) +def library_and_sheets_topic_pools(django_db_setup, django_db_blocker): + with django_db_blocker.unblock(): + TopicPool.objects.create(name=PoolType.LIBRARY.value) + TopicPool.objects.create(name=PoolType.SHEETS.value) -@pytest.fixture() -def topic_pool(db): - pool = TopicPool.objects.create(name='test-pool') - yield pool - pool.delete() +@pytest.fixture(scope='module') +def topic_graph(django_db_setup, django_db_blocker): + with django_db_blocker.unblock(): + isa_links = [ + (1, 2), + (2, 3), + (2, 4), + (4, 5), + (6, 5), + ] + trefs = [r.normal() for r in Ref('Genesis 1:1-10').range_list()] + for a, b in isa_links: + clean_links(str(a)) + clean_links(str(b)) + graph = { + 'topics': { + str(i): make_topic(str(i)) for i in range(1, 10) + }, + 'links': [make_it_link(str(a), str(b), 'is-a') for a, b in isa_links] + [make_rt_link('1', r) for r in trefs] + } + yield graph + for k, v in graph['topics'].items(): + v.delete() + for v in graph['links']: + v.delete() + + +@pytest.fixture(scope='module') +def topic_graph_to_merge(django_db_setup, django_db_blocker): + with django_db_blocker.unblock(): + isa_links = [ + (10, 20), + (20, 30), + (20, 40), + (40, 50), + (60, 50), + ] + trefs = [r.normal() for r in Ref('Genesis 1:1-10').range_list()] + trefs1 = [r.normal() for r in Ref('Exodus 1:1-10').range_list()] + trefs2 = [r.normal() for r in Ref('Leviticus 1:1-10').range_list()] + + graph = { + 'topics': { + str(i): make_topic(str(i)) for i in range(10, 100, 10) + }, + 'links': [make_it_link(str(a), str(b), 'is-a') for a, b in isa_links] + [make_rt_link('10', r) for r in trefs] + [make_rt_link('20', r) for r in trefs1] + [make_rt_link('40', r) for r in trefs2] + } + mongo_db.sheets.insert_one({ + "id": 1234567890, + "topics": [ + {"slug": _ms('20'), 'asTyped': 'twenty'}, + {"slug": _ms('40'), 'asTyped': '4d'}, + {"slug": _ms('20'), 'asTyped': 'twent-e'}, + {"slug": _ms('30'), 'asTyped': 'thirty'} + ] + }) + + yield graph + for k, v in graph['topics'].items(): + v.delete() + for v in graph['links']: + v.delete() + mongo_db.sheets.delete_one({"id": 1234567890}) + + +@pytest.fixture(scope='module') +def topic_pool(django_db_setup, django_db_blocker): + with django_db_blocker.unblock(): + pool = TopicPool.objects.create(name='test-pool') + yield pool + pool.delete() class TestTopics(object): - @pytest.mark.django_db def test_graph_funcs(self, topic_graph): ts = topic_graph['topics'] assert ts['1'].get_types() == {_ms(x) for x in {'1', '2', '3', '4', '5'}} @@ -165,7 +165,6 @@ def test_link_set(self, topic_graph): ls = ts['1'].link_set(_class=None) assert {getattr(l, 'ref', getattr(l, 'topic', None)) for l in ls} == (trefs | {_ms('2')}) - @pytest.mark.django_db def test_merge(self, topic_graph_to_merge): ts = topic_graph_to_merge['topics'] ts['20'].merge(ts['40']) @@ -200,7 +199,6 @@ def test_change_title(self, topic_graph): dt1 = DjangoTopic.objects.get(slug=ts['1'].slug) assert dt1.en_title == ts['1'].get_primary_title('en') - @pytest.mark.django_db def test_pools(self, topic_graph, topic_pool): ts = topic_graph['topics'] t1 = ts['1'] @@ -228,9 +226,6 @@ def test_sanitize(self): assert "