Compare commits

...

295 Commits

Author SHA1 Message Date
KKlochko 045faf59a4 Update the CI/CD configuration to build the image.
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details
1 month ago
KKlochko 152bee732f Update the version.
1 month ago
KKlochko 99188454e9 Update Navbar partial to show the Server menu item for moderators.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko 80e99b7de8 Remove extra debug logs which used to inspect a state.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko 51c584056b Fix a typo in SearchResources component that an admin is a moderator.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko b70b99ba51 Update DBIServer's Index and Show to allow moderators to read.
1 month ago
KKlochko 9c7a555dae Update Show LiveViews to add information from which server.
1 month ago
KKlochko ab3d65a899 Update Oban configuration to prune jobs which older than 7 days.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko 44841a53e8 Update the LiveViews permission test to fix misuse of the user values.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko a25a4e24da Update to refatactor tests for syncing.
1 month ago
KKlochko 493aca0e5b Update to move get_id functions to support/helpers.
1 month ago
KKlochko 8a3b522049 Update to refactor tests for Author and Book.
1 month ago
KKlochko 89c871110c Update to refactor tests for resource forms.
1 month ago
KKlochko 64028d09f5 Fix data transformers to remove a nil value of dbi_server for syncing.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko ea5ada751d Update DBIServerTransformer to fetch the dbi_server relationship.
1 month ago
KKlochko f4eb929401 Update DBIServer to make the relationship to another server public.
1 month ago
KKlochko 59e2d2f8a1 Update the footer to add the license.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko ddcab0b843 Update the API get actions to use the by_id action.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko b7979bf6ba Add descriptions for resources' actions.
1 month ago
KKlochko db025ece6a Fix DBIServer FormComponent to allow edit only other servers' sync_on?.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko ffbec934a6 Update resources and generator to accept dbi_server_id.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko 4edf526475 Update tests to add missing assert and = which check permission for LiveViews.
continuous-integration/drone/push Build is failing Details
1 month ago
KKlochko 4a28708479 Add tests to check permissions for editing other servers' data.
1 month ago
KKlochko 3430693dac Update the pagination component to show itself if there's more than one page.
continuous-integration/drone/push Build is failing Details
1 month ago
KKlochko 54f15bead3 Rename the test module to LiveViewsPermissionsTest.
1 month ago
KKlochko 88a8eba322 Update to refactor tests which check permission for LiveViews.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko f406239b16 Add tests to check permission for Show and Edit LiveViews.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko bdc6670475 Add tests to check permission for Index LiveViews.
continuous-integration/drone/push Build is passing Details
1 month ago
KKlochko 4688d09dcf Add the LiveCase template for testing LiveViews.
1 month ago
KKlochko c51bca1eb5 Add the helper to make a user log in.
1 month ago
KKlochko 7bf009c38f Update the error message for the RequireAdmin Plug.
1 month ago
KKlochko 08b5bd3a12 Add the license.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko f79316a916 Update to make the sticky footer.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 6636cb8b6b Add an example of the nginx configuration.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko c7d193e2b3 Remove delete action for DBIServers from Server Index LiveView.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 3db1a9ab2a Update the format for sync workers' loggers.
2 months ago
KKlochko 96a6c34895 Fix to init new Flowbite components to make them work.
2 months ago
KKlochko 8999897685 Update Server edit to allow change only sync_on? for other server's data.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 40a19b9c35 Fix edit actions to allow create new data.
2 months ago
KKlochko c96aac44cd Update Server's edit action to prevent change other server's data.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 3f157e5a00 Update the style for Server and User Show LiveViews.
2 months ago
KKlochko d659d694b0 Update edit actions to prevent change other server's data.
2 months ago
KKlochko efbb7e2f46 Update BookForm tests to update required AuthorRoles.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 51c86be131 Add migrations to require Book's Publisher and AuthorRole's Author.
2 months ago
KKlochko 59cc87cd97 Update AuthorRole and SelectedAuthor component to require Author.
2 months ago
KKlochko d82e4c20fc Update Book and SelectedPublisher component to require Publisher.
2 months ago
KKlochko 61338cd404 Update the input component to show errors depend on the show_errors? attribute.
2 months ago
KKlochko 0bd6453f6b Add tests for assigning DBIServer to Author and Book.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 47595e5634 Add tests for Publisher resource.
2 months ago
KKlochko 72bc941d18 Update Book to sync only a new non-local data.
2 months ago
KKlochko 83a82a2da2 Add helpers to convert datetimes.
2 months ago
KKlochko ec8edbb006 Update Author to sync only a new non-local data.
2 months ago
KKlochko 5ba0e4da06 Update Publisher to sync only a new non-local data.
2 months ago
KKlochko 5d8e70d79d Update Book and Publisher transformers to sync the relationship for DBIServer.
2 months ago
KKlochko d57fa73825 Update the AuthorTransformer to sync all attributes and relationships.
2 months ago
KKlochko 3b761f9c66 Update SyncServerTask to sync depend on the sync_on? attribute.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 981e1f0b92 Add the sync for DBIServer.
2 months ago
KKlochko 4291a3090d Add the DBIServer to the JSON API.
2 months ago
KKlochko 1d4cf53d76 Update the style for the core checkbox component.
continuous-integration/drone/push Build is failing Details
2 months ago
KKlochko b038bb1fc0 Update the DBIserver form to update the sync_on.
2 months ago
KKlochko 2d78c2bd1b Update DBIServer to add a relationship to itself and the sync on attribute.
2 months ago
KKlochko 0415938248 Update the tests for the error htmls.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 0aa54b8f3e Update the error htmls to check if the flash exists.
2 months ago
KKlochko 38d6510e9e Add components to change the author alias.
continuous-integration/drone/push Build is failing Details
2 months ago
KKlochko 956e61ad62 Add components to change the book edition.
2 months ago
KKlochko 954324200c Update the suffix for the default page title.
continuous-integration/drone/push Build is failing Details
2 months ago
KKlochko e1c818914e Update the style for the error pages.
2 months ago
KKlochko 0094e80270 Update the README to add guide how to create an admin user.
continuous-integration/drone/push Build is failing Details
2 months ago
KKlochko a991f63aae Add the configuration for the email.
continuous-integration/drone/push Build is failing Details
2 months ago
KKlochko 72c147cb78 Add the minimal height for the description for Author Show LiveView.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 3eccc2fd44 Update the Author Show LiveView to show only the description.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko af11f13942 Add the brief_description for Book and Author.
2 months ago
KKlochko 6021d3e8c8 Fix the navbar's link for the logo to redirect with the link component.
2 months ago
KKlochko c0f91c52f1 Update the format for navbar and footer partials.
2 months ago
KKlochko 6baac297c5 Add GIN indexes for attributes which used to search.
2 months ago
KKlochko 44213069c9 Add the SyncWorkerManual to run sync manually and notify when done.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko b616c0d5a0 Update the SyncWorker to add logging.
2 months ago
KKlochko ca1c9c05d2 Update the add_button to add_button_link and remove the extra links.
2 months ago
KKlochko ebbee7f9a5 Update the code format.
2 months ago
KKlochko cffbeb04e7 Fix to do not show empty parentheses if no Author's role.
2 months ago
KKlochko 90bacf8e37 Add the Task dashboard button to access Oban dashboard.
2 months ago
KKlochko dff915e835 Add the SyncWorker and its cron configuration for Oban.
2 months ago
KKlochko f4c2207a80 Update the Oban Dashboard to show only for admin users.
2 months ago
KKlochko 14b0b78e15 Add Oban for background jobs.
2 months ago
KKlochko df4518b757 Fix the SyncBooksTask to transform Roles with AuthorRolesTransformer.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 1c7fce1d3f Update to add the search actor for the Author and Publisher Index LiveViews.
2 months ago
KKlochko f1f0b77954 Add the sync button to Server Index LiveView.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 9115d6f596 Update the Book Show LiveView to show the identifiers.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 7b2c726b2c Update the Publisher Show LiveView to remove redundant information.
2 months ago
KKlochko 7c77ff3b23 Update the header style for mobile devices for Show LiveViews.
2 months ago
KKlochko 9205d91a0b Fix the Book FormComponent to add AuthorRoles if a new book.
2 months ago
KKlochko d8e982782e Fix the Book FormComponent to save publisher_id.
2 months ago
KKlochko ab3cc4596c Update the SyncServerTask's parent module to SyncTasks.
2 months ago
KKlochko 7779308cc6 Update the Book Show LiveView.
continuous-integration/drone/push Build is failing Details
2 months ago
KKlochko aaa18fd1b6 Update the headers styles for Book and DBIServer Index LiveViews.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 7d1b33af6c Update the auth page to remove the images.
2 months ago
KKlochko 757916fb9c Update the README.
2 months ago
KKlochko c074afb0f2 Add the docker-compose configuration and examples of env files.
2 months ago
KKlochko 1cd773cc6f Update the mix and docker image configuration to install js assets.
2 months ago
KKlochko 6e92e73829 Add the docker release configuration.
2 months ago
KKlochko 54833a92ca Update User and Book LiveView to handle changed params.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko abfa20a6a6 Update the search component to send the query if changed.
2 months ago
KKlochko 0102b1c25a Update the layout for the BookSearch's dropdown menu.
2 months ago
KKlochko 523f017089 Fix the broken layout for the BookSearch component.
2 months ago
KKlochko 8b35c9b060 Add the add edition button for Book Show LiveView.
2 months ago
KKlochko d7e0a2117c Add the add alias button for Author Show LiveView.
2 months ago
KKlochko dcc3d43387 Update the BookSearch component to show as the row for mobiles.
2 months ago
KKlochko e2094b915f Update to refactor the unused and deprecated code.
2 months ago
KKlochko 601f77e0a8 Update the user info to show the non-regular role and the border.
2 months ago
KKlochko e91f46c2cd Fix the nested form for AuthorRole to persist the author.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 99ae616eff Update the style for AuthorRoles' nested forms for the Book's form.
2 months ago
KKlochko 289ff4855c Update the SearchResources component to change the text's alightment.
2 months ago
KKlochko 0915938331 Update to remove unused code for the SelectPublisher component.
2 months ago
KKlochko a1c2eca103 Update the Book form to select Author for AuthorRole via the components.
2 months ago
KKlochko 5d64f1364b Add components to select and show selected Author.
2 months ago
KKlochko 7c4eb2357c Update the Book form to show the label for Publisher.
2 months ago
KKlochko 34bf021962 Update the Book form to select publisher via the components.
2 months ago
KKlochko 71a61d3765 Add components to select and show selected Publisher.
2 months ago
KKlochko 2275e26c88 Update the Book Show to show the alternative editions.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 2ccf820f7d Update the Book Show to show the Authors with links.
2 months ago
KKlochko dc35461634 Update the footer to center text for small displays.
2 months ago
KKlochko 8655068bac Update the search resources components.
2 months ago
KKlochko a8951a5166 Update the table component to remove the extra white border.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko b1e174eb2e Update the FormComponent for Book to reorder BookIds and AuthorRoles.
2 months ago
KKlochko d0470f5aa5 Add sortablejs to reorder lists.
2 months ago
KKlochko 77514d75a0 Update the LiveView to refactor and remove the unused code.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 638c6c3bd1 Fix the form components to show the flash component for Book and Author.
2 months ago
KKlochko 4de9c62939 Update the select component to add the dark theme.
2 months ago
KKlochko d8587ca9b6 Add the separated Edit LiveViews for Publisher and DBIServer.
2 months ago
KKlochko 3ee8b2ed0b Add the moderator role attribute for search the resources component.
2 months ago
KKlochko a2c22319f0 Update the Authors Index LiveView to use the search_resource component.
2 months ago
KKlochko a3b5155337 Add the search for Users Index LiveView.
2 months ago
KKlochko 1f895f7ef5 Update the Server Show LiveView.
2 months ago
KKlochko 403d037b55 Add the search and pagination for Server Index LiveView.
2 months ago
KKlochko 97633869df Add the search action for DBIServer.
2 months ago
KKlochko 5e478b7e6d Add the User LiveViews to manage roles.
2 months ago
KKlochko 524595da9a Update User to allow admin search users.
2 months ago
KKlochko 33a70a023f Update the Publisher Index LiveView to search and sort data.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 291fbfbdf4 Remove the table from Book and Author Index LiveViews.
2 months ago
KKlochko daa1eadba5 Add the search component.
2 months ago
KKlochko 7a6d594ea7 Update the table's padding for Publisher and Servers LiveViews.
2 months ago
KKlochko c0f55e235e Update the table component style.
2 months ago
KKlochko 0f5ec22038 Update the model's transparent background color for the dark theme.
2 months ago
KKlochko d2c539333c Update the sync tests.
continuous-integration/drone/push Build is passing Details
2 months ago
KKlochko 3285d3860e Update the DBIServer generator to use admin user.
2 months ago
KKlochko f40af2bc76 Update to make the sync actions authorised for Book and Author.
2 months ago
KKlochko e078bf0911 Fix the routers order to create new resources.
2 months ago
KKlochko 1f3a2fa9e0 Update the formating for Publisher resource.
2 months ago
KKlochko 777a9436d5 Update Book resource and its tests.
2 months ago
KKlochko 6014b53dd1 Add policies for Book, BookId, AuthorRole, BookEditionsRegistry, DBI_Server.
2 months ago
KKlochko 8dc4a80e31 Update Author resource and test for the form.
2 months ago
KKlochko d004affd74 Add policies for AuthorAliasRegistry resource.
2 months ago
KKlochko 1d0abee1de Add tests for the Publisher form.
2 months ago
KKlochko 6886a1b5d2 Add the update action and the form for Publisher.
2 months ago
KKlochko 12c805c0bf Add policies for Publisher resource.
2 months ago
KKlochko 840549dd66 Update the generators for test to use the moderator user as an actor.
2 months ago
KKlochko 775564ea1d Add policies for AuthorRole resource.
2 months ago
KKlochko d3233a7aab Add policies for Author resource.
2 months ago
KKlochko 73f2f8c261 Update User generator for tests.
2 months ago
KKlochko 87dd98bd0a Fix the navbar to show the menu button if signed in.
3 months ago
KKlochko 5c0ea0f88f Update LiveViews and component to check if user can moderate.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 92a090575c Update the navbar and routes to check the User's role.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 2456b48929 Update the LiveUserAuth to check the User's role.
3 months ago
KKlochko 92cb5d342c Update User's actions to manage roles.
3 months ago
KKlochko e5dd5a8dde Add roles for users.
3 months ago
KKlochko 9189ee0b14 Update to refactor the test for Book sync.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko b9e23eeb90 Remove unused variable from the Book sync task.
3 months ago
KKlochko 3285265e4d Update to sync newer resources from a datetime.
3 months ago
KKlochko cbec8fceb4 Update to sync also BookEditionsRegistry.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 62be4c9165 Update to refactor Author and its sync.
3 months ago
KKlochko 99f59e6923 Update to refactor AuthorAliasRegistry, its sync and test.
3 months ago
KKlochko a53f0abae5 Add tests for sync AuthorAliasRegistry.
continuous-integration/drone/push Build is failing Details
3 months ago
KKlochko 034882672a Add the helpers for tests.
3 months ago
KKlochko 1a326cc8aa Update to sync also AuthorAliasRegistry.
3 months ago
KKlochko bbe5de8cb2 Remove unused aliases from DataTransformers.
3 months ago
KKlochko ac1b8aa66f Update sync task for Books.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko f4c11b99e3 Update AuthorRole and BookId for sync Book data.
3 months ago
KKlochko 74570c81a1 Update AuthorRole delete logic to cascade if no Book.
3 months ago
KKlochko d1a44a5457 Add transformers for BookId.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko b64aa37c4f Add transformers for AuthorRole.
3 months ago
KKlochko 4d48795ccd Update the AuthorRole API to show the author relationship.
3 months ago
KKlochko d0426e208e Update the navbar to show user information, sign in and out buttons.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 57bb008026 Update the routes to add authentication if needed.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 39ea8e0deb Add links for Publisher and Servers to navbar if user is signed in.
3 months ago
KKlochko 4edb1650b0 Update the style for models for Publishers and DBI Servers.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 297821b693 Update to refactor DataTransformers for Author and Publisher.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 4e8ce20bb0 Add the Book interface to search book by a bid.
3 months ago
KKlochko 38cd8eff54 Remove New Book button from Book Index LiveView.
3 months ago
KKlochko e9ed2d9731 Update the style for no data text for Index LiveViews.
3 months ago
KKlochko 07a4d6f9ce Add the sorting for Author Index LiveView.
3 months ago
KKlochko 4626ff8a29 Update the search component to send event for updating the query.
3 months ago
KKlochko 0150095233 Add the search by bids for Book Index LiveView.
3 months ago
KKlochko 73f69a72a5 Add the BookSearch component.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 877bc63f9b Add the JSON API exntension for BookId and AuthorRoles.
3 months ago
KKlochko 68169cc78b Add the validation for Book's page count to be greater than 0.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 730b2b6927 Add the sync task for Book.
3 months ago
KKlochko fb90783c35 Update the sync for Author and Publisher to verify synced data.
3 months ago
KKlochko 133d788584 Update to refactor Author and sync modules.
3 months ago
KKlochko 5ee34f76bc Add the sync task for Publisher.
3 months ago
KKlochko 6a6987bee6 Update the JSON API endpoint to /authors for Author.
3 months ago
KKlochko 71c7ce3501 Add JSON API for Book and Publisher.
3 months ago
KKlochko 488b610aed Update the card component to center their text.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 731c67302a Update nested forms style for Book FormComponent.
3 months ago
KKlochko 17caffc616 Add the red border for an input if there's an error and the dark theme.
3 months ago
KKlochko e98a98b2c1 Add tests for the Book and Author forms.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 5f786cfb4b Add the update action for the Book FormComponent.
3 months ago
KKlochko 72875c20d2 Update the input type to textarea for the description field.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko ae0e9d44e1 Update the dark style for the textarea component.
3 months ago
KKlochko 47964f9f0c Add the footer partial.
3 months ago
KKlochko a7b6d64d40 Update the Book Show LiveView to show the cover image.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 9c89dec3cc Update the Book Show LiveView to show authors with their roles.
3 months ago
KKlochko df98f12aea Update the background color for the dark theme for the whole page.
3 months ago
KKlochko 10b34b4980 Add the action to read AuthorRoles by a Book id.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 8cfac66a56 Add the search action for Books.
3 months ago
KKlochko 7a4d30ba5e Add the BookCard component to the Book Index LiveView.
3 months ago
KKlochko 905f4edf88 Add BookCard component.
3 months ago
KKlochko 3e5f362d6a Add the cover_image_url attribute to arguments to create a Book.
3 months ago
KKlochko 198d408847 Update the Author Show LiveView to show the avatar image and aliases.
3 months ago
KKlochko 98c89e1bb5 Update the image size for AuthorCard.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 99678c12e5 Add the avatar_url attribute to Author's create action.
3 months ago
KKlochko 5b9646003b Update the style for nested forms to add dark theme.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko d563034bb2 Update the button style for Show LiveViews.
3 months ago
KKlochko 4f86571579 Add separated Edit LiveView for Book.
3 months ago
KKlochko f210fb0ff1 Update the button style for Author's form.
3 months ago
KKlochko 9c2b596942 Update the back component to show white text if dark theme is turn on.
3 months ago
KKlochko f2a6af8366 Add the dark theme for core component texts.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 6f47e58a30 Fix the button alignment in the simple form.
3 months ago
KKlochko 72af6ccafc Add the svg icon for AuthorCard's edit action.
3 months ago
KKlochko 3e8e7ed0b0 Add the buttons for save, edit, cancel actions.
3 months ago
KKlochko 2e583ac33f Update headers for Author Index and FormComponent LiveViews.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 834d3e46b9 Update core components for forms to add dark theme.
3 months ago
KKlochko 1a3b30e251 Add the styled buttons for the forms.
3 months ago
KKlochko 396b1eb0be Fixed the AuthorCard edit url.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 69612a0d4a Add the cancel button to Author's FormComponent.
3 months ago
KKlochko 8c155f2546 Update the routes and Author's Index page.
3 months ago
KKlochko 1133c048d1 Update the Author form to redirect to Index or Show LiveView.
3 months ago
KKlochko cad5758ce9 Update the Show LiveView to redirect to Edit Liveview for Author.
3 months ago
KKlochko d39cacf88d Add separated Edit LiveView for Author.
3 months ago
KKlochko 0950d3fe6b Update background color and width for the page content.
3 months ago
KKlochko 96e8fdff5f Update the disabled style for pagination buttons.
3 months ago
KKlochko 6da06d8c7b Update the AuthorCard to allow edit and redirect to the show page.
3 months ago
KKlochko 4661409c56 Add the pagination to the AuthorIndex LiveView.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 6d5b29a230 Add the Pagination component.
3 months ago
KKlochko ce437b023f Update the Author Index page to use the search.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 9736fa3507 Add AuthorSearch component.
3 months ago
KKlochko f9f10ca1f2 Add the my components and AuthorCard.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko e76eff8a46 Replace the built-in navbar with the partial.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 87b90ae7d6 Add the partials and navbar.
3 months ago
KKlochko 970f8376e4 Add the flowbite.
3 months ago
KKlochko 1b27b07268 Add the sync server task.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko b8a7ac9a48 Update the sync task for Author to link the record with the server.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko e5e05320cf Add a generator for DBIServer.
3 months ago
KKlochko 97758de39c Add relationships to server for all resources.
3 months ago
KKlochko b49b7c954c Add LiveViews for DBI Servers.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko e1169c1d82 Update the Author form to add avatar url.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 6ca324622b Update the Book form to add fields: cover image url and publisher id.
3 months ago
KKlochko 71287ab6e1 Update the Book form to add remove buttons for ids and author roles.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 42cba07009 Add the author roles to the Book form.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko afc1c07936 Refactor the Book generator to add authors and a related book to opts.
3 months ago
KKlochko 2c6a9f4c16 Remove the debug information for the Book form.
3 months ago
KKlochko 288f835805 Fix the Book generator has a non existing publisher.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 05365ee210 Update the Book form and core components for the bids' nested form.
3 months ago
KKlochko 709905a8e1 Update BookId to add the reference logic.
3 months ago
KKlochko ddd300625c Update the test for the home page.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko ce0060ce73 Update to change the home page to the book index page.
continuous-integration/drone/push Build is failing Details
3 months ago
KKlochko bc6747f81b Update the home page to tell about DBI.
3 months ago
KKlochko f01a5eda1b Add the task to sync authors from the API.
continuous-integration/drone/push Build is failing Details
3 months ago
KKlochko da0e5246c7 Update AuthorTransformer to check if the "data" attibute is available.
3 months ago
KKlochko d398cc1594 Update the FetchJsons to allow use a function to transform the data.
3 months ago
KKlochko 57ead52ba2 Add the json fetchers to scrape the API.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 52ff683c2d Update the test configuration to allow run server during tests.
3 months ago
KKlochko 85993dbe9a Update the AuthorTransformer to return a map instead of a struct.
3 months ago
KKlochko e08372102f Add AuthorSync to sync author's attributes.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 1042ac4830 Add LiveViews for Book.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 532b209b3a Add LiveViews for Publisher.
3 months ago
KKlochko 3947ee4e3c Add the currect user as an actor for Author's LiveViews.
3 months ago
KKlochko 1e8619de40 Add LiveViews for Author.
3 months ago
KKlochko 7d0a098a47 Add the attribute for a avatar image url for Author.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko 100d8ba39a Add the attribute for a cover image url for Book.
3 months ago
KKlochko ddc5cc590f Update the Book to add language, format, page_count, published date.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko e23092d4d7 Update Book create interfaces and tests.
continuous-integration/drone/push Build is passing Details
3 months ago
KKlochko c6ce8173b6 Add generators for Publisher and Book for testing.
3 months ago
KKlochko 23584c2b78 Add the Publisher resource.
3 months ago
KKlochko 5f064a3235 Add the action to get Book by a BookId.
continuous-integration/drone/push Build is passing Details
4 months ago
KKlochko 23cfb1009a Update tests for Book to use bids.
continuous-integration/drone/push Build is passing Details
4 months ago
KKlochko d7b6f32cd8 Update the generators to generate bids.
4 months ago
KKlochko 91065e0acd Add BookId as ids for Book.
4 months ago
KKlochko 9f15260275 Update the action to get the author's books including aliases.
continuous-integration/drone/push Build is passing Details
4 months ago
KKlochko d6eef962de Add the action to get author's ids.
4 months ago
KKlochko c546c61268 Add the action to get author's books.
continuous-integration/drone/push Build is passing Details
4 months ago
KKlochko 70542781c2 Update AuthorRole to set author_id.
continuous-integration/drone/push Build is passing Details
4 months ago
KKlochko 9ad3ca2ee1 Update to make Author has many AuthorRoles.
4 months ago
KKlochko ecdd4089e5 Add a data transformer to transform a json to Author.
continuous-integration/drone/push Build is passing Details
4 months ago
KKlochko 2af5f6cf42 Add the JSON API for Author.
continuous-integration/drone/push Build is passing Details
4 months ago
KKlochko 040d2771f0 Update Author to add the search action and refactor the format.
4 months ago

@ -0,0 +1,50 @@
# Emacs
*~
.\#*
\#*\#
# This file excludes paths from the Docker build context.
#
# By default, Docker's build context includes all files (and folders) in the
# current directory. Even if a file isn't copied into the container it is still sent to
# the Docker daemon.
#
# There are multiple reasons to exclude files from the build context:
#
# 1. Prevent nested folders from being copied into the container (ex: exclude
# /assets/node_modules when copying /assets)
# 2. Reduce the size of the build context and improve build time (ex. /build, /deps, /doc)
# 3. Avoid sending files containing sensitive information
#
# More information on using .dockerignore is available here:
# https://docs.docker.com/engine/reference/builder/#dockerignore-file
.dockerignore
# Ignore git, but keep git HEAD and refs to access current commit hash if needed:
#
# $ cat .git/HEAD | awk '{print ".git/"$2}' | xargs cat
# d0b8727759e1e0e7aa3d41707d12376e373d5ecc
.git
!.git/HEAD
!.git/refs
# Common development/test artifacts
/cover/
/doc/
/test/
/tmp/
.elixir_ls
# Mix artifacts
/_build/
/deps/
*.ez
# Generated on crash by the VM
erl_crash.dump
# Static artifacts - These should be fetched and built inside the Docker image
/assets/node_modules/
/priv/static/assets/
/priv/static/cache_manifest.json

@ -24,6 +24,20 @@ steps:
commands:
- mix test
- name: build the image
image: plugins/kaniko
settings:
username: kklochko
password:
from_secret: REGISTRY_PASSWORD
repo: git.kklochko.space/kklochko/decentralised_book_index
registry: git.kklochko.space
tags:
- latest
- ${DRONE_TAG}
when:
event: tag
volumes:
- name: mix
temp: {}
@ -34,4 +48,4 @@ services:
environment:
POSTGRES_DB: decentralised_book_index_dev
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_PASSWORD: postgres

@ -0,0 +1,16 @@
DATABASE_URL=ecto://postgres:postgres@db/decentralised_book_index_prod
SECRET_KEY_BASE=<secret>
TOKEN_SIGNING_SECRET=<secret>
PHX_HOST=example.com
#PHX_HOST=127.0.0.1
#PORT=4000
#SYSTEM_EMAIL=noreply@example.com
#SMTP_EMAIL_RELAY=mail.example.com
#SMTP_EMAIL_USERNAME=noreply@example.com
#SMTP_EMAIL_PASSWORD=password
#SMTP_EMAIL_PORT=587
#SCALEWAY_EMAIL_PROJECT_ID=uuid
#SCALEWAY_EMAIL_SECRET_KEY=secret

@ -0,0 +1,4 @@
POSTGRES_DB=decentralised_book_index_prod
POSTGRES_USER=postgres
POSTGRES_PASSWORD=postgres

@ -1,5 +1,7 @@
[
import_deps: [
:oban,
:ash_oban,
:ash_json_api,
:ash_authentication_phoenix,
:ash_authentication,

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
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 AGPL, see
<https://www.gnu.org/licenses/>.

@ -0,0 +1,97 @@
# Find eligible builder and runner images on Docker Hub. We use Ubuntu/Debian
# instead of Alpine to avoid DNS resolution issues in production.
#
# https://hub.docker.com/r/hexpm/elixir/tags?page=1&name=ubuntu
# https://hub.docker.com/_/ubuntu?tab=tags
#
# This file is based on these images:
#
# - https://hub.docker.com/r/hexpm/elixir/tags - for the build image
# - https://hub.docker.com/_/debian?tab=tags&page=1&name=bullseye-20250317-slim - for the release image
# - https://pkgs.org/ - resource for finding needed packages
# - Ex: hexpm/elixir:1.17.3-erlang-25.3.2.18-debian-bullseye-20250317-slim
#
ARG ELIXIR_VERSION=1.17.3
ARG OTP_VERSION=25.3.2.18
ARG DEBIAN_VERSION=bullseye-20250317-slim
ARG BUILDER_IMAGE="hexpm/elixir:${ELIXIR_VERSION}-erlang-${OTP_VERSION}-debian-${DEBIAN_VERSION}"
ARG RUNNER_IMAGE="debian:${DEBIAN_VERSION}"
FROM ${BUILDER_IMAGE} as builder
# install build dependencies
RUN apt-get update -y && apt-get install -y build-essential git nodejs npm \
&& apt-get clean && rm -f /var/lib/apt/lists/*_*
# prepare build dir
WORKDIR /app
# install hex + rebar
RUN mix local.hex --force && \
mix local.rebar --force
# set build ENV
ENV MIX_ENV="prod"
# install mix dependencies
COPY mix.exs mix.lock ./
RUN mix deps.get --only $MIX_ENV
RUN mkdir config
# copy compile-time config files before we compile dependencies
# to ensure any relevant config change will trigger the dependencies
# to be re-compiled.
COPY config/config.exs config/${MIX_ENV}.exs config/
RUN mix deps.compile
COPY priv priv
COPY lib lib
COPY assets assets
# compile assets
RUN mix assets.deploy
# Compile the release
RUN mix compile
# Changes to config/runtime.exs don't require recompiling the code
COPY config/runtime.exs config/
COPY rel rel
RUN mix release
# start a new build stage so that the final image will only contain
# the compiled release and other runtime necessities
FROM ${RUNNER_IMAGE}
RUN apt-get update -y && \
apt-get install -y libstdc++6 openssl libncurses5 locales ca-certificates \
&& apt-get clean && rm -f /var/lib/apt/lists/*_*
# Set the locale
RUN sed -i '/en_US.UTF-8/s/^# //g' /etc/locale.gen && locale-gen
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
WORKDIR "/app"
RUN chown nobody /app
# set runner ENV
ENV MIX_ENV="prod"
# Only copy the final release from the build stage
COPY --from=builder --chown=nobody:root /app/_build/${MIX_ENV}/rel/decentralised_book_index ./
USER nobody
# If using an environment that doesn't automatically reap zombie processes, it is
# advised to add an init process such as tini via `apt-get install`
# above and adding an entrypoint. See https://github.com/krallin/tini for details
# ENTRYPOINT ["/tini", "--"]
CMD ["/app/bin/server"]

@ -1,18 +1,37 @@
# DecentralisedBookIndex
To start your Phoenix server:
**DecentralisedBookIndex** is a web-server to manage the book metadata in the decentralise manner.
* Run `mix setup` to install and setup dependencies
* Start Phoenix endpoint with `mix phx.server` or inside IEx with `iex -S mix phx.server`
## Getting started
- clone this repository
- copy `.env.example` file and save as `.env`
- copy `.env_db.example` file and save as `.env_db`
- change the values in `.env` and `.env_db`
you can use `mix phx.gen.secret` to generate secrets.
update the PHX_HOST to your domain name.
- run `docker compose up -d`
- run migrations `docker exec -it dbi bin/migrate`
- open the url (`PHX_HOST`) in a browser.
register a user.
- install nginx for as a reverse proxy
- configure the web-site config for nginx
change example.com to your domain.
copy example config from `examples/nginx/example.com.conf` to `/etc/nginx/sites-available`.
rename the file to your domain and change the domain within the file.
enable the web-site with command `ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/`.
- run the commands to promote an user to the admin.
change `admin@example.com` to your email.
```shell
docker exec -it dbi bin/decentralised_book_index remote
DecentralisedBookIndex.Accounts.User.get_by_email!("admin@example.com", authorize?: false) \
|> DecentralisedBookIndex.Accounts.User.set_role(:admin, authorize?: false)
```
close the terminal with `Ctrl + c` and `a`.
Now you can visit [`localhost:4000`](http://localhost:4000) from your browser.
# Author
Ready to run in production? Please [check our deployment guides](https://hexdocs.pm/phoenix/deployment.html).
Kostiantyn Klochko (c) 2025
## Learn more
# License
* Official website: https://www.phoenixframework.org/
* Guides: https://hexdocs.pm/phoenix/overview.html
* Docs: https://hexdocs.pm/phoenix
* Forum: https://elixirforum.com/c/phoenix-forum
* Source: https://github.com/phoenixframework/phoenix
Under the GNU Affero General Public License v3.0.

@ -22,10 +22,15 @@ import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
import topbar from "../vendor/topbar"
import "flowbite/dist/flowbite.phoenix.js";
import bidSort from "./bidSort";
import authorRoleSort from "./authorRoleSort";
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {
longPollFallbackMs: 2500,
params: {_csrf_token: csrfToken}
params: {_csrf_token: csrfToken},
hooks: { bidSort, authorRoleSort }
})
// Show progress bar on live navigation and form submits
@ -42,3 +47,14 @@ liveSocket.connect()
// >> liveSocket.disableLatencySim()
window.liveSocket = liveSocket
// to init new Flowbite components if a page updated by navigation
window.addEventListener("phx:navigate", () => {
const delay = 100;
setTimeout(() => {
window.dispatchEvent(
new Event("phx:page-loading-stop", { bubbles: true, cancelable: true })
);
}, delay);
});

@ -0,0 +1,14 @@
import Sortable from 'sortablejs';
export default {
mounted() {
var sortable = new Sortable(this.el, {
handle: ".handle",
draggable: "tr",
ghostClass: "bg-gray-100",
onSort: (e) => {
this.pushEventTo(this.el, "reorder-author-role", { order: sortable.toArray(e.to) })
}
})
}
}

@ -0,0 +1,14 @@
import Sortable from 'sortablejs';
export default {
mounted() {
var sortable = new Sortable(this.el, {
handle: ".handle",
draggable: "tr",
ghostClass: "bg-gray-100",
onSort: (e) => {
this.pushEventTo(this.el, "reorder-bids", { order: sortable.toArray(e.to) })
}
})
}
}

@ -0,0 +1,297 @@
{
"name": "assets",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"flowbite": "^3.1.2",
"sortablejs": "^1.15.6"
}
},
"node_modules/@popperjs/core": {
"version": "2.11.8",
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
"integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==",
"license": "MIT",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/popperjs"
}
},
"node_modules/@rollup/plugin-node-resolve": {
"version": "15.3.1",
"resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-15.3.1.tgz",
"integrity": "sha512-tgg6b91pAybXHJQMAAwW9VuWBO6Thi+q7BCNARLwSqlmsHz0XYURtGvh/AuwSADXSI4h/2uHbs7s4FzlZDGSGA==",
"license": "MIT",
"dependencies": {
"@rollup/pluginutils": "^5.0.1",
"@types/resolve": "1.20.2",
"deepmerge": "^4.2.2",
"is-module": "^1.0.0",
"resolve": "^1.22.1"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"rollup": "^2.78.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
}
},
"node_modules/@rollup/pluginutils": {
"version": "5.1.4",
"resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.1.4.tgz",
"integrity": "sha512-USm05zrsFxYLPdWWq+K3STlWiT/3ELn3RcV5hJMghpeAIhxfsUIg6mt12CBJBInWMV4VneoV7SfGv8xIwo2qNQ==",
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.0",
"estree-walker": "^2.0.2",
"picomatch": "^4.0.2"
},
"engines": {
"node": ">=14.0.0"
},
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
}
},
"node_modules/@types/estree": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz",
"integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==",
"license": "MIT"
},
"node_modules/@types/resolve": {
"version": "1.20.2",
"resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.20.2.tgz",
"integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==",
"license": "MIT"
},
"node_modules/deepmerge": {
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/deepmerge/-/deepmerge-4.3.1.tgz",
"integrity": "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/estree-walker": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
"integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
"license": "MIT"
},
"node_modules/flowbite": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/flowbite/-/flowbite-3.1.2.tgz",
"integrity": "sha512-MkwSgbbybCYgMC+go6Da5idEKUFfMqc/AmSjm/2ZbdmvoKf5frLPq/eIhXc9P+rC8t9boZtUXzHDgt5whZ6A/Q==",
"license": "MIT",
"dependencies": {
"@popperjs/core": "^2.9.3",
"flowbite-datepicker": "^1.3.1",
"mini-svg-data-uri": "^1.4.3",
"postcss": "^8.5.1"
}
},
"node_modules/flowbite-datepicker": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/flowbite-datepicker/-/flowbite-datepicker-1.3.2.tgz",
"integrity": "sha512-6Nfm0MCVX3mpaR7YSCjmEO2GO8CDt6CX8ZpQnGdeu03WUCWtEPQ/uy0PUiNtIJjJZWnX0Cm3H55MOhbD1g+E/g==",
"license": "MIT",
"dependencies": {
"@rollup/plugin-node-resolve": "^15.2.3",
"flowbite": "^2.0.0"
}
},
"node_modules/flowbite-datepicker/node_modules/flowbite": {
"version": "2.5.2",
"resolved": "https://registry.npmjs.org/flowbite/-/flowbite-2.5.2.tgz",
"integrity": "sha512-kwFD3n8/YW4EG8GlY3Od9IoKND97kitO+/ejISHSqpn3vw2i5K/+ZI8Jm2V+KC4fGdnfi0XZ+TzYqQb4Q1LshA==",
"license": "MIT",
"dependencies": {
"@popperjs/core": "^2.9.3",
"flowbite-datepicker": "^1.3.0",
"mini-svg-data-uri": "^1.4.3"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"license": "MIT",
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/is-core-module": {
"version": "2.16.1",
"resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz",
"integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==",
"license": "MIT",
"dependencies": {
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/is-module": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/is-module/-/is-module-1.0.0.tgz",
"integrity": "sha512-51ypPSPCoTEIN9dy5Oy+h4pShgJmPCygKfyRCISBI+JoWT/2oJvK8QPxmwv7b/p239jXrm9M1mlQbyKJ5A152g==",
"license": "MIT"
},
"node_modules/mini-svg-data-uri": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/mini-svg-data-uri/-/mini-svg-data-uri-1.4.4.tgz",
"integrity": "sha512-r9deDe9p5FJUPZAk3A59wGH7Ii9YrjjWw0jmw/liSbHl2CHiyXj6FcDXDu2K3TjVAXqiJdaw3xxwlZZr9E6nHg==",
"license": "MIT",
"bin": {
"mini-svg-data-uri": "cli.js"
}
},
"node_modules/nanoid": {
"version": "3.3.11",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
"integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.cjs"
},
"engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/path-parse": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
"integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
"license": "MIT"
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"license": "ISC"
},
"node_modules/picomatch": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"license": "MIT",
"engines": {
"node": ">=12"
},
"funding": {
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/postcss": {
"version": "8.5.3",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.3.tgz",
"integrity": "sha512-dle9A3yYxlBSrt8Fu+IpjGT8SY8hN0mlaA6GY8t0P5PjIOZemULz/E2Bnm/2dcUOena75OTNkHI76uZBNUUq3A==",
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/postcss"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.8",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/resolve": {
"version": "1.22.10",
"resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz",
"integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==",
"license": "MIT",
"dependencies": {
"is-core-module": "^2.16.0",
"path-parse": "^1.0.7",
"supports-preserve-symlinks-flag": "^1.0.0"
},
"bin": {
"resolve": "bin/resolve"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/sortablejs": {
"version": "1.15.6",
"resolved": "https://registry.npmjs.org/sortablejs/-/sortablejs-1.15.6.tgz",
"integrity": "sha512-aNfiuwMEpfBM/CN6LY0ibyhxPfPbyFeBTYJKCvzkJ2GkUpazIt3H+QIPAMHwqQ7tMKaHz1Qj+rJJCqljnf4p3A==",
"license": "MIT"
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/supports-preserve-symlinks-flag": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
"integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
}
}
}

@ -0,0 +1,6 @@
{
"dependencies": {
"flowbite": "^3.1.2",
"sortablejs": "^1.15.6"
}
}

@ -10,7 +10,8 @@ module.exports = {
"../deps/ash_authentication_phoenix/**/*.*ex",
"./js/**/*.js",
"../lib/decentralised_book_index_web.ex",
"../lib/decentralised_book_index_web/**/*.*ex"
"../lib/decentralised_book_index_web/**/*.*ex",
"./node_modules/flowbite/**/*.js"
],
theme: {
extend: {
@ -21,6 +22,7 @@ module.exports = {
},
plugins: [
require("@tailwindcss/forms"),
require('flowbite/plugin'),
// Allows prefixing tailwind classes with LiveView classes to add rules
// only when LiveView classes are applied, for example:
//

@ -7,6 +7,19 @@
# General application configuration
import Config
config :ash_oban, pro?: false
config :decentralised_book_index, Oban,
repo: DecentralisedBookIndex.Repo,
queues: [default: 14],
plugins: [
# A job will be pruned after 7 days.
{Oban.Plugins.Pruner, max_age: 7*24*60*60},
{Oban.Plugins.Cron,
crontab: [
{"@daily", DecentralisedBookIndex.SyncWorker},
]}
]
config :mime,
extensions: %{"json" => "application/vnd.api+json"},
types: %{"application/vnd.api+json" => ["json"]}

@ -1,5 +1,6 @@
import Config
require Logger
# config/runtime.exs is executed for all environments, including
# during releases. It is executed after compilation and before the
# system starts, so it is typically used to load production configuration
@ -119,4 +120,33 @@ if config_env() == :prod do
# config :swoosh, :api_client, Swoosh.ApiClient.Hackney
#
# See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details.
if System.get_env("SMTP_EMAIL_RELAY") do
Logger.info("Using SMTP for email delivery")
config :decentralised_book_index, DecentralisedBookIndex.Mailer,
adapter: Swoosh.Adapters.SMTP,
relay: System.get_env("SMTP_EMAIL_RELAY"),
username: System.get_env("SMTP_EMAIL_USERNAME"),
password: System.get_env("SMTP_EMAIL_PASSWORD"),
ssl: true,
tls: :always,
auth: :always,
port: System.get_env("SMTP_EMAIL_PORT"),
retries: 2,
no_mx_lookups: false
config :swoosh, :api_client, Swoosh.ApiClient.Finch
end
if System.get_env("SCALEWAY_EMAIL_PROJECT_ID") do
Logger.info("Using Scaleway for email delivery")
config :decentralised_book_index, DecentralisedBookIndex.Mailer,
adapter: Swoosh.Adapters.Scaleway,
project_id: System.get_env("SCALEWAY_EMAIL_PROJECT_ID"),
secret_key: System.get_env("SCALEWAY_EMAIL_SECRET_KEY")
config :swoosh, :api_client, Swoosh.ApiClient.Finch
end
end

@ -1,4 +1,5 @@
import Config
config :decentralised_book_index, Oban, testing: :manual
config :decentralised_book_index, token_signing_secret: "k+YMBGan4wi4I3DRYRVLNVCOIDIqm+O5"
config :ash, disable_async?: true
@ -20,7 +21,7 @@ config :decentralised_book_index, DecentralisedBookIndex.Repo,
config :decentralised_book_index, DecentralisedBookIndexWeb.Endpoint,
http: [ip: {127, 0, 0, 1}, port: 4002],
secret_key_base: "6NMai4xOf+JhqltU9Ecf+U+DcyMSKs7SYtUc1Kf06H8UrG+MmJu3nXHS4CosOOdN",
server: false
server: true
# In test we don't send emails
config :decentralised_book_index, DecentralisedBookIndex.Mailer, adapter: Swoosh.Adapters.Test

@ -0,0 +1,32 @@
version: '3'
networks:
dbi:
external: false
services:
db:
image: postgres:17-alpine
restart: always
volumes:
- ./data:/var/lib/postgresql/data
networks:
- dbi
env_file:
- .env_db
web:
# to build the image
build:
context: .
container_name: dbi
ports:
- 4000:4000
depends_on:
- db
networks:
- dbi
env_file:
- .env

@ -0,0 +1,17 @@
server {
server_name example.com;
location / {
proxy_pass http://localhost:4000;
# Add WebSocket support
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

@ -0,0 +1,11 @@
defmodule DecentralisedBookIndex.Accounts.Role do
use Ash.Type.Enum, values: [:user, :moderator, :admin]
def can_moderate?(role) when is_atom(role) do
role in [:moderator, :admin]
end
def can_administrate?(role) when is_atom(role) do
role == :admin
end
end

@ -48,6 +48,18 @@ defmodule DecentralisedBookIndex.Accounts.User do
repo DecentralisedBookIndex.Repo
end
code_interface do
define :list_moderators
define :search, action: :search, args: [:email]
define :get_by_id, action: :read, get_by: [:id]
define :get_by_email, args: [:email]
define :set_role, args: [:role]
define :make_moderator
define :make_user
end
actions do
defaults [:read]
@ -218,6 +230,38 @@ defmodule DecentralisedBookIndex.Accounts.User do
# Generates an authentication token for the user
change AshAuthentication.GenerateTokenChange
end
update :set_role do
description "Sets user role"
accept [:role]
end
update :make_moderator do
description "Sets user role to moderator"
change set_attribute(:role, :moderator)
end
update :make_user do
description "Sets user role to user"
change set_attribute(:role, :user)
end
read :list_moderators do
description "Looks up users with the moderator role"
filter expr(role == :moderator)
end
read :search do
argument :email, :ci_string do
constraints allow_empty?: true
default ""
end
filter expr(contains(email, ^arg(:email)))
pagination offset?: true, default_limit: 10
end
end
policies do
@ -225,6 +269,10 @@ defmodule DecentralisedBookIndex.Accounts.User do
authorize_if always()
end
bypass actor_attribute_equals(:role, :admin) do
authorize_if always()
end
policy always() do
forbid_if always()
end
@ -242,6 +290,12 @@ defmodule DecentralisedBookIndex.Accounts.User do
allow_nil? false
sensitive? true
end
attribute :role, DecentralisedBookIndex.Accounts.Role do
allow_nil? false
default :user
public? true
end
end
identities do

@ -13,8 +13,7 @@ defmodule DecentralisedBookIndex.Accounts.User.Senders.SendNewUserConfirmationEm
@impl true
def send(user, token, _) do
new()
# TODO: Replace with your email
|> from({"noreply", "noreply@example.com"})
|> from({"noreply", System.get_env("SYSTEM_EMAIL", "noreply@example.com")})
|> to(to_string(user.email))
|> subject("Confirm your email address")
|> html_body(body(token: token))

@ -13,8 +13,7 @@ defmodule DecentralisedBookIndex.Accounts.User.Senders.SendPasswordResetEmail do
@impl true
def send(user, token, _) do
new()
# TODO: Replace with your email
|> from({"noreply", "noreply@example.com"})
|> from({"noreply", System.get_env("SYSTEM_EMAIL", "noreply@example.com")})
|> to(to_string(user.email))
|> subject("Reset your password")
|> html_body(body(token: token))

@ -10,6 +10,11 @@ defmodule DecentralisedBookIndex.Application do
children = [
DecentralisedBookIndexWeb.Telemetry,
DecentralisedBookIndex.Repo,
{Oban,
AshOban.config(
Application.fetch_env!(:decentralised_book_index, :ash_domains),
Application.fetch_env!(:decentralised_book_index, Oban)
)},
{DNSCluster,
query: Application.get_env(:decentralised_book_index, :dns_cluster_query) || :ignore},
{Phoenix.PubSub, name: DecentralisedBookIndex.PubSub},

@ -1,41 +1,116 @@
defmodule DecentralisedBookIndex.Metadata do
use Ash.Domain,
otp_app: :decentralised_book_index
use Ash.Domain, otp_app: :decentralised_book_index, extensions: [AshJsonApi.Domain, AshPhoenix]
alias DecentralisedBookIndex.Metadata
json_api do
routes do
base_route "/books", Metadata.Book do
get :by_id
index :search
related :bids, :read, primary?: true
related :author_roles, :read, primary?: true
related :publisher, :read, primary?: true
end
base_route "/authors", Metadata.Author do
get :by_id
index :search
end
base_route "/publishers", Metadata.Publisher do
get :by_id
index :search
end
base_route "/servers", Metadata.DBIServer do
get :by_id
index :search
end
end
end
resources do
resource DecentralisedBookIndex.Metadata.Book do
define :create_book,
action: :create,
args: [:title, :isbn, :description, :author_roles, {:optional, :book_editions_registry_id}]
args: [
:title,
:description,
:language,
:format,
:page_count,
:published,
:bids,
:author_roles,
:publisher_id,
{:optional, :cover_image_url},
{:optional, :book_editions_registry_id}
]
define :add_book_to_related_editions_registry,
action: :add_book_to_related_editions_registry,
args: [:title, :isbn, :description, :author_roles, :related_book_id]
args: [
:title,
:description,
:language,
:format,
:page_count,
:published,
:bids,
:author_roles,
:publisher_id,
:related_book_id,
{:optional, :cover_image_url}
]
define :list_books, action: :read
define :get_book_by_id, args: [:id], action: :by_id
define :get_book_by_bid, args: [:type, :bid], action: :by_bid
define :get_book_alternative_editions, args: [:book], action: :get_alternative_editions
define :get_author_books, args: [:author], action: :get_author_books
define :search_book, action: :search, args: [:query]
define :search_book_by_bid, action: :search_by_bid, args: [:type, :bid]
define :update_book, action: :update
define :assign_book_cover_image, args: [:cover_image_url], action: :assign_cover_image
define :assign_book_dbi_server, args: [:dbi_server_id], action: :assign_dbi_server_id
define :destroy_book, action: :destroy
end
resource DecentralisedBookIndex.Metadata.Author do
define :create_author,
action: :create,
args: [:name, :description, {:optional, :author_alias_registry_id}]
args: [
:name,
:description,
{:optional, :avatar_url},
{:optional, :author_alias_registry_id}
]
define :add_author_to_related_alias_registry,
action: :add_author_to_related_alias_registry,
args: [:name, :description, :related_author_id]
args: [:name, :description, :related_author_id, {:optional, :avatar_url}]
define :list_authors, action: :read
define :get_author_by_id, args: [:id], action: :by_id
define :get_author_ids, args: [:author], action: :get_author_ids
define :get_author_alternative_names, args: [:author], action: :get_alternative_names
define :search_author, action: :search, args: [:name]
define :update_author, action: :update
define :assign_author_avatar_image, args: [:avatar_url], action: :assign_avatar_image
define :assign_author_dbi_server, args: [:dbi_server_id], action: :assign_dbi_server_id
define :destroy_author, action: :destroy
end
resource DecentralisedBookIndex.Metadata.DBIServer
resource DecentralisedBookIndex.Metadata.DBIServer do
define :create_dbi_server, args: [:name, :url, :sync_on?], action: :create
define :list_dbi_server, action: :read
define :get_dbi_server_by_id, args: [:id], action: :by_id
define :search_dbi_server, action: :search, args: [:name]
define :update_dbi_server, action: :update
define :destroy_dbi_server, action: :destroy
end
resource DecentralisedBookIndex.Metadata.AuthorAliasRegistry do
define :create_author_alias_registry, action: :create
@ -53,6 +128,31 @@ defmodule DecentralisedBookIndex.Metadata do
define :destroy_book_editions_registry, action: :destroy
end
resource DecentralisedBookIndex.Metadata.AuthorRole
resource DecentralisedBookIndex.Metadata.AuthorRole do
define :create_author_role, action: :create, args: [:author_id, :order, :role]
define :list_author_roles, action: :read
define :get_author_role_by_id, args: [:id], action: :by_id
define :get_author_roles_by_book_id, args: [:book_id], action: :by_book_id
define :update_author_role, action: :update
define :destroy_author_role, action: :destroy
end
resource DecentralisedBookIndex.Metadata.BookId do
define :create_book_id, action: :create, args: [:type, :bid, :order]
define :list_book_ids, action: :read
define :get_book_id_by_id, args: [:id], action: :by_id
define :update_book_id, action: :update
define :destroy_book_id, action: :destroy
end
resource DecentralisedBookIndex.Metadata.Publisher do
define :create_publisher, action: :create, args: [:name]
define :list_publishers, action: :read
define :get_publisher_by_id, args: [:id], action: :by_id
define :search_publisher, action: :search, args: [:name]
define :update_publisher, action: :update
define :assign_publisher_dbi_server, args: [:dbi_server_id], action: :assign_dbi_server_id
define :destroy_publisher, action: :destroy
end
end
end

@ -2,28 +2,48 @@ defmodule DecentralisedBookIndex.Metadata.Author do
use Ash.Resource,
otp_app: :decentralised_book_index,
domain: DecentralisedBookIndex.Metadata,
data_layer: AshPostgres.DataLayer
data_layer: AshPostgres.DataLayer,
extensions: [AshJsonApi.Resource],
authorizers: [Ash.Policy.Authorizer]
require Ash.Query
alias DecentralisedBookIndex.Metadata
@brief_description_length 20
@brief_description_max_length @brief_description_length + 3
json_api do
type "author"
end
postgres do
table "authors"
repo DecentralisedBookIndex.Repo
custom_indexes do
index "name gin_trgm_ops", name: "author_name_gin_index", using: "GIN"
end
end
resource do
description "An author's metadata."
end
actions do
defaults [:read, :update, :destroy]
defaults [:read, :destroy]
create :create do
primary? true
accept [:name, :description, :author_alias_registry_id]
accept [:name, :description, :avatar_url, :author_alias_registry_id, :dbi_server_id]
change fn changeset, context ->
actor = Map.get(context, :actor, nil)
change fn changeset, _ ->
registry_id = Ash.Changeset.get_attribute(changeset, :author_alias_registry_id)
if registry_id == nil do
{:ok, registry} = DecentralisedBookIndex.Metadata.create_author_alias_registry()
registry =
DecentralisedBookIndex.Metadata.create_author_alias_registry!(actor: actor)
Ash.Changeset.force_change_attribute(changeset, :author_alias_registry_id, registry.id)
else
@ -33,7 +53,7 @@ defmodule DecentralisedBookIndex.Metadata.Author do
end
create :add_author_to_related_alias_registry do
accept [:name, :description]
accept [:name, :description, :avatar_url]
argument :related_author_id, :uuid do
allow_nil? false
@ -45,14 +65,46 @@ defmodule DecentralisedBookIndex.Metadata.Author do
if related_author_id == nil do
Ash.Changeset.add_error(changeset, :related_author_id, "Related author is empty")
else
{:ok, related_author} = DecentralisedBookIndex.Metadata.get_author_by_id(related_author_id)
related_author =
DecentralisedBookIndex.Metadata.get_author_by_id!(related_author_id)
Ash.Changeset.force_change_attribute(changeset, :author_alias_registry_id, related_author.author_alias_registry_id)
Ash.Changeset.force_change_attribute(
changeset,
:author_alias_registry_id,
related_author.author_alias_registry_id
)
end
end
end
create :sync_create do
accept [
:id,
:name,
:description,
:avatar_url,
:author_alias_registry_id,
:inserted_at,
:updated_at,
:dbi_server_id
]
change fn changeset, context ->
registry_id = Ash.Changeset.get_attribute(changeset, :author_alias_registry_id)
if registry_id == nil do
{:ok, registry} =
DecentralisedBookIndex.Metadata.create_author_alias_registry(authorize?: false)
Ash.Changeset.force_change_attribute(changeset, :author_alias_registry_id, registry.id)
else
changeset
end
end
end
read :by_id do
description "Return the Author by its id."
argument :id, :uuid, allow_nil?: false
get? true
filter expr(id == ^arg(:id))
@ -65,14 +117,126 @@ defmodule DecentralisedBookIndex.Metadata.Author do
author = query.arguments.author
DecentralisedBookIndex.Metadata.Author
|> Ash.Query.filter(author_alias_registry_id == ^author.author_alias_registry_id
and id != ^author.id)
|> Ash.Query.filter(
author_alias_registry_id == ^author.author_alias_registry_id and
id != ^author.id
)
end
end
action :get_author_ids, :vector do
argument :author, :struct, allow_nil?: false
run fn input, _ ->
author = input.arguments.author
{:ok, ids} =
DecentralisedBookIndex.Metadata.Author
|> Ash.Query.filter(author_alias_registry_id == ^author.author_alias_registry_id)
|> Ash.Query.select([:id])
|> Ash.read()
{:ok, Enum.map(ids, & &1.id)}
end
end
read :search do
description "Return a list of Authors, optionally filtering by name."
argument :name, :ci_string do
description "Return Authors, which names includes the name."
constraints allow_empty?: true
default ""
end
filter expr(contains(name, ^arg(:name)))
pagination offset?: true, default_limit: 10
end
update :sync do
description "Sync the data for an existing record."
require_atomic? false
accept [
:id,
:name,
:description,
:avatar_url,
:author_alias_registry_id,
:inserted_at,
:updated_at,
:dbi_server_id
]
change fn changeset, _ ->
registry_id = Ash.Changeset.get_attribute(changeset, :author_alias_registry_id)
if registry_id == nil do
{:ok, registry} = DecentralisedBookIndex.Metadata.create_author_alias_registry()
Ash.Changeset.force_change_attribute(changeset, :author_alias_registry_id, registry.id)
else
changeset
end
end
end
update :update do
primary? true
accept [:name, :description, :avatar_url, :author_alias_registry_id]
require_atomic? false
change fn changeset, _ ->
registry_id = Ash.Changeset.get_attribute(changeset, :author_alias_registry_id)
if registry_id == nil do
{:ok, registry} = DecentralisedBookIndex.Metadata.create_author_alias_registry()
Ash.Changeset.force_change_attribute(changeset, :author_alias_registry_id, registry.id)
else
changeset
end
end
end
update :assign_avatar_image do
accept [:avatar_url]
end
update :assign_dbi_server_id do
accept [:dbi_server_id]
end
end
policies do
bypass actor_attribute_equals(:role, :admin) do
authorize_if always()
end
policy action_type(:read) do
authorize_if always()
end
policy action(:get_author_ids) do
authorize_if always()
end
policy action_type(:create) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:update) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:destroy) do
authorize_if actor_attribute_equals(:role, :admin)
end
end
attributes do
uuid_primary_key :id
uuid_primary_key :id, writable?: true
attribute :name, :string do
allow_nil? false
@ -84,16 +248,39 @@ defmodule DecentralisedBookIndex.Metadata.Author do
public? true
end
timestamps()
attribute :avatar_url, :string do
allow_nil? true
public? true
end
timestamps do
writable? true
public? true
end
end
relationships do
belongs_to :author_alias_registry, Metadata.AuthorAliasRegistry do
attribute_writable? true
belongs_to :dbi_server, Metadata.DBIServer do
public? true
end
belongs_to :author_role, Metadata.AuthorRole do
belongs_to :author_alias_registry, Metadata.AuthorAliasRegistry do
attribute_writable? true
public? true
end
has_many :author_role, Metadata.AuthorRole
end
calculations do
calculate :brief_description,
:string,
expr(
if(string_length(description) <= @brief_description_max_length) do
description
else
fragment("substr(?, 1, ?)", description, @brief_description_length) <> "..."
end
)
end
end

@ -2,7 +2,10 @@ defmodule DecentralisedBookIndex.Metadata.AuthorAliasRegistry do
use Ash.Resource,
otp_app: :decentralised_book_index,
domain: DecentralisedBookIndex.Metadata,
data_layer: AshPostgres.DataLayer
data_layer: AshPostgres.DataLayer,
authorizers: [Ash.Policy.Authorizer]
alias DecentralisedBookIndex.Metadata
postgres do
table "author_alias_registries"
@ -12,6 +15,14 @@ defmodule DecentralisedBookIndex.Metadata.AuthorAliasRegistry do
actions do
defaults [:read, :create, :update, :destroy]
create :sync_create do
accept [:id, :dbi_server_id]
end
update :sync do
accept [:id, :dbi_server_id]
end
read :by_id do
argument :id, :uuid, allow_nil?: false
get? true
@ -19,13 +30,37 @@ defmodule DecentralisedBookIndex.Metadata.AuthorAliasRegistry do
end
end
policies do
bypass actor_attribute_equals(:role, :admin) do
authorize_if always()
end
policy action_type(:read) do
authorize_if always()
end
policy action_type(:create) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:update) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:destroy) do
authorize_if actor_attribute_equals(:role, :moderator)
end
end
attributes do
uuid_primary_key :id
uuid_primary_key :id, writable?: true
timestamps()
end
relationships do
belongs_to :dbi_server, Metadata.DBIServer
has_many :authors, DecentralisedBookIndex.Metadata.Author
end
end

@ -2,27 +2,114 @@ defmodule DecentralisedBookIndex.Metadata.AuthorRole do
use Ash.Resource,
otp_app: :decentralised_book_index,
domain: DecentralisedBookIndex.Metadata,
data_layer: AshPostgres.DataLayer
data_layer: AshPostgres.DataLayer,
extensions: [AshJsonApi.Resource],
authorizers: [Ash.Policy.Authorizer]
alias DecentralisedBookIndex.Metadata
json_api do
type "author_role"
end
postgres do
table "author_role"
repo DecentralisedBookIndex.Repo
references do
reference :book, index?: true, on_delete: :delete
end
end
resource do
description "A metadata of an author's role."
end
actions do
defaults [:read, :update, :destroy]
defaults [:destroy]
create :create do
primary? true
accept [:id, :order, :role]
argument :author_id, :uuid, allow_nil?: false
change fn changeset, _ ->
author_id =
Map.get(changeset.arguments, :author_id, nil)
if author_id != nil do
{:ok, author} = DecentralisedBookIndex.Metadata.get_author_by_id(author_id)
Ash.Changeset.force_change_attribute(changeset, :author_id, author.id)
else
changeset
end
end
end
read :read do
description "Return a list of AuthorRoles."
primary? true
end
read :by_id do
description "Return the AuthorRole by its id."
argument :id, :uuid, allow_nil?: false
get? true
filter expr(id == ^arg(:id))
end
read :by_book_id do
description "Return the AuthorRole by its BookId."
argument :book_id, :uuid, allow_nil?: false
filter expr(book_id == ^arg(:book_id))
end
update :update do
primary? true
accept [:order, :role]
argument :author_id, :uuid
argument :author_id, :uuid, allow_nil?: false
require_atomic? false
change fn changeset, _ ->
author_id =
Map.get(changeset.arguments, :author_id, nil)
if author_id != nil do
{:ok, author} = DecentralisedBookIndex.Metadata.get_author_by_id(author_id)
Ash.Changeset.force_change_attribute(changeset, :author_id, author.id)
else
changeset
end
end
end
end
policies do
bypass actor_attribute_equals(:role, :admin) do
authorize_if always()
end
policy action_type(:read) do
authorize_if always()
end
policy action_type(:create) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:update) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:destroy) do
authorize_if actor_attribute_equals(:role, :moderator)
end
end
attributes do
uuid_primary_key :id
uuid_primary_key :id, writable?: true
attribute :role, :string do
allow_nil? true
@ -38,12 +125,15 @@ defmodule DecentralisedBookIndex.Metadata.AuthorRole do
end
relationships do
belongs_to :dbi_server, Metadata.DBIServer
belongs_to :book, Metadata.Book do
allow_nil? true
end
has_one :author, Metadata.Author do
belongs_to :author, Metadata.Author do
allow_nil? false
public? true
end
end
end

@ -2,29 +2,99 @@ defmodule DecentralisedBookIndex.Metadata.Book do
use Ash.Resource,
otp_app: :decentralised_book_index,
domain: DecentralisedBookIndex.Metadata,
data_layer: AshPostgres.DataLayer
data_layer: AshPostgres.DataLayer,
extensions: [AshJsonApi.Resource],
authorizers: [Ash.Policy.Authorizer]
require Ash.Query
alias DecentralisedBookIndex.Metadata
@brief_description_length 20
@brief_description_max_length @brief_description_length + 3
json_api do
type "book"
end
postgres do
table "books"
repo DecentralisedBookIndex.Repo
custom_indexes do
index "title gin_trgm_ops", name: "book_title_gin_index", using: "GIN"
end
end
resource do
description "A book's metadata."
end
actions do
defaults [:read, :update, :destroy]
defaults [:read, :destroy]
create :create do
primary? true
accept [:title, :isbn, :description, :book_editions_registry_id]
accept [
:title,
:description,
:format,
:language,
:page_count,
:published,
:publisher_id,
:cover_image_url,
:book_editions_registry_id,
:dbi_server_id
]
argument :bids, {:array, :map}
argument :author_roles, {:array, :map}
change fn changeset, _ ->
change fn changeset, context ->
actor = Map.get(context, :actor, nil)
registry_id = Ash.Changeset.get_attribute(changeset, :book_editions_registry_id)
if registry_id == nil do
{:ok, registry} = DecentralisedBookIndex.Metadata.create_book_editions_registry()
registry = DecentralisedBookIndex.Metadata.create_book_editions_registry!(actor: actor)
Ash.Changeset.force_change_attribute(changeset, :book_editions_registry_id, registry.id)
else
changeset
end
end
change manage_relationship(:bids, type: :direct_control, order_is_key: :order)
change manage_relationship(:author_roles, type: :direct_control, order_is_key: :order)
end
create :sync_create do
accept [
:id,
:title,
:description,
:format,
:language,
:page_count,
:published,
:publisher_id,
:cover_image_url,
:book_editions_registry_id,
:inserted_at,
:updated_at,
:dbi_server_id
]
argument :bids, {:array, :map}
argument :author_roles, {:array, :map}
change fn changeset, context ->
registry_id = Ash.Changeset.get_attribute(changeset, :book_editions_registry_id)
if registry_id == nil do
registry =
DecentralisedBookIndex.Metadata.create_book_editions_registry!(authorize?: false)
Ash.Changeset.force_change_attribute(changeset, :book_editions_registry_id, registry.id)
else
@ -32,16 +102,27 @@ defmodule DecentralisedBookIndex.Metadata.Book do
end
end
change manage_relationship(:bids, type: :direct_control, order_is_key: :order)
change manage_relationship(:author_roles, type: :direct_control, order_is_key: :order)
end
create :add_book_to_related_editions_registry do
accept [:title, :isbn, :description]
accept [
:title,
:description,
:format,
:language,
:page_count,
:published,
:publisher_id,
:cover_image_url
]
argument :related_book_id, :uuid do
allow_nil? false
end
argument :bids, {:array, :map}
argument :author_roles, {:array, :map}
change fn changeset, context ->
@ -52,19 +133,32 @@ defmodule DecentralisedBookIndex.Metadata.Book do
else
{:ok, related_book} = DecentralisedBookIndex.Metadata.get_book_by_id(related_book_id)
Ash.Changeset.force_change_attribute(changeset, :book_editions_registry_id, related_book.book_editions_registry_id)
Ash.Changeset.force_change_attribute(
changeset,
:book_editions_registry_id,
related_book.book_editions_registry_id
)
end
end
change manage_relationship(:bids, type: :direct_control, order_is_key: :order)
change manage_relationship(:author_roles, type: :direct_control, order_is_key: :order)
end
read :by_id do
description "Return the Book by its id."
argument :id, :uuid, allow_nil?: false
get? true
filter expr(id == ^arg(:id))
end
read :by_bid do
argument :type, :string, allow_nil?: false
argument :bid, :string, allow_nil?: false
get? true
filter expr(exists(bids, type == ^arg(:type) and bid == ^arg(:bid)))
end
read :get_alternative_editions do
argument :book, :struct, allow_nil?: false
@ -72,39 +166,237 @@ defmodule DecentralisedBookIndex.Metadata.Book do
book = query.arguments.book
DecentralisedBookIndex.Metadata.Book
|> Ash.Query.filter(book_editions_registry_id == ^book.book_editions_registry_id
and id != ^book.id)
|> Ash.Query.filter(
book_editions_registry_id == ^book.book_editions_registry_id and
id != ^book.id
)
end
end
read :get_author_books do
argument :author, :struct, allow_nil?: false
prepare fn query, context ->
author = query.arguments.author
{:ok, author_ids} = Metadata.get_author_ids(author)
Metadata.Book
|> Ash.Query.filter(expr(exists(author_roles, author_id in ^author_ids)))
end
end
read :search do
description "Return a list of Books, optionally filtering by title."
argument :query, :ci_string do
description "Return Books, which titles includes the query."
constraints allow_empty?: true
default ""
end
filter expr(contains(title, ^arg(:query)))
pagination offset?: true, default_limit: 10
end
read :search_by_bid do
description "Return a list of Books, optionally filtering by BookId."
argument :type, :string, allow_nil?: false
argument :bid, :string, allow_nil?: false
filter expr(exists(bids, type == ^arg(:type) and contains(bid, ^arg(:bid))))
pagination offset?: true, default_limit: 10
end
update :update do
primary? true
require_atomic? false
accept [
:title,
:description,
:format,
:language,
:page_count,
:published,
:publisher_id,
:cover_image_url,
:book_editions_registry_id
]
argument :bids, {:array, :map}
argument :author_roles, {:array, :map}
change fn changeset, _ ->
registry_id = Ash.Changeset.get_attribute(changeset, :book_editions_registry_id)
if registry_id == nil do
{:ok, registry} = DecentralisedBookIndex.Metadata.create_book_editions_registry()
Ash.Changeset.force_change_attribute(changeset, :book_editions_registry_id, registry.id)
else
changeset
end
end
change manage_relationship(:bids, type: :direct_control, order_is_key: :order)
change manage_relationship(:author_roles, type: :direct_control, order_is_key: :order)
end
update :sync do
require_atomic? false
accept [
:id,
:title,
:description,
:format,
:language,
:page_count,
:published,
:publisher_id,
:cover_image_url,
:book_editions_registry_id,
:inserted_at,
:updated_at,
:dbi_server_id
]
argument :bids, {:array, :map}
argument :author_roles, {:array, :map}
change fn changeset, _ ->
registry_id = Ash.Changeset.get_attribute(changeset, :book_editions_registry_id)
if registry_id == nil do
{:ok, registry} = DecentralisedBookIndex.Metadata.create_book_editions_registry()
Ash.Changeset.force_change_attribute(changeset, :book_editions_registry_id, registry.id)
else
changeset
end
end
change manage_relationship(:bids, type: :direct_control, order_is_key: :order)
change manage_relationship(:author_roles, type: :direct_control, order_is_key: :order)
end
update :assign_cover_image do
accept [:cover_image_url]
end
update :assign_dbi_server_id do
accept [:dbi_server_id]
end
end
policies do
bypass actor_attribute_equals(:role, :admin) do
authorize_if always()
end
policy action_type(:read) do
authorize_if always()
end
policy action_type(:create) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:update) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:destroy) do
authorize_if actor_attribute_equals(:role, :admin)
end
end
validations do
validate numericality(:page_count, greater_than: 0)
end
attributes do
uuid_primary_key :id
uuid_primary_key :id, writable?: true
attribute :title, :string do
allow_nil? false
public? true
end
attribute :isbn, :string do
attribute :description, :string do
allow_nil? false
public? true
end
attribute :description, :string do
attribute :published, :date do
allow_nil? false
public? true
end
attribute :language, :string do
allow_nil? false
public? true
end
attribute :format, :string do
allow_nil? false
public? true
end
timestamps()
attribute :page_count, :integer do
allow_nil? false
public? true
end
attribute :cover_image_url, :string do
allow_nil? true
public? true
end
timestamps do
writable? true
public? true
end
end
relationships do
belongs_to :book_editions_registry, Metadata.BookEditionsRegistry
belongs_to :dbi_server, Metadata.DBIServer do
public? true
end
belongs_to :book_editions_registry, Metadata.BookEditionsRegistry do
public? true
end
belongs_to :publisher, Metadata.Publisher do
allow_nil? false
public? true
end
has_many :author_roles, Metadata.AuthorRole do
sort order: :asc
public? true
end
has_many :bids, Metadata.BookId do
sort order: :asc
public? true
end
end
calculations do
calculate :brief_description,
:string,
expr(
if(string_length(description) <= @brief_description_max_length) do
description
else
fragment("substr(?, 1, ?)", description, @brief_description_length) <> "..."
end
)
end
end

@ -2,7 +2,10 @@ defmodule DecentralisedBookIndex.Metadata.BookEditionsRegistry do
use Ash.Resource,
otp_app: :decentralised_book_index,
domain: DecentralisedBookIndex.Metadata,
data_layer: AshPostgres.DataLayer
data_layer: AshPostgres.DataLayer,
authorizers: [Ash.Policy.Authorizer]
alias DecentralisedBookIndex.Metadata
postgres do
table "book_editions_registries"
@ -12,6 +15,14 @@ defmodule DecentralisedBookIndex.Metadata.BookEditionsRegistry do
actions do
defaults [:read, :create, :update, :destroy]
create :sync_create do
accept [:id, :dbi_server_id]
end
update :sync do
accept [:id, :dbi_server_id]
end
read :by_id do
argument :id, :uuid, allow_nil?: false
get? true
@ -19,13 +30,37 @@ defmodule DecentralisedBookIndex.Metadata.BookEditionsRegistry do
end
end
policies do
bypass actor_attribute_equals(:role, :admin) do
authorize_if always()
end
policy action_type(:read) do
authorize_if always()
end
policy action_type(:create) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:update) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:destroy) do
authorize_if actor_attribute_equals(:role, :moderator)
end
end
attributes do
uuid_primary_key :id
uuid_primary_key :id, writable?: true
timestamps()
end
relationships do
has_many :authors, DecentralisedBookIndex.Metadata.Book
belongs_to :dbi_server, Metadata.DBIServer
has_many :books, DecentralisedBookIndex.Metadata.Book
end
end

@ -0,0 +1,109 @@
defmodule DecentralisedBookIndex.Metadata.BookId do
use Ash.Resource,
otp_app: :decentralised_book_index,
domain: DecentralisedBookIndex.Metadata,
data_layer: AshPostgres.DataLayer,
extensions: [AshJsonApi.Resource],
authorizers: [Ash.Policy.Authorizer]
alias DecentralisedBookIndex.Metadata
json_api do
type "book_id"
end
postgres do
table "book_ids"
repo DecentralisedBookIndex.Repo
references do
reference :book, index?: true, on_delete: :delete
end
custom_indexes do
index "type gin_trgm_ops", name: "book_id_type_gin_index", using: "GIN"
index "bid gin_trgm_ops", name: "book_id_bid_gin_index", using: "GIN"
end
end
resource do
description "A book's identifier."
end
actions do
defaults [:destroy]
create :create do
primary? true
accept [:id, :type, :bid, :order]
end
update :update do
primary? true
accept [:id, :type, :bid, :order]
end
read :read do
description "Return a list of BookIds."
primary? true
end
read :by_id do
description "Return the BookId by its id."
argument :id, :uuid, allow_nil?: false
get? true
filter expr(id == ^arg(:id))
end
end
policies do
bypass actor_attribute_equals(:role, :admin) do
authorize_if always()
end
policy action_type(:read) do
authorize_if always()
end
policy action_type(:create) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:update) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:destroy) do
authorize_if actor_attribute_equals(:role, :moderator)
end
end
attributes do
uuid_primary_key :id, writable?: true
attribute :type, :string do
allow_nil? false
public? true
end
attribute :bid, :string do
allow_nil? false
public? true
end
attribute :order, :integer do
allow_nil? false
public? true
end
timestamps()
end
relationships do
belongs_to :dbi_server, Metadata.DBIServer
belongs_to :book, Metadata.Book do
allow_nil? true
end
end
end

@ -2,19 +2,84 @@ defmodule DecentralisedBookIndex.Metadata.DBIServer do
use Ash.Resource,
otp_app: :decentralised_book_index,
domain: DecentralisedBookIndex.Metadata,
data_layer: AshPostgres.DataLayer
data_layer: AshPostgres.DataLayer,
authorizers: [Ash.Policy.Authorizer],
extensions: [AshJsonApi.Resource]
alias DecentralisedBookIndex.Metadata
json_api do
type "dbi_server"
end
postgres do
table "dbi_servers"
repo DecentralisedBookIndex.Repo
custom_indexes do
index "name gin_trgm_ops", name: "server_name_gin_index", using: "GIN"
end
end
resource do
description "An DBIServer's metadata."
end
actions do
defaults [:read]
defaults [:read, :destroy]
create :create do
primary? true
accept [:name, :url, :sync_on?, :dbi_server_id]
end
create :sync_create do
accept [:id, :name, :url, :inserted_at, :updated_at, :dbi_server_id]
end
update :update do
primary? true
accept [:name, :url, :sync_on?]
end
update :sync do
accept [:name, :url, :inserted_at, :updated_at, :dbi_server_id]
end
read :by_id do
description "Return the DBIServer by its id."
argument :id, :uuid, allow_nil?: false
get? true
filter expr(id == ^arg(:id))
end
read :search do
description "Return a list of DBIServers, optionally filtering by name."
argument :name, :ci_string do
description "Return DBIServers, which names includes the name."
constraints allow_empty?: true
default ""
end
filter expr(contains(name, ^arg(:name)))
pagination offset?: true, default_limit: 10
end
end
policies do
bypass actor_attribute_equals(:role, :admin) do
authorize_if always()
end
policy action_type(:read) do
authorize_if always()
end
end
attributes do
uuid_primary_key :id
uuid_primary_key :id, writable?: true
attribute :name, :string do
allow_nil? false
@ -26,6 +91,30 @@ defmodule DecentralisedBookIndex.Metadata.DBIServer do
public? true
end
timestamps()
attribute :sync_on?, :boolean do
allow_nil? true
default false
end
timestamps do
writable? true
public? true
end
end
relationships do
belongs_to :dbi_server, Metadata.DBIServer do
public? true
end
has_many :author, Metadata.Author
has_many :author_alias_registries, Metadata.AuthorAliasRegistry
has_many :author_roles, Metadata.AuthorRole
has_many :books, Metadata.Book
has_many :bids, Metadata.BookId
has_many :book_editions_registries, Metadata.BookEditionsRegistry
has_many :publisher, Metadata.Publisher
end
end

@ -0,0 +1,124 @@
defmodule DecentralisedBookIndex.Metadata.Publisher do
use Ash.Resource,
otp_app: :decentralised_book_index,
domain: DecentralisedBookIndex.Metadata,
data_layer: AshPostgres.DataLayer,
extensions: [AshJsonApi.Resource],
authorizers: [Ash.Policy.Authorizer]
require Ash.Query
alias DecentralisedBookIndex.Metadata
json_api do
type "publisher"
end
postgres do
table "publishers"
repo DecentralisedBookIndex.Repo
custom_indexes do
index "name gin_trgm_ops", name: "publisher_name_gin_index", using: "GIN"
end
end
resource do
description "An publisher's metadata."
end
actions do
defaults [:destroy]
create :create do
primary? true
accept [:name, :dbi_server_id]
end
create :sync_create do
accept [:id, :name, :inserted_at, :updated_at, :dbi_server_id]
end
read :read do
description "Return a list of Publishers."
primary? true
end
read :by_id do
description "Return the Publisher by its id."
argument :id, :uuid, allow_nil?: false
get? true
filter expr(id == ^arg(:id))
end
read :search do
description "Return a list of Publishers, optionally filtering by name."
argument :name, :ci_string do
description "Return Publishers, which names includes the name."
constraints allow_empty?: true
default ""
end
filter expr(contains(name, ^arg(:name)))
pagination offset?: true, default_limit: 10
end
update :update do
primary? true
accept [:name]
end
update :assign_dbi_server_id do
accept [:dbi_server_id]
end
update :sync do
accept [:name, :inserted_at, :updated_at, :dbi_server_id]
end
end
policies do
bypass actor_attribute_equals(:role, :admin) do
authorize_if always()
end
policy action_type(:read) do
authorize_if always()
end
policy action_type(:create) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:update) do
authorize_if actor_attribute_equals(:role, :moderator)
end
policy action_type(:destroy) do
authorize_if actor_attribute_equals(:role, :admin)
end
end
attributes do
uuid_primary_key :id, writable?: true
attribute :name, :string do
allow_nil? false
public? true
end
timestamps do
writable? true
public? true
end
end
relationships do
belongs_to :dbi_server, Metadata.DBIServer do
public? true
end
has_many :books, Metadata.Book
end
end

@ -0,0 +1,28 @@
defmodule DecentralisedBookIndex.Release do
@moduledoc """
Used for executing DB release tasks when run in production without Mix
installed.
"""
@app :decentralised_book_index
def migrate do
load_app()
for repo <- repos() do
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true))
end
end
def rollback(repo, version) do
load_app()
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version))
end
defp repos do
Application.fetch_env!(@app, :ecto_repos)
end
defp load_app do
Application.load(@app)
end
end

@ -0,0 +1,15 @@
defmodule DecentralisedBookIndex.Sync.ApiClients.FetchJson do
def get(url) do
case Req.get(url) do
{:ok, data} ->
if data.status == 200 do
{:ok, data.body}
else
{:error, data}
end
{:error, message} ->
{:error, message}
end
end
end

@ -0,0 +1,37 @@
defmodule DecentralisedBookIndex.Sync.ApiClients.FetchJsons do
alias DecentralisedBookIndex.Sync.ApiClients.FetchJsons
alias DecentralisedBookIndex.Sync.ApiClients.FetchJson
require Logger
def get(url, mapper \\ &FetchJsons.get_data/1) do
query_results =
Stream.resource(
# Initial state:
fn -> url end,
fn
# Stop the stream if no more data
next when is_nil(next) ->
{:halt, nil}
next ->
case FetchJson.get(next) do
{:ok, page} ->
{mapper.(page["data"]), get_in(page, ["links", "next"])}
{:error, message} ->
Logger.error("FetchJsons error for #{url}: #{inspect(message)}")
{[], nil}
end
end,
fn _ -> :ok end
)
|> Enum.to_list()
{:ok, query_results}
end
def get_data(data) do
data
end
end

@ -0,0 +1,20 @@
defmodule DecentralisedBookIndex.Sync.DataTransformers.AuthorRoleTransformer do
def from_json(json_body) do
json_body =
if Map.has_key?(json_body, "data") do
json_body["data"]
else
json_body
end
attrs =
%{
id: get_in(json_body, ["id"]),
order: get_in(json_body, ["attributes", "order"]),
role: get_in(json_body, ["attributes", "role"]),
author_id: get_in(json_body, ["attributes", "author_id"])
}
{:ok, attrs}
end
end

@ -0,0 +1,21 @@
defmodule DecentralisedBookIndex.Sync.DataTransformers.AuthorRolesTransformer do
alias DecentralisedBookIndex.Sync.DataTransformers.AuthorRoleTransformer
def from_json(json_body) do
json_body =
if Map.has_key?(json_body, "data") do
json_body["data"]
else
json_body
end
{:ok,
Enum.map(
json_body,
fn record ->
{:ok, record} = AuthorRoleTransformer.from_json(record)
record
end
)}
end
end

@ -0,0 +1,29 @@
defmodule DecentralisedBookIndex.Sync.DataTransformers.AuthorTransformer do
def from_json(json_body) do
json_body =
if Map.has_key?(json_body, "data") do
json_body["data"]
else
json_body
end
attrs =
%{
id: get_in(json_body, ["id"]),
name: get_in(json_body, ["attributes", "name"]),
description: get_in(json_body, ["attributes", "description"]),
avatar_url: get_in(json_body, ["attributes", "avatar_url"]),
inserted_at: get_in(json_body, ["attributes", "inserted_at"]),
updated_at: get_in(json_body, ["attributes", "updated_at"]),
# relationship
author_alias_registry_id: get_in(json_body, ["attributes", "author_alias_registry_id"]),
dbi_server_id: get_in(json_body, ["attributes", "dbi_server_id"])
}
if is_nil(attrs[:dbi_server_id]) do
{:ok, attrs |> Map.delete(:dbi_server_id)}
else
{:ok, attrs}
end
end
end

@ -0,0 +1,20 @@
defmodule DecentralisedBookIndex.Sync.DataTransformers.BidTransformer do
def from_json(json_body) do
json_body =
if Map.has_key?(json_body, "data") do
json_body["data"]
else
json_body
end
attrs =
%{
id: get_in(json_body, ["id"]),
order: get_in(json_body, ["attributes", "order"]),
type: get_in(json_body, ["attributes", "type"]),
bid: get_in(json_body, ["attributes", "bid"])
}
{:ok, attrs}
end
end

@ -0,0 +1,21 @@
defmodule DecentralisedBookIndex.Sync.DataTransformers.BidsTransformer do
alias DecentralisedBookIndex.Sync.DataTransformers.BidTransformer
def from_json(json_body) do
json_body =
if Map.has_key?(json_body, "data") do
json_body["data"]
else
json_body
end
{:ok,
Enum.map(
json_body,
fn record ->
{:ok, record} = BidTransformer.from_json(record)
record
end
)}
end
end

@ -0,0 +1,35 @@
defmodule DecentralisedBookIndex.Sync.DataTransformers.BookTransformer do
def from_json(json_body) do
json_body =
if Map.has_key?(json_body, "data") do
json_body["data"]
else
json_body
end
attrs =
%{
id: get_in(json_body, ["id"]),
title: get_in(json_body, ["attributes", "title"]),
description: get_in(json_body, ["attributes", "description"]),
cover_image_url: get_in(json_body, ["attributes", "cover_image_url"]),
format: get_in(json_body, ["attributes", "format"]),
language: get_in(json_body, ["attributes", "language"]),
published: get_in(json_body, ["attributes", "published"]),
page_count: get_in(json_body, ["attributes", "page_count"]),
publisher_id: get_in(json_body, ["attributes", "publisher_id"]),
inserted_at: get_in(json_body, ["attributes", "inserted_at"]),
updated_at: get_in(json_body, ["attributes", "updated_at"]),
# relationship
publisher_id: get_in(json_body, ["attributes", "publisher_id"]),
# relationship
dbi_server_id: get_in(json_body, ["attributes", "dbi_server_id"])
}
if is_nil(attrs[:dbi_server_id]) do
{:ok, attrs |> Map.delete(:dbi_server_id)}
else
{:ok, attrs}
end
end
end

@ -0,0 +1,27 @@
defmodule DecentralisedBookIndex.Sync.DataTransformers.DBIServerTransformer do
def from_json(json_body) do
json_body =
if Map.has_key?(json_body, "data") do
json_body["data"]
else
json_body
end
attrs =
%{
id: get_in(json_body, ["id"]),
name: get_in(json_body, ["attributes", "name"]),
url: get_in(json_body, ["attributes", "url"]),
inserted_at: get_in(json_body, ["attributes", "inserted_at"]),
updated_at: get_in(json_body, ["attributes", "updated_at"]),
# relationship
dbi_server_id: get_in(json_body, ["attributes", "dbi_server_id"])
}
if is_nil(attrs[:dbi_server_id]) do
{:ok, attrs |> Map.delete(:dbi_server_id)}
else
{:ok, attrs}
end
end
end

@ -0,0 +1,26 @@
defmodule DecentralisedBookIndex.Sync.DataTransformers.PublisherTransformer do
def from_json(json_body) do
json_body =
if Map.has_key?(json_body, "data") do
json_body["data"]
else
json_body
end
attrs =
%{
id: get_in(json_body, ["id"]),
name: get_in(json_body, ["attributes", "name"]),
inserted_at: get_in(json_body, ["attributes", "inserted_at"]),
updated_at: get_in(json_body, ["attributes", "updated_at"]),
# relationship
dbi_server_id: get_in(json_body, ["attributes", "dbi_server_id"])
}
if is_nil(attrs[:dbi_server_id]) do
{:ok, attrs |> Map.delete(:dbi_server_id)}
else
{:ok, attrs}
end
end
end

@ -0,0 +1,31 @@
defmodule DecentralisedBookIndex.Sync.AuthorAliasRegistrySync do
alias DecentralisedBookIndex.Metadata
alias DecentralisedBookIndex.Metadata.AuthorAliasRegistry
def create_update(attrs, server_id) do
case Metadata.get_author_alias_registry_by_id(attrs.id) do
{:ok, alias_registry} ->
attrs =
attrs
|> Map.delete(:id)
|> Map.put(:dbi_server_id, server_id)
alias_registry
|> Ash.Changeset.for_update(:sync, attrs)
|> Ash.update!(authorize?: false)
:ok
{:error, %Ash.Error.Query.NotFound{}} ->
attrs =
attrs
|> Map.put(:dbi_server_id, server_id)
AuthorAliasRegistry
|> Ash.Changeset.for_create(:sync_create, attrs)
|> Ash.create!(authorize?: false)
:ok
end
end
end

@ -0,0 +1,76 @@
defmodule DecentralisedBookIndex.Sync.AuthorSync do
alias DecentralisedBookIndex.Metadata
alias DecentralisedBookIndex.Metadata.Author
alias DecentralisedBookIndex.Sync.AuthorAliasRegistrySync
def create_update(attrs, server_id) do
registry_info = sync_registry(attrs, server_id)
case Metadata.get_author_by_id(attrs.id) do
{:ok, author} ->
if not is_local(author) and is_new(attrs, author) do
attrs =
attrs
|> Map.delete(:id)
|> update_registry(registry_info)
|> Map.put_new(:dbi_server_id, server_id)
author
|> Ash.Changeset.for_update(:sync, attrs)
|> Ash.update!(authorize?: false)
end
:ok
{:error, %Ash.Error.Query.NotFound{}} ->
attrs =
attrs
|> update_registry(registry_info)
|> Map.put_new(:dbi_server_id, server_id)
Author
|> Ash.Changeset.for_create(:sync_create, attrs)
|> Ash.create!(authorize?: false)
:ok
end
end
defp sync_registry(attrs, server_id) do
id = Map.get(attrs, :author_alias_registry_id, nil)
if id != nil do
%{id: id}
|> AuthorAliasRegistrySync.create_update(server_id)
{:ok, id}
else
{:error, :no_author_alias_registry_id}
end
end
defp update_registry(attrs, registry_info) do
case registry_info do
{:ok, id} ->
attrs
|> Map.replace(:author_alias_registry_id, id)
{:error, _} ->
attrs
|> Map.delete(:author_alias_registry_id)
end
end
defp is_local(author) do
is_nil(author.dbi_server_id)
end
defp is_new(new_author, author) do
with {:ok, datetime, _offset} <- DateTime.from_iso8601(new_author[:updated_at]) do
DateTime.after?(datetime, author.updated_at)
else
{:error, reason} ->
false
end
end
end

@ -0,0 +1,31 @@
defmodule DecentralisedBookIndex.Sync.BookEditionsRegistrySync do
alias DecentralisedBookIndex.Metadata
alias DecentralisedBookIndex.Metadata.BookEditionsRegistry
def create_update(attrs, server_id) do
case Metadata.get_book_editions_registry_by_id(attrs.id) do
{:ok, editions_registry} ->
attrs =
attrs
|> Map.delete(:id)
|> Map.put(:dbi_server_id, server_id)
editions_registry
|> Ash.Changeset.for_update(:sync, attrs)
|> Ash.update!(authorize?: false)
:ok
{:error, %Ash.Error.Query.NotFound{}} ->
attrs =
attrs
|> Map.put(:dbi_server_id, server_id)
BookEditionsRegistry
|> Ash.Changeset.for_create(:sync_create, attrs)
|> Ash.create!(authorize?: false)
:ok
end
end
end

@ -0,0 +1,77 @@
defmodule DecentralisedBookIndex.Sync.BookSync do
alias DecentralisedBookIndex.Metadata
alias DecentralisedBookIndex.Metadata.Book
alias DecentralisedBookIndex.Sync.BookEditionsRegistrySync
def create_update(attrs, server_id) do
registry_info = sync_registry(attrs, server_id)
case Metadata.get_book_by_id(attrs.id) do
{:ok, book} ->
if not is_local(book) and is_new(attrs, book) do
attrs =
attrs
|> Map.delete(:id)
|> update_registry(registry_info)
|> Map.put_new(:dbi_server_id, server_id)
book
|> Ash.Changeset.for_update(:sync, attrs)
|> Ash.update!(authorize?: false)
end
:ok
{:error, %Ash.Error.Query.NotFound{}} ->
attrs =
attrs
|> update_registry(registry_info)
|> Map.put_new(:dbi_server_id, server_id)
Book
|> Ash.Changeset.for_create(:sync_create, attrs)
|> Ash.create!(authorize?: false)
:ok
end
end
defp sync_registry(attrs, server_id) do
id = Map.get(attrs, :book_editions_registry_id, nil)
if id != nil do
%{id: id}
|> BookEditionsRegistrySync.create_update(server_id)
{:ok, id}
else
{:error, :no_book_editions_registry_id}
end
end
defp update_registry(attrs, registry_info) do
case registry_info do
{:ok, id} ->
attrs
|> Map.replace(:book_editions_registry_id, id)
{:error, _} ->
attrs
|> Map.delete(:book_editions_registry_id)
end
end
defp is_local(book) do
is_nil(book.dbi_server_id)
end
defp is_new(new_book, book) do
with {:ok, datetime, _offset} <- DateTime.from_iso8601(new_book[:updated_at]) do
DateTime.after?(datetime, book.updated_at)
else
{:error, reason} ->
false
end
end
end

@ -0,0 +1,31 @@
defmodule DecentralisedBookIndex.Sync.DBIServerSync do
alias DecentralisedBookIndex.Metadata
alias DecentralisedBookIndex.Metadata.DBIServer
def create_update(attrs, server_id) do
case Metadata.get_dbi_server_by_id(attrs.id) do
{:ok, dbi_server} ->
attrs =
attrs
|> Map.delete(:id)
|> Map.put(:dbi_server_id, server_id)
dbi_server
|> Ash.Changeset.for_update(:sync, attrs)
|> Ash.update!(authorize?: false)
:ok
{:error, %Ash.Error.Query.NotFound{}} ->
attrs =
attrs
|> Map.put(:dbi_server_id, server_id)
DBIServer
|> Ash.Changeset.for_create(:sync_create, attrs)
|> Ash.create!(authorize?: false)
:ok
end
end
end

@ -0,0 +1,46 @@
defmodule DecentralisedBookIndex.Sync.PublisherSync do
alias DecentralisedBookIndex.Metadata
alias DecentralisedBookIndex.Metadata.Publisher
def create_update(attrs, server_id) do
case Metadata.get_publisher_by_id(attrs.id) do
{:ok, publisher} ->
if not is_local(publisher) and is_new(attrs, publisher) do
attrs =
attrs
|> Map.delete(:id)
|> Map.put_new(:dbi_server_id, server_id)
publisher
|> Ash.Changeset.for_update(:sync, attrs)
|> Ash.update!(authorize?: false)
end
:ok
{:error, %Ash.Error.Query.NotFound{}} ->
attrs =
attrs
|> Map.put_new(:dbi_server_id, server_id)
Publisher
|> Ash.Changeset.for_create(:sync_create, attrs)
|> Ash.create!(authorize?: false)
:ok
end
end
defp is_local(publisher) do
is_nil(publisher.dbi_server_id)
end
defp is_new(new_publisher, publisher) do
with {:ok, datetime, _offset} <- DateTime.from_iso8601(new_publisher[:updated_at]) do
DateTime.after?(datetime, publisher.updated_at)
else
{:error, reason} ->
false
end
end
end

@ -0,0 +1,36 @@
defmodule DecentralisedBookIndex.SyncTasks.SyncAuthorsTask do
alias DecentralisedBookIndex.Sync.ApiClients.FetchJsons
alias DecentralisedBookIndex.Sync.DataTransformers.AuthorTransformer
alias DecentralisedBookIndex.Sync.AuthorSync
alias DecentralisedBookIndex.Metadata.DBIServer
require Logger
def sync(%DBIServer{} = server, url_params \\ "") do
url = "#{server.url}/api/v1/json/authors#{url_params}"
FetchJsons.get(url, sync_author_closure(server))
server
end
def sync_author_chunk(json_chunk, server_id) do
for json <- json_chunk do
with {:ok, attrs} <- AuthorTransformer.from_json(json),
:ok <- AuthorSync.create_update(attrs, server_id) do
:ok
else
{:error, reason} ->
Logger.error("Pipeline error: #{inspect(reason)}")
end
end
[]
end
def sync_author_closure(server) do
fn json_chunk ->
sync_author_chunk(json_chunk, server.id)
end
end
end

@ -0,0 +1,84 @@
defmodule DecentralisedBookIndex.SyncTasks.SyncBooksTask do
alias DecentralisedBookIndex.Sync.ApiClients.FetchJson
alias DecentralisedBookIndex.Sync.ApiClients.FetchJsons
alias DecentralisedBookIndex.Sync.DataTransformers.BookTransformer
alias DecentralisedBookIndex.Sync.DataTransformers.BidsTransformer
alias DecentralisedBookIndex.Sync.DataTransformers.AuthorRolesTransformer
alias DecentralisedBookIndex.Sync.BookSync
alias DecentralisedBookIndex.Metadata.DBIServer
require Logger
def sync(%DBIServer{} = server, url_params \\ "") do
url = "#{server.url}/api/v1/json/books#{url_params}"
FetchJsons.get(url, sync_author_closure(server))
server
end
def sync_author_chunk(json_chunk, server_id) do
for json <- json_chunk do
with {:ok, attrs} <- BookTransformer.from_json(json),
{:ok, author_roles} <- get_author_roles(json),
{:ok, bids} <- get_bids(json),
attrs <- merge_relationships_attrs(attrs, bids, author_roles),
:ok <- BookSync.create_update(attrs, server_id) do
:ok
else
{:error, reason} ->
Logger.error("Pipeline error: #{inspect(reason)}")
end
end
[]
end
def sync_author_closure(server) do
fn json_chunk ->
sync_author_chunk(json_chunk, server.id)
end
end
defp merge_relationships_attrs(attrs, bids, author_roles) do
attrs
|> Map.put(:bids, bids)
|> Map.put(:author_roles, author_roles)
end
defp get_author_roles_url(json) do
get_in(json, ["relationships", "author_roles", "links", "related"])
end
defp get_author_roles(json) do
url = get_author_roles_url(json)
with {:ok, json} <- FetchJson.get(url),
{:ok, roles} <- AuthorRolesTransformer.from_json(json) do
{:ok, roles}
else
{:error, reason} ->
Logger.error("Pipeline error: #{inspect(reason)}")
{:error, reason}
end
end
defp get_bids_url(json) do
get_in(json, ["relationships", "bids", "links", "related"])
end
defp get_bids(json) do
url = json |> get_bids_url()
with {:ok, json} <- FetchJson.get(url),
{:ok, bids} <- BidsTransformer.from_json(json) do
{:ok, bids}
else
{:error, reason} ->
Logger.error("Pipeline error: #{inspect(reason)}")
{:error, reason}
end
end
end

@ -0,0 +1,36 @@
defmodule DecentralisedBookIndex.SyncTasks.SyncDBIServerTask do
alias DecentralisedBookIndex.Sync.ApiClients.FetchJsons
alias DecentralisedBookIndex.Sync.DataTransformers.DBIServerTransformer
alias DecentralisedBookIndex.Sync.DBIServerSync
alias DecentralisedBookIndex.Metadata.DBIServer
require Logger
def sync(%DBIServer{} = server, url_params \\ "") do
url = "#{server.url}/api/v1/json/servers#{url_params}"
FetchJsons.get(url, sync_closure(server))
server
end
def sync_chunk(json_chunk, server_id) do
for json <- json_chunk do
with {:ok, attrs} <- DBIServerTransformer.from_json(json),
:ok <- DBIServerSync.create_update(attrs, server_id) do
:ok
else
{:error, reason} ->
Logger.error("Pipeline error: #{inspect(reason)}")
end
end
[]
end
def sync_closure(server) do
fn json_chunk ->
sync_chunk(json_chunk, server.id)
end
end
end

@ -0,0 +1,36 @@
defmodule DecentralisedBookIndex.SyncTasks.SyncPublishersTask do
alias DecentralisedBookIndex.Sync.ApiClients.FetchJsons
alias DecentralisedBookIndex.Sync.DataTransformers.PublisherTransformer
alias DecentralisedBookIndex.Sync.PublisherSync
alias DecentralisedBookIndex.Metadata.DBIServer
require Logger
def sync(%DBIServer{} = server, url_params \\ "") do
url = "#{server.url}/api/v1/json/publishers#{url_params}"
FetchJsons.get(url, sync_closure(server))
server
end
def sync_chunk(json_chunk, server_id) do
for json <- json_chunk do
with {:ok, attrs} <- PublisherTransformer.from_json(json),
:ok <- PublisherSync.create_update(attrs, server_id) do
:ok
else
{:error, reason} ->
Logger.error("Pipeline error: #{inspect(reason)}")
end
end
[]
end
def sync_closure(server) do
fn json_chunk ->
sync_chunk(json_chunk, server.id)
end
end
end

@ -0,0 +1,37 @@
defmodule DecentralisedBookIndex.SyncTasks.SyncServerTask do
alias DecentralisedBookIndex.Metadata
alias DecentralisedBookIndex.Metadata.DBIServer
alias DecentralisedBookIndex.SyncTasks.SyncDBIServerTask
alias DecentralisedBookIndex.SyncTasks.SyncAuthorsTask
alias DecentralisedBookIndex.SyncTasks.SyncPublishersTask
alias DecentralisedBookIndex.SyncTasks.SyncBooksTask
def sync_all(last_sync_datetime \\ nil) do
{:ok, servers} = Metadata.list_dbi_server(authorize?: false)
params = params(last_sync_datetime)
for server <- servers do
if server.sync_on?, do: sync_one(server, params)
end
:ok
end
def sync_one(%DBIServer{} = server, url_params \\ "") do
server
|> SyncDBIServerTask.sync(url_params)
|> SyncAuthorsTask.sync(url_params)
|> SyncPublishersTask.sync(url_params)
|> SyncBooksTask.sync(url_params)
:ok
end
defp params(datetime) when is_nil(datetime), do: ""
defp params(datetime) when not is_nil(datetime) do
"?filter[updated_at][gte]=#{DateTime.to_iso8601(datetime)}"
end
end

@ -0,0 +1,21 @@
defmodule DecentralisedBookIndex.SyncWorker do
use Oban.Worker,
queue: :default,
max_attempts: 2,
tags: ["sync", "cron"]
require Logger
alias DecentralisedBookIndex.SyncTasks.SyncServerTask
@impl Oban.Worker
def perform(%Oban.Job{args: args} = job) do
Logger.info("The cron job (#{job.id}) run SyncServerTask at #{DateTime.utc_now()} with args: #{inspect(args)}.")
result = SyncServerTask.sync_all()
Logger.info("The cron job (#{job.id}) is done.")
result
end
end

@ -0,0 +1,31 @@
defmodule DecentralisedBookIndex.SyncWorkerManual do
use Oban.Worker,
queue: :default,
max_attempts: 2,
tags: ["sync", "manual"]
require Logger
alias DecentralisedBookIndex.SyncTasks.SyncServerTask
@topic "task:events"
@impl Oban.Worker
def perform(%Oban.Job{args: args} = job) do
Logger.info("The manual job (#{job.id}) run SyncServerTask at #{DateTime.utc_now()} with args: #{inspect(args)}.")
result = SyncServerTask.sync_all()
Phoenix.PubSub.broadcast!(
DecentralisedBookIndex.PubSub,
@topic,
{:manual_sync_completed, result}
)
Logger.info("The manual job (#{job.id}) is done.")
result
end
def topic, do: @topic
end

@ -89,6 +89,8 @@ defmodule DecentralisedBookIndexWeb do
import Phoenix.HTML
# Core UI components
import DecentralisedBookIndexWeb.CoreComponents
use DecentralisedBookIndexWeb.Components.MyPartials
use DecentralisedBookIndexWeb.Components.MyComponents
# Shortcut for generating JS commands
alias Phoenix.LiveView.JS

@ -1,5 +1,5 @@
defmodule DecentralisedBookIndexWeb.AshJsonApiRouter do
use AshJsonApi.Router,
domains: [],
domains: [Module.concat(["DecentralisedBookIndex.Metadata"])],
open_api: "/open_api"
end

@ -9,10 +9,12 @@ defmodule DecentralisedBookIndexWeb.AuthOverrides do
# For a complete reference, see https://hexdocs.pm/ash_authentication_phoenix/ui-overrides.html
# override AshAuthentication.Phoenix.Components.Banner do
# set :image_url, "https://media.giphy.com/media/g7GKcSzwQfugw/giphy.gif"
# set :text_class, "bg-red-500"
# end
override AshAuthentication.Phoenix.Components.Banner do
# set :image_url, "https://media.giphy.com/media/g7GKcSzwQfugw/giphy.gif"
# set :text_class, "bg-red-500"
set :image_url, nil
set :dark_image_url, nil
end
# override AshAuthentication.Phoenix.Components.SignIn do
# set :show_banner, false

@ -50,7 +50,7 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
data-cancel={JS.exec(@on_cancel, "phx-remove")}
class="relative z-50 hidden"
>
<div id={"#{@id}-bg"} class="bg-zinc-50/90 fixed inset-0 transition-opacity" aria-hidden="true" />
<div id={"#{@id}-bg"} class="bg-zinc-50/90 dark:bg-gray-900/90 fixed inset-0 transition-opacity" aria-hidden="true" />
<div
class="fixed inset-0 overflow-y-auto"
aria-labelledby={"#{@id}-title"}
@ -66,7 +66,7 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
phx-window-keydown={JS.exec("data-cancel", to: "##{@id}")}
phx-key="escape"
phx-click-away={JS.exec("data-cancel", to: "##{@id}")}
class="shadow-zinc-700/10 ring-zinc-700/10 relative hidden rounded-2xl bg-white p-14 shadow-lg ring-1 transition"
class="shadow-zinc-700/10 ring-zinc-700/10 relative hidden rounded-2xl bg-white p-14 shadow-lg ring-1 transition dark:bg-gray-900"
>
<div class="absolute top-6 right-5">
<button
@ -75,7 +75,7 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
class="-m-3 flex-none p-3 opacity-20 hover:opacity-40"
aria-label={gettext("close")}
>
<.icon name="hero-x-mark-solid" class="h-5 w-5" />
<.icon name="hero-x-mark-solid" class="h-5 w-5 dark:text-white" />
</button>
</div>
<div id={"#{@id}-content"}>
@ -176,6 +176,69 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
"""
end
attr :kind, :string,
values: ~w(base primary error),
default: "base"
attr :inverse, :boolean, default: false
attr :size, :string, values: ~w(sm xs md), default: "md"
attr :class, :string, default: ""
attr :rest, :global, include: ~w(navigate disabled patch)
slot :inner_block
def button_link(assigns) do
assigns =
assign(assigns, :theme, button_styles(assigns.kind, assigns.inverse, assigns.size))
~H"""
<.link
class={[
@theme,
@rest[:disabled] && "opacity-60 grayscale pointer-events-none",
@class
]}
{@rest}
>
{render_slot(@inner_block)}
</.link>
"""
end
def button_styles(kind, inverse, size) do
theme =
case {kind, inverse} do
{"base", false} ->
"bg-gray-100"
{"base", true} ->
"border border-gray-500 text-gray-600"
{"primary", false} ->
"bg-primary-600 hover:bg-primary-700 text-white dark:text-white"
{"primary", true} ->
"border border-primary-700 text-primary-700 hover:bg-primary-50 font-semibold dark:text-white"
{"error", false} ->
"bg-error-700 hover:bg-error-800 text-white"
{"error", true} ->
"text-error-600 underline"
_ ->
""
end
[
"phx-submit-loading:opacity-75 rounded-lg font-medium leading-none inline-block",
size == "md" && "py-3 px-5 text-sm",
size == "sm" && "py-2 px-3 text-sm",
size == "xs" && "py-2 px-2 text-xs",
theme
]
end
@doc """
Renders a simple form.
@ -202,9 +265,9 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
def simple_form(assigns) do
~H"""
<.form :let={f} for={@for} as={@as} {@rest}>
<div class="mt-10 space-y-8 bg-white">
<div class="mt-10 space-y-8 bg-white dark:bg-gray-900">
{render_slot(@inner_block, f)}
<div :for={action <- @actions} class="mt-2 flex items-center justify-between gap-6">
<div :for={action <- @actions} class="mt-2 flex items-center justify-start gap-6">
{render_slot(action, f)}
</div>
</div>
@ -282,6 +345,7 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
doc: "a form field struct retrieved from the form, for example: @form[:email]"
attr :errors, :list, default: []
attr :show_errors?, :boolean, default: true
attr :checked, :boolean, doc: "the checked flag for checkbox inputs"
attr :prompt, :string, default: nil, doc: "the prompt for select inputs"
attr :options, :list, doc: "the options to pass to Phoenix.HTML.Form.options_for_select/2"
@ -310,7 +374,7 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
~H"""
<div>
<label class="flex items-center gap-4 text-sm leading-6 text-zinc-600">
<label class="flex items-center gap-4 text-sm leading-6 text-zinc-600 dark:text-white">
<input type="hidden" name={@name} value="false" disabled={@rest[:disabled]} />
<input
type="checkbox"
@ -318,12 +382,14 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
name={@name}
value="true"
checked={@checked}
class="rounded border-zinc-300 text-zinc-900 focus:ring-0"
class="rounded text-blue-600 bg-gray-100 border-gray-300 rounded-sm focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600"
{@rest}
/>
{@label}
</label>
<.error :for={msg <- @errors}>{msg}</.error>
<%= if @show_errors? do %>
<.error :for={msg <- @errors}>{msg}</.error>
<% end %>
</div>
"""
end
@ -335,14 +401,16 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
<select
id={@id}
name={@name}
class="mt-2 block w-full rounded-md border border-gray-300 bg-white shadow-sm focus:border-zinc-400 focus:ring-0 sm:text-sm"
class="mt-2 block w-full rounded-md border border-gray-300 bg-white shadow-sm focus:border-zinc-400 focus:ring-0 sm:text-sm dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
multiple={@multiple}
{@rest}
>
<option :if={@prompt} value="">{@prompt}</option>
{Phoenix.HTML.Form.options_for_select(@options, @value)}
</select>
<.error :for={msg <- @errors}>{msg}</.error>
<%= if @show_errors? do %>
<.error :for={msg <- @errors}>{msg}</.error>
<% end %>
</div>
"""
end
@ -355,13 +423,15 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
id={@id}
name={@name}
class={[
"mt-2 block w-full rounded-lg text-zinc-900 focus:ring-0 sm:text-sm sm:leading-6 min-h-[6rem]",
"mt-2 block w-full rounded-lg text-zinc-900 focus:ring-0 sm:text-sm sm:leading-6 min-h-[6rem] dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500",
@errors == [] && "border-zinc-300 focus:border-zinc-400",
@errors != [] && "border-rose-400 focus:border-rose-400"
@errors != [] && "border-rose-400 focus:border-rose-400 dark:border-rose-400 dark:focus:border-rose-400"
]}
{@rest}
>{Phoenix.HTML.Form.normalize_value("textarea", @value)}</textarea>
<.error :for={msg <- @errors}>{msg}</.error>
<%= if @show_errors? do %>
<.error :for={msg <- @errors}>{msg}</.error>
<% end %>
</div>
"""
end
@ -377,13 +447,15 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
id={@id}
value={Phoenix.HTML.Form.normalize_value(@type, @value)}
class={[
"mt-2 block w-full rounded-lg text-zinc-900 focus:ring-0 sm:text-sm sm:leading-6",
"mt-2 block w-full rounded-lg text-zinc-900 focus:ring-0 sm:text-sm sm:leading-6 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500",
@errors == [] && "border-zinc-300 focus:border-zinc-400",
@errors != [] && "border-rose-400 focus:border-rose-400"
@errors != [] && "border-rose-400 focus:border-rose-400 dark:border-rose-400 dark:focus:border-rose-400"
]}
{@rest}
/>
<.error :for={msg <- @errors}>{msg}</.error>
<%= if @show_errors? do %>
<.error :for={msg <- @errors}>{msg}</.error>
<% end %>
</div>
"""
end
@ -396,7 +468,7 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
def label(assigns) do
~H"""
<label for={@for} class="block text-sm font-semibold leading-6 text-zinc-800">
<label for={@for} class="block text-sm font-semibold leading-6 text-zinc-800 dark:text-white">
{render_slot(@inner_block)}
</label>
"""
@ -429,10 +501,10 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
~H"""
<header class={[@actions != [] && "flex items-center justify-between gap-6", @class]}>
<div>
<h1 class="text-lg font-semibold leading-8 text-zinc-800">
<h1 class="text-lg font-semibold leading-8 text-zinc-800 dark:text-white">
{render_slot(@inner_block)}
</h1>
<p :if={@subtitle != []} class="mt-2 text-sm leading-6 text-zinc-600">
<p :if={@subtitle != []} class="mt-2 text-sm leading-6 text-zinc-600 dark:text-white">
{render_slot(@subtitle)}
</p>
</div>
@ -473,11 +545,11 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
end
~H"""
<div class="overflow-y-auto px-4 sm:overflow-visible sm:px-0">
<table class="w-[40rem] mt-11 sm:w-full">
<thead class="text-sm text-left leading-6 text-zinc-500">
<div class="overflow-y-auto px-4 sm:overflow-visible sm:px-0 ">
<table class="w-full text-sm text-left text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-800 relative shadow-md sm:rounded-lg overflow-hidden">
<thead class="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
<tr>
<th :for={col <- @col} class="p-0 pb-4 pr-6 font-normal">{col[:label]}</th>
<th :for={col <- @col} class="p-4 font-normal">{col[:label]}</th>
<th :if={@action != []} class="relative p-0 pb-4">
<span class="sr-only">{gettext("Actions")}</span>
</th>
@ -486,9 +558,9 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
<tbody
id={@id}
phx-update={match?(%Phoenix.LiveView.LiveStream{}, @rows) && "stream"}
class="relative divide-y divide-zinc-100 border-t border-zinc-200 text-sm leading-6 text-zinc-700"
class="relative divide-zinc-100 text-sm leading-6 text-zinc-700"
>
<tr :for={row <- @rows} id={@row_id && @row_id.(row)} class="group hover:bg-zinc-50">
<tr :for={row <- @rows} id={@row_id && @row_id.(row)} class=" bg-white shadow-md dark:bg-gray-800 hover:bg-gray-100 dark:bg-gray-850 dark:hover:bg-gray-700">
<td
:for={{col, i} <- Enum.with_index(@col)}
phx-click={@row_click && @row_click.(row)}
@ -496,17 +568,17 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
>
<div class="block py-4 pr-6">
<span class="absolute -inset-y-px right-0 -left-4 group-hover:bg-zinc-50 sm:rounded-l-xl" />
<span class={["relative", i == 0 && "font-semibold text-zinc-900"]}>
<span class={["p-4 relative font-sm text-gray-500 dark:text-gray-400", i == 0 && "p-4 medium text-gray-900 whitespace-nowrap dark:text-white"]}>
{render_slot(col, @row_item.(row))}
</span>
</div>
</td>
<td :if={@action != []} class="relative w-14 p-0">
<div class="relative whitespace-nowrap py-4 text-right text-sm font-medium">
<div class="relative whitespace-nowrap py-4 text-right text-sm font-medium px-2">
<span class="absolute -inset-y-px -right-4 left-0 group-hover:bg-zinc-50 sm:rounded-r-xl" />
<span
:for={action <- @action}
class="relative ml-4 font-semibold leading-6 text-zinc-900 hover:text-zinc-700"
class="relative ml-4 font-semibold leading-6 text-zinc-900 hover:text-zinc-700 dark:text-white dark:hover:text-white/90"
>
{render_slot(action, @row_item.(row))}
</span>
@ -538,8 +610,8 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
<div class="mt-14">
<dl class="-my-4 divide-y divide-zinc-100">
<div :for={item <- @item} class="flex gap-4 py-4 text-sm leading-6 sm:gap-8">
<dt class="w-1/4 flex-none text-zinc-500">{item.title}</dt>
<dd class="text-zinc-700">{render_slot(item)}</dd>
<dt class="w-1/4 flex-none text-zinc-500 dark:text-white">{item.title}</dt>
<dd class="text-zinc-700 dark:text-white">{render_slot(item)}</dd>
</div>
</dl>
</div>
@ -561,7 +633,7 @@ defmodule DecentralisedBookIndexWeb.CoreComponents do
<div class="mt-16">
<.link
navigate={@navigate}
class="text-sm font-semibold leading-6 text-zinc-900 hover:text-zinc-700"
class="text-sm font-semibold leading-6 text-zinc-900 hover:text-zinc-700 dark:text-white dark:hover:text-white/70"
>
<.icon name="hero-arrow-left-solid" class="h-3 w-3" />
{render_slot(@inner_block)}

@ -1,32 +1,17 @@
<header class="px-4 sm:px-6 lg:px-8">
<div class="flex items-center justify-between border-b border-zinc-100 py-3 text-sm">
<div class="flex items-center gap-4">
<a href="/">
<img src={~p"/images/logo.svg"} width="36" />
</a>
<p class="bg-brand/5 text-brand rounded-full px-2 font-medium leading-6">
v{Application.spec(:phoenix, :vsn)}
</p>
<div class="flex flex-col h-screen">
<header>
<.partial_navbar
page_title={assigns[:page_title]}
current_user={assigns[:current_user]}
/>
</header>
<main class="px-4 pt-20 pb-2 sm:px-6 lg:px-8 flex-grow">
<div class="mx-auto max-w-4xl">
<.flash_group flash={@flash} />
{@inner_content}
</div>
<div class="flex items-center gap-4 font-semibold leading-6 text-zinc-900">
<a href="https://twitter.com/elixirphoenix" class="hover:text-zinc-700">
@elixirphoenix
</a>
<a href="https://github.com/phoenixframework/phoenix" class="hover:text-zinc-700">
GitHub
</a>
<a
href="https://hexdocs.pm/phoenix/overview.html"
class="rounded-lg bg-zinc-100 px-2 py-1 hover:bg-zinc-200/80"
>
Get Started <span aria-hidden="true">&rarr;</span>
</a>
</div>
</div>
</header>
<main class="px-4 py-20 sm:px-6 lg:px-8">
<div class="mx-auto max-w-2xl">
<.flash_group flash={@flash} />
{@inner_content}
</div>
</main>
</main>
<.partial_footer />
</div>

@ -4,14 +4,14 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="csrf-token" content={get_csrf_token()} />
<.live_title default="DecentralisedBookIndex" suffix=" · Phoenix Framework">
<.live_title default="DecentralisedBookIndex">
{assigns[:page_title]}
</.live_title>
<link phx-track-static rel="stylesheet" href={~p"/assets/app.css"} />
<script defer phx-track-static type="text/javascript" src={~p"/assets/app.js"}>
</script>
</head>
<body class="bg-white">
<body class="bg-white dark:bg-gray-900">
{@inner_content}
</body>
</html>

@ -0,0 +1,39 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents do
alias DecentralisedBookIndexWeb.Components.MyComponents
defmacro __using__(_) do
quote do
import MyComponents.BookCard, only: [book_card: 1]
import MyComponents.BookSearch, only: [book_search: 1]
import MyComponents.AuthorCard, only: [author_card: 1]
import MyComponents.SearchResources, only: [search_resources: 1]
import MyComponents.JustSearchResources, only: [just_search_resources: 1]
import MyComponents.Pagination, only: [pagination: 1]
import MyComponents.Buttons,
only: [
success_button: 1,
primary_button: 1,
add_button_link: 1,
save_button: 1,
edit_button: 1,
cancel_button: 1
]
alias MyComponents.SelectPublisher
import MyComponents.SelectedPublisher, only: [selected_publisher: 1]
alias MyComponents.SelectAuthor
import MyComponents.SelectedAuthor, only: [selected_author: 1]
alias MyComponents.SelectBookEdition
import MyComponents.SelectedBookEdition, only: [selected_book_edition: 1]
alias MyComponents.SelectAuthorAlias
import MyComponents.SelectedAuthorAlias, only: [selected_author_alias: 1]
end
end
end

@ -0,0 +1,101 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.AuthorCard do
use Phoenix.Component
use DecentralisedBookIndexWeb, :verified_routes
alias DecentralisedBookIndex.Accounts.Role
attr(:author, :map, required: true)
attr :current_user, :map, default: nil
def author_card(assigns) do
~H"""
<div class="w-full max-w-sm bg-white border border-gray-200 rounded-lg shadow-sm dark:bg-gray-800 dark:border-gray-700 mx-auto my-3">
<%= if @current_user != nil and Role.can_moderate?(@current_user.role) and is_nil(@author.dbi_server) do %>
<div class="flex justify-end px-4 pt-4">
<button
id={"dropdownButton#{@author.id}"}
data-dropdown-toggle={"dropdown#{@author.id}"}
class="inline-block text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 focus:ring-4 focus:outline-none focus:ring-gray-200 dark:focus:ring-gray-700 rounded-lg text-sm p-1.5"
type="button"
>
<span class="sr-only">Open dropdown</span>
<svg
class="w-5 h-5"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
fill="currentColor"
viewBox="0 0 16 3"
>
<path d="M2 0a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3Zm6.041 0a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM14 0a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3Z" />
</svg>
</button>
<!-- Dropdown menu -->
<div
id={"dropdown#{@author.id}"}
class="z-10 hidden text-base list-none bg-white divide-y divide-gray-100 rounded-lg shadow-sm w-44 dark:bg-gray-700"
>
<ul class="py-2" aria-labelledby="dropdownButton">
<li>
<.link
navigate={~p"/authors/#{@author.id}/edit"}
class="flex items-center block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-200 dark:hover:text-white"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4 mr-2 -ml-0.5"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path d="M17.414 2.586a2 2 0 00-2.828 0L7 10.172V13h2.828l7.586-7.586a2 2 0 000-2.828z">
</path>
<path
fill-rule="evenodd"
d="M2 6a2 2 0 012-2h4a1 1 0 010 2H4v10h10v-4a1 1 0 112 0v4a2 2 0 01-2 2H4a2 2 0 01-2-2V6z"
clip-rule="evenodd"
>
</path>
</svg>
Edit
</.link>
</li>
</ul>
</div>
</div>
<% end %>
<div class="flex flex-col items-center py-5 text-center">
<.link navigate={~p"/authors/#{@author.id}"}>
<%= if @author.avatar_url != nil do %>
<img
class="w-36 h-36 mb-3 rounded-full shadow-lg"
src={@author.avatar_url}
alt={"#{@author.name} image"}
/>
<% else %>
<div class="relative w-36 h-36 overflow-hidden bg-gray-100 rounded-full dark:bg-gray-600">
<svg
class="absolute w-36 h-36 text-gray-400"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"
clip-rule="evenodd"
>
</path>
</svg>
</div>
<% end %>
</.link>
<.link navigate={~p"/authors/#{@author.id}"}>
<h5 class="mb-1 text-xl font-medium text-gray-900 dark:text-white">{@author.name}</h5>
</.link>
<span class="text-sm text-gray-500 dark:text-gray-400">{@author.brief_description}</span>
</div>
</div>
"""
end
end

@ -0,0 +1,99 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.BookCard do
use Phoenix.Component
use DecentralisedBookIndexWeb, :verified_routes
alias DecentralisedBookIndex.Accounts.Role
attr(:book, :map, required: true)
attr :current_user, :map, default: nil
def book_card(assigns) do
~H"""
<div class="w-full max-w-sm bg-white border border-gray-200 rounded-lg shadow-sm dark:bg-gray-800 dark:border-gray-700 mx-auto my-3">
<%= if @current_user != nil and Role.can_moderate?(@current_user.role) and is_nil(@book.dbi_server) do %>
<div class="flex justify-end px-4 pt-4">
<button
id={"dropdownButton#{@book.id}"}
data-dropdown-toggle={"dropdown#{@book.id}"}
class="inline-block text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 focus:ring-4 focus:outline-none focus:ring-gray-200 dark:focus:ring-gray-700 rounded-lg text-sm p-1.5"
type="button"
>
<span class="sr-only">Open dropdown</span>
<svg
class="w-5 h-5"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
fill="currentColor"
viewBox="0 0 16 3"
>
<path d="M2 0a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3Zm6.041 0a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3ZM14 0a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3Z" />
</svg>
</button>
<!-- Dropdown menu -->
<div
id={"dropdown#{@book.id}"}
class="z-10 hidden text-base list-none bg-white divide-y divide-gray-100 rounded-lg shadow-sm w-44 dark:bg-gray-700"
>
<ul class="py-2" aria-labelledby="dropdownButton">
<li>
<.link
navigate={~p"/books/#{@book.id}/edit"}
class="flex items-center block px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 dark:hover:bg-gray-600 dark:text-gray-200 dark:hover:text-white"
>
<svg
xmlns="http://www.w3.org/2000/svg"
class="h-4 w-4 mr-2 -ml-0.5"
viewBox="0 0 20 20"
fill="currentColor"
aria-hidden="true"
>
<path d="M17.414 2.586a2 2 0 00-2.828 0L7 10.172V13h2.828l7.586-7.586a2 2 0 000-2.828z">
</path>
<path
fill-rule="evenodd"
d="M2 6a2 2 0 012-2h4a1 1 0 010 2H4v10h10v-4a1 1 0 112 0v4a2 2 0 01-2 2H4a2 2 0 01-2-2V6z"
clip-rule="evenodd"
>
</path>
</svg>
Edit
</.link>
</li>
</ul>
</div>
</div>
<% end %>
<div class="flex flex-col items-center py-5 text-center">
<.link navigate={~p"/books/#{@book.id}"}>
<%= if @book.cover_image_url != nil do %>
<img class="w-36 mb-3 shadow-lg" src={@book.cover_image_url} alt={"#{@book.title} image"} />
<% else %>
<div class="relative w-36 h-36 overflow-hidden">
<svg
class="w-36 h-36 text-gray-800 dark:text-white"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="currentColor"
viewBox="0 0 24 24"
>
<path
fill-rule="evenodd"
d="M6 2a2 2 0 0 0-2 2v15a3 3 0 0 0 3 3h12a1 1 0 1 0 0-2h-2v-2h2a1 1 0 0 0 1-1V4a2 2 0 0 0-2-2h-8v16h5v2H7a1 1 0 1 1 0-2h1V2H6Z"
clip-rule="evenodd"
/>
</svg>
</div>
<% end %>
</.link>
<.link navigate={~p"/books/#{@book.id}"}>
<h5 class="mb-1 text-xl font-medium text-gray-900 dark:text-white">{@book.title}</h5>
</.link>
<span class="text-sm text-gray-500 dark:text-gray-400">{@book.brief_description}</span>
</div>
</div>
"""
end
end

@ -0,0 +1,99 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.BookSearch do
use Phoenix.Component
use DecentralisedBookIndexWeb, :verified_routes
alias DecentralisedBookIndex.Accounts.Role
attr :search_query, :string, default: ""
attr :search_mode, :string, default: "title"
attr :search_mode_options, :list, required: true
attr :select_options, :list, required: true
attr :selected_option, :string, required: true
attr :current_user, :map, default: nil
def book_search(assigns) do
~H"""
<div class="bg-white shadow-md dark:bg-gray-800 sm:rounded-lg">
<div class="flex items-center justify-center p-4 flex-row space-y-0 space-x-4">
<div class="w-full grow">
<form class="flex items-center" phx-change="search" phx-submit="search">
<label for="simple-search" class="sr-only">Search</label>
<div class="relative w-full">
<div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
<svg aria-hidden="true" class="w-5 h-5 text-gray-500 dark:text-gray-400" fill="currentColor" viewbox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
</svg>
</div>
<input name="query" type="text" phx-debounce="300" autocomplete="off" id="simple-search" class="block w-full p-2 pl-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder="Search" value={@search_query}>
</div>
</form>
</div>
<%= if @current_user != nil and Role.can_moderate?(@current_user.role) do %>
<.link patch={~p"/books/new"} class="flex-shrink-0 my-auto">
<button type="button" class="flex items-center justify-between px-4 py-2 text-sm font-medium text-black dark:text-white rounded-lg bg-primary-700 hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 dark:bg-primary-600 dark:hover:bg-primary-700 focus:outline-none dark:focus:ring-primary-800">
<svg class="h-3.5 w-3.5 mr-2" fill="currentColor" viewbox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path clip-rule="evenodd" fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" />
</svg>
Add book
</button>
</.link>
<% end %>
<.dropdown_settings
search_mode={@search_mode}
search_mode_options={@search_mode_options}
select_options={@select_options}
selected_option={@selected_option}
/>
</div>
</div>
"""
end
attr :search_mode, :string, default: "title"
attr :search_mode_options, :list, required: true
attr :select_options, :list, required: true
attr :selected_option, :string, required: true
def dropdown_settings(assigns) do
~H"""
<div class="flex justify-end px-4">
<button id="dropdownButtonSearchBook" data-dropdown-toggle="dropdownSearchBook" class="inline-block text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 focus:ring-4 focus:outline-none focus:ring-gray-200 dark:focus:ring-gray-700 rounded-lg text-sm p-1.5" type="button">
<span class="sr-only">Open dropdown</span>
<svg class="w-5 h-5 text-gray-800 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linecap="round" stroke-width="2" d="M20 6H10m0 0a2 2 0 1 0-4 0m4 0a2 2 0 1 1-4 0m0 0H4m16 6h-2m0 0a2 2 0 1 0-4 0m4 0a2 2 0 1 1-4 0m0 0H4m16 6H10m0 0a2 2 0 1 0-4 0m4 0a2 2 0 1 1-4 0m0 0H4"/>
</svg>
</button>
<!-- Dropdown menu -->
<div id="dropdownSearchBook" class="z-10 hidden text-base list-none bg-white rounded-lg shadow-sm w-64 dark:bg-gray-700 p-2 flex flex-col gap-2">
<div class="flex items-center space-x-3 md:w-auto">
<form phx-change="change-search-mode" class="w-full">
<select name="search_mode" id="search_mode" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500">
<%= for {name, value} <- @search_mode_options do %>
<%= if value == @search_mode do %>
<option value={value} selected>{name}</option>
<% else %>
<option value={value}>{name}</option>
<% end %>
<% end %>
</select>
</form>
</div>
<div class="flex items-center space-x-3 md:w-auto">
<form phx-change="change-sort" class="w-full">
<select name="sort_by" id="sort_by" class="bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500">
<%= for {name, value} <- @select_options do %>
<%= if value == @selected_option do %>
<option value={value} selected>{name}</option>
<% else %>
<option value={value}>{name}</option>
<% end %>
<% end %>
</select>
</form>
</div>
</div>
</div>
"""
end
end

@ -0,0 +1,184 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.Buttons do
use Phoenix.Component
import DecentralisedBookIndexWeb.CoreComponents
@doc """
Renders a success button.
## Examples
<.success_button>Send!</.success_button>
<.success_button phx-click="go" class="ml-2">Send!</.success_button>
"""
attr :type, :string, default: nil
attr :class, :string, default: nil
attr :rest, :global, include: ~w(disabled form name value)
slot :inner_block, required: true
def success_button(assigns) do
~H"""
<button
type={@type}
class={[
"phx-submit-loading:opacity-75 rounded-lg py-2 px-3 focus:outline-none text-white bg-green-700 hover:bg-green-800 focus:ring-4 focus:ring-green-300 font-medium rounded-lg text-sm px-5 py-2.5 me-2 mb-2 dark:bg-green-600 dark:hover:bg-green-700 dark:focus:ring-green-800",
"text-sm font-semibold leading-6 text-white active:text-white/80",
@class
]}
{@rest}
>
{render_slot(@inner_block)}
</button>
"""
end
@doc """
Renders a primary button.
## Examples
<.primary_button>Send!</.primary_button>
<.primary_button phx-click="go" class="ml-2">Send!</.primary_button>
"""
attr :type, :string, default: nil
attr :class, :string, default: nil
attr :rest, :global, include: ~w(disabled form name value)
slot :inner_block, required: true
def primary_button(assigns) do
~H"""
<button
type={@type}
class={[
"phx-submit-loading:opacity-75 rounded-lg py-2 px-3 text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 mb-2 bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-blue-800",
"text-sm font-semibold leading-6 text-white active:text-white/80",
@class
]}
{@rest}
>
{render_slot(@inner_block)}
</button>
"""
end
attr :type, :string, default: nil
attr :class, :string, default: nil
attr :rest, :global, include: ~w(disabled form name value)
slot :inner_block, required: true
def add_button_link(assigns) do
~H"""
<.link
class={[
"phx-submit-loading:opacity-75 rounded-lg py-2 px-3 text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 mb-2 bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-blue-800",
"text-sm font-semibold leading-6 text-white active:text-white/80",
"flex items-center gap-1",
@class
]}
{@rest}
>
<svg
class="w-6 h-6 text-white dark:text-white"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="none"
viewBox="0 0 24 24"
>
<path
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M5 12h14m-7 7V5"
/>
</svg>
{render_slot(@inner_block)}
</.link>
"""
end
attr :type, :string, default: nil
attr :class, :string, default: nil
attr :rest, :global, include: ~w(disabled form name value)
slot :inner_block, required: true
def save_button(assigns) do
~H"""
<.success_button
type={@type}
class={[
"phx-submit-loading:opacity-75 rounded-lg py-2 px-3 text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 mb-2 bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-blue-800",
"text-sm font-semibold leading-6 text-white active:text-white/80",
"flex items-center gap-1",
@class
]}
{@rest}
>
<svg class="w-6 h-6 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M5 3a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V7.414A2 2 0 0 0 20.414 6L18 3.586A2 2 0 0 0 16.586 3H5Zm3 11a1 1 0 0 1 1-1h6a1 1 0 0 1 1 1v6H8v-6Zm1-7V5h6v2a1 1 0 0 1-1 1h-4a1 1 0 0 1-1-1Z" clip-rule="evenodd"/>
<path fill-rule="evenodd" d="M14 17h-4v-2h4v2Z" clip-rule="evenodd"/>
</svg>
{render_slot(@inner_block)}
</.success_button>
"""
end
attr :type, :string, default: nil
attr :class, :string, default: nil
attr :rest, :global, include: ~w(disabled form name value)
slot :inner_block, required: true
def edit_button(assigns) do
~H"""
<.primary_button
type={@type}
class={[
"phx-submit-loading:opacity-75 rounded-lg py-2 px-3 text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 mb-2 bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-blue-800",
"text-sm font-semibold leading-6 text-white active:text-white/80",
"flex items-center gap-1",
@class
]}
{@rest}
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-2 -ml-0.5" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path d="M17.414 2.586a2 2 0 00-2.828 0L7 10.172V13h2.828l7.586-7.586a2 2 0 000-2.828z"></path>
<path fill-rule="evenodd" d="M2 6a2 2 0 012-2h4a1 1 0 010 2H4v10h10v-4a1 1 0 112 0v4a2 2 0 01-2 2H4a2 2 0 01-2-2V6z" clip-rule="evenodd"></path>
</svg>
{render_slot(@inner_block)}
</.primary_button>
"""
end
attr :type, :string, default: nil
attr :class, :string, default: nil
attr :rest, :global, include: ~w(disabled form name value)
slot :inner_block, required: true
def cancel_button(assigns) do
~H"""
<.primary_button
type={@type}
class={[
"phx-submit-loading:opacity-75 rounded-lg py-2 px-3 text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 mb-2 bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-blue-800",
"text-sm font-semibold leading-6 text-white active:text-white/80",
"flex items-center gap-1",
@class
]}
{@rest}
>
<svg class="w-6 h-6 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18 17.94 6M18 18 6.06 6"/>
</svg>
{render_slot(@inner_block)}
</.primary_button>
"""
end
end

@ -0,0 +1,48 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.JustSearchResources do
use Phoenix.Component
use DecentralisedBookIndexWeb, :verified_routes
attr :search_query, :string, default: ""
attr :select_options, :list, required: true
attr :selected_option, :string, required: true
attr :current_user, :map, default: nil
attr :search_placeholder, :string, default: "Search by name"
def just_search_resources(assigns) do
~H"""
<div class="relative bg-white shadow-md dark:bg-gray-800 sm:rounded-lg">
<div class="flex flex-col items-center justify-between p-4 space-y-3 md:flex-row md:space-y-0 md:space-x-4">
<div class="w-full grow">
<form class="flex items-center" phx-change="search" phx-submit="search">
<label for="simple-search" class="sr-only">Search</label>
<div class="relative w-full">
<div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
<svg aria-hidden="true" class="w-5 h-5 text-gray-500 dark:text-gray-400" fill="currentColor" viewbox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
</svg>
</div>
<input name="query" type="text" phx-debounce="300" autocomplete="off" id="simple-search" class="block w-full p-2 pl-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder={@search_placeholder} value={@search_query}>
</div>
</form>
</div>
<div class="flex flex-col items-stretch justify-end flex-shrink-0 w-full space-y-2 md:w-auto md:flex-row md:space-y-0 md:items-center md:space-x-3">
<div class="flex items-center w-full space-x-3 md:w-auto">
<form phx-change="change-sort" class="w-full">
<select name="sort_by" id="sort_by" class="grow bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500">
<%= for {name, value} <- @select_options do %>
<%= if value == @selected_option do %>
<option value={value} selected>{name}</option>
<% else %>
<option value={value}>{name}</option>
<% end %>
<% end %>
</select>
</form>
</div>
</div>
</div>
</div>
"""
end
end

@ -0,0 +1,135 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.Pagination do
use Phoenix.Component
use DecentralisedBookIndexWeb, :verified_routes
attr :endpoint, :string, required: true
attr :page, :map, required: true
attr :page_params, :list, required: true
attr :params, :list, required: true
def pagination(assigns) do
assigns = assign(assigns, :current_page_number, get_current_page(assigns.page))
~H"""
<%= if AshPhoenix.LiveView.prev_page?(@page) or AshPhoenix.LiveView.next_page?(@page) do %>
<nav aria-label="Page navigation example" class="flex justify-center">
<ul class="inline-flex -space-x-px text-base h-10 mx-auto">
<li class="pl-auto">
<.button_link
data-role="previous-page"
kind="primary"
inverse
patch={"#{@endpoint}?#{page_params_which(@page, @params, "prev")}"}
class="flex items-center justify-center px-4 h-10 ms-0 leading-tight text-gray-500 bg-white border border-e-0 border-gray-300 rounded-s-lg hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
disabled={!AshPhoenix.LiveView.prev_page?(@page)}
>
Previous
</.button_link>
</li>
<%= for number <- get_page_numbers(@page) do %>
<%= if number == @current_page_number do %>
<li>
<a
href={"#{@endpoint}?#{page_params_number(@page_params, @params, number)}"}
aria-current="page"
class="flex items-center justify-center px-4 h-10 text-blue-600 border border-gray-300 bg-blue-50 hover:bg-blue-100 hover:text-blue-700 dark:border-gray-700 dark:bg-gray-700 dark:text-white"
>
{number}
</a>
</li>
<% else %>
<li>
<a
href={"#{@endpoint}?#{page_params_number(@page_params, @params, number)}"}
class="flex items-center justify-center px-4 h-10 leading-tight text-gray-500 bg-white border border-gray-300 hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
>
{number}
</a>
</li>
<% end %>
<% end %>
<li>
<.button_link
data-role="next-page"
kind="primary"
inverse
patch={"#{@endpoint}?#{page_params_which(@page, @params, "next")}"}
class="flex items-center justify-center px-4 h-10 leading-tight text-gray-500 bg-white border border-gray-300 rounded-e-lg hover:bg-gray-100 hover:text-gray-700 dark:bg-gray-800 dark:border-gray-700 dark:text-gray-400 dark:hover:bg-gray-700 dark:hover:text-white"
disabled={!AshPhoenix.LiveView.next_page?(@page)}
>
Next
</.button_link>
</li>
</ul>
</nav>
<% end %>
"""
end
attr :kind, :string,
values: ~w(base primary error),
default: "base"
attr :inverse, :boolean, default: false
attr :class, :string, default: ""
attr :rest, :global, include: ~w(navigate disabled patch)
slot :inner_block
defp button_link(assigns) do
~H"""
<.link
class={[
@rest[:disabled] && "opacity-80 pointer-events-none",
@class
]}
{@rest}
>
{render_slot(@inner_block)}
</.link>
"""
end
defp get_page_numbers(pages) do
%{count: count, limit: limit} = pages
max_number =
(count / limit)
|> :math.ceil()
|> Kernel.trunc()
1..max_number
end
defp get_current_page(pages) do
%{offset: offset, limit: limit} = pages
Kernel.trunc(offset / limit) + 1
end
def page_params_which(page, params, which) do
page_params =
case AshPhoenix.LiveView.page_link_params(page, which) do
:invalid -> []
list -> list
end
page_params
|> Enum.into(params, fn {k, v} -> {Atom.to_string(k), v} end)
|> to_uri_params()
end
def page_params_number(page_params, params, number) do
limit = Keyword.get(page_params, :limit)
offset = limit * (number - 1)
params
|> Map.put("limit", limit)
|> Map.put("offset", offset)
|> to_uri_params()
end
defp to_uri_params(params) do
URI.encode_query(params)
end
end

@ -0,0 +1,72 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.SearchResources do
use Phoenix.Component
use DecentralisedBookIndexWeb, :verified_routes
alias DecentralisedBookIndex.Accounts.Role
attr :search_query, :string, default: ""
attr :select_options, :list, required: true
attr :selected_option, :string, required: true
attr :current_user, :map, default: nil
attr :resource_type, :string, required: true
attr :resource_new_url, :string, required: true
attr :search_placeholder, :string, default: "Search by name"
attr :moderator_role, :atom, default: :moderator
def search_resources(assigns) do
~H"""
<div class="relative bg-white shadow-md dark:bg-gray-800 sm:rounded-lg">
<div class="flex flex-col items-center justify-between p-4 space-y-3 md:flex-row md:space-y-0 md:space-x-4">
<div class="w-full grow">
<form class="flex items-center" phx-change="search" phx-submit="search">
<label for="simple-search" class="sr-only">Search</label>
<div class="relative w-full">
<div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
<svg aria-hidden="true" class="w-5 h-5 text-gray-500 dark:text-gray-400" fill="currentColor" viewbox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd" />
</svg>
</div>
<input name="query" type="text" phx-debounce="300" autocomplete="off" id="simple-search" class="block w-full p-2 pl-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder={@search_placeholder} value={@search_query}>
</div>
</form>
</div>
<div class="flex flex-col items-stretch justify-end flex-shrink-0 w-full space-y-2 md:w-auto md:flex-row md:space-y-0 md:items-center md:space-x-3">
<%= if can_add?(@current_user, @moderator_role) do %>
<.link patch={@resource_new_url}>
<button type="button" class="grow w-full flex items-center justify-left px-4 py-2 text-sm font-medium text-black dark:text-white rounded-lg bg-primary-700 hover:bg-primary-800 focus:ring-4 focus:ring-primary-300 dark:bg-primary-600 dark:hover:bg-primary-700 focus:outline-none dark:focus:ring-primary-800">
<svg class="h-3.5 w-3.5 mr-2" fill="currentColor" viewbox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
<path clip-rule="evenodd" fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" />
</svg>
Add {@resource_type}
</button>
</.link>
<% end %>
<div class="flex items-center w-full space-x-3 md:w-auto">
<form phx-change="change-sort" class="w-full">
<select name="sort_by" id="sort_by" class="grow bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500">
<%= for {name, value} <- @select_options do %>
<%= if value == @selected_option do %>
<option value={value} selected>{name}</option>
<% else %>
<option value={value}>{name}</option>
<% end %>
<% end %>
</select>
</form>
</div>
</div>
</div>
</div>
"""
end
defp can_add?(current_user, role) do
case role do
:admin -> current_user != nil and Role.can_administrate?(current_user.role)
:moderator -> current_user != nil and Role.can_moderate?(current_user.role)
_ -> false
end
end
end

@ -0,0 +1,57 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.SelectAuthor do
use DecentralisedBookIndexWeb, :live_component
alias DecentralisedBookIndex.Metadata
@impl true
def render(assigns) do
~H"""
<div>
<.header>
Select Author
</.header>
<form class="flex items-center" phx-change="search" phx-target={@myself}>
<label for="simple-search" class="sr-only">Search</label>
<div class="relative w-full">
<div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
<svg aria-hidden="true" class="w-5 h-5 text-gray-500 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd"></path>
</svg>
</div>
<input name="query" type="text" phx-debounce="300" autocomplete="off" id="simple-search" class="block w-full p-2 pl-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder="Search" value="">
</div>
</form>
<%= for author <- @page.results do %>
<div phx-click="select-author" phx-target={@notify_component} phx-value-author={author.id} phx-value-path={@form_path} class="w-full bg-white border border-gray-200 rounded-lg shadow-sm dark:bg-gray-800 dark:border-gray-700 mx-auto my-3">
<h5 class="mb-1 text-lg font-medium text-gray-900 dark:text-white px-2 pt-1">{author.name}</h5>
</div>
<% end %>
</div>
"""
end
@impl true
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign(:author_query, "")
|> search()}
end
def handle_event("search", %{"query" => query}, socket) do
{:noreply,
socket
|> assign(:author_query, query)
|> search()}
end
defp search(socket) do
query = Map.get(socket.assigns, :author_query, "")
page = Metadata.search_author!(query)
socket
|> assign(page: page)
end
end

@ -0,0 +1,84 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.SelectAuthorAlias do
use DecentralisedBookIndexWeb, :live_component
alias DecentralisedBookIndex.Metadata
@impl true
def render(assigns) do
~H"""
<div>
<.header>
Select another alias of the author
</.header>
<form class="flex items-center" phx-change="search" phx-target={@myself}>
<label for="simple-search" class="sr-only">Search</label>
<div class="relative w-full">
<div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
<svg
aria-hidden="true"
class="w-5 h-5 text-gray-500 dark:text-gray-400"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z"
clip-rule="evenodd"
>
</path>
</svg>
</div>
<input
name="query"
type="text"
phx-debounce="300"
autocomplete="off"
id="simple-search"
class="block w-full p-2 pl-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500"
placeholder="Search"
value=""
/>
</div>
</form>
<%= for author_alias <- @page.results do %>
<div
phx-click="select-author-alias"
phx-target={@notify_component}
phx-value-author-alias={author_alias.author_alias_registry_id}
class="w-full bg-white border border-gray-200 rounded-lg shadow-sm dark:bg-gray-800 dark:border-gray-700 mx-auto my-3"
>
<h5 class="mb-1 text-lg font-medium text-gray-900 dark:text-white px-2 pt-1">
{author_alias.name}
</h5>
</div>
<% end %>
</div>
"""
end
@impl true
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign(:author_alias_query, "")
|> search()}
end
def handle_event("search", %{"query" => query}, socket) do
{:noreply,
socket
|> assign(:author_alias_query, query)
|> search()}
end
defp search(socket) do
query = Map.get(socket.assigns, :author_alias_query, "")
page = Metadata.search_author!(query)
socket
|> assign(page: page)
end
end

@ -0,0 +1,84 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.SelectBookEdition do
use DecentralisedBookIndexWeb, :live_component
alias DecentralisedBookIndex.Metadata
@impl true
def render(assigns) do
~H"""
<div>
<.header>
Select another edition of the book
</.header>
<form class="flex items-center" phx-change="search" phx-target={@myself}>
<label for="simple-search" class="sr-only">Search</label>
<div class="relative w-full">
<div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
<svg
aria-hidden="true"
class="w-5 h-5 text-gray-500 dark:text-gray-400"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z"
clip-rule="evenodd"
>
</path>
</svg>
</div>
<input
name="query"
type="text"
phx-debounce="300"
autocomplete="off"
id="simple-search"
class="block w-full p-2 pl-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500"
placeholder="Search"
value=""
/>
</div>
</form>
<%= for book_edition <- @page.results do %>
<div
phx-click="select-book-edition"
phx-target={@notify_component}
phx-value-book-edition={book_edition.book_editions_registry_id}
class="w-full bg-white border border-gray-200 rounded-lg shadow-sm dark:bg-gray-800 dark:border-gray-700 mx-auto my-3"
>
<h5 class="mb-1 text-lg font-medium text-gray-900 dark:text-white px-2 pt-1">
{book_edition.title}
</h5>
</div>
<% end %>
</div>
"""
end
@impl true
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign(:book_edition_query, "")
|> search()}
end
def handle_event("search", %{"query" => query}, socket) do
{:noreply,
socket
|> assign(:book_edition_query, query)
|> search()}
end
defp search(socket) do
query = Map.get(socket.assigns, :book_edition_query, "")
page = Metadata.search_book!(query)
socket
|> assign(page: page)
end
end

@ -0,0 +1,57 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.SelectPublisher do
use DecentralisedBookIndexWeb, :live_component
alias DecentralisedBookIndex.Metadata
@impl true
def render(assigns) do
~H"""
<div>
<.header>
Select Publisher
</.header>
<form class="flex items-center" phx-change="search" phx-target={@myself}>
<label for="simple-search" class="sr-only">Search</label>
<div class="relative w-full">
<div class="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none">
<svg aria-hidden="true" class="w-5 h-5 text-gray-500 dark:text-gray-400" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M8 4a4 4 0 100 8 4 4 0 000-8zM2 8a6 6 0 1110.89 3.476l4.817 4.817a1 1 0 01-1.414 1.414l-4.816-4.816A6 6 0 012 8z" clip-rule="evenodd"></path>
</svg>
</div>
<input name="query" type="text" phx-debounce="300" autocomplete="off" id="simple-search" class="block w-full p-2 pl-10 text-sm text-gray-900 border border-gray-300 rounded-lg bg-gray-50 focus:ring-primary-500 focus:border-primary-500 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500" placeholder="Search" value="">
</div>
</form>
<%= for publisher <- @page.results do %>
<div phx-click="select-publisher" phx-target={@notify_component} phx-value-publisher={publisher.id} class="w-full bg-white border border-gray-200 rounded-lg shadow-sm dark:bg-gray-800 dark:border-gray-700 mx-auto my-3">
<h5 class="mb-1 text-lg font-medium text-gray-900 dark:text-white px-2 pt-1">{publisher.name}</h5>
</div>
<% end %>
</div>
"""
end
@impl true
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign(:publisher_query, "")
|> search()}
end
def handle_event("search", %{"query" => query}, socket) do
{:noreply,
socket
|> assign(:publisher_query, query)
|> search()}
end
defp search(socket) do
query = Map.get(socket.assigns, :publisher_query, "")
page = Metadata.search_publisher!(query)
socket
|> assign(page: page)
end
end

@ -0,0 +1,47 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.SelectedAuthor do
use Phoenix.Component
use DecentralisedBookIndexWeb, :verified_routes
alias DecentralisedBookIndexWeb.CoreComponents
attr :author_form, :map, default: nil
attr :form_path, :string, default: ""
attr :class, :string, default: ""
def selected_author(assigns) do
author_id = assigns.author_form.value
author =
if author_id == nil do
author_id
else
DecentralisedBookIndex.Metadata.get_author_by_id!(author_id)
end
errors =
if Phoenix.Component.used_input?(assigns.author_form), do: assigns.author_form.errors, else: []
assigns =
assigns
|> assign(:author, author)
|> assign(:errors, Enum.map(errors, &CoreComponents.translate_error(&1)))
~H"""
<button
type="button"
phx-click="open-select-author"
phx-target={@notify_component}
phx-value-path={@form_path}
class={"text-white bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300 font-medium rounded-full text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800 #{@class}"}
>
<%= if @author != nil do %>
{@author.name}
<% else %>
Select an author
<% end %>
</button>
<CoreComponents.error :for={msg <- @errors}>{msg}</CoreComponents.error>
"""
end
end

@ -0,0 +1,19 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.SelectedAuthorAlias do
use Phoenix.Component
use DecentralisedBookIndexWeb, :verified_routes
attr :author_alias_registry_form, :map, default: nil
def selected_author_alias(assigns) do
~H"""
<button
type="button"
phx-click="open-select-author-alias"
phx-target={@notify_component}
class={"text-white bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300 font-medium rounded-full text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"}
>
Change the author alias
</button>
"""
end
end

@ -0,0 +1,19 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.SelectedBookEdition do
use Phoenix.Component
use DecentralisedBookIndexWeb, :verified_routes
attr :book_editions_registry_form, :map, default: nil
def selected_book_edition(assigns) do
~H"""
<button
type="button"
phx-click="open-select-book-edition"
phx-target={@notify_component}
class={"text-white bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300 font-medium rounded-full text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"}
>
Change the book edition
</button>
"""
end
end

@ -0,0 +1,44 @@
defmodule DecentralisedBookIndexWeb.Components.MyComponents.SelectedPublisher do
use Phoenix.Component
use DecentralisedBookIndexWeb, :verified_routes
alias DecentralisedBookIndexWeb.CoreComponents
attr :publisher_form, :map, default: nil
def selected_publisher(assigns) do
publisher_id = assigns.publisher_form.value
publisher =
if publisher_id == nil do
publisher_id
else
DecentralisedBookIndex.Metadata.get_publisher_by_id!(publisher_id)
end
errors =
if Phoenix.Component.used_input?(assigns.publisher_form), do: assigns.publisher_form.errors, else: []
assigns =
assigns
|> assign(:publisher, publisher)
|> assign(:errors, Enum.map(errors, &CoreComponents.translate_error(&1)))
~H"""
<button
type="button"
phx-click="open-select-publisher"
phx-target={@notify_component}
class="text-white bg-blue-700 hover:bg-blue-800 focus:outline-none focus:ring-4 focus:ring-blue-300 font-medium rounded-full text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800"
>
<%= if @publisher != nil do %>
{@publisher.name}
<% else %>
Select a publisher
<% end %>
</button>
<CoreComponents.error :for={msg <- @errors}>{msg}</CoreComponents.error>
"""
end
end

@ -0,0 +1,10 @@
defmodule DecentralisedBookIndexWeb.Components.MyPartials do
alias DecentralisedBookIndexWeb.Components.MyPartials
defmacro __using__(_) do
quote do
import MyPartials.Navbar, only: [partial_navbar: 1]
import MyPartials.Footer, only: [partial_footer: 1]
end
end
end

@ -0,0 +1,27 @@
defmodule DecentralisedBookIndexWeb.Components.MyPartials.Footer do
use Phoenix.Component
def partial_footer(assigns) do
~H"""
<footer class="bg-white shadow-sm dark:bg-gray-900">
<div class="w-full max-w-screen-xl mx-auto p-4 md:py-8">
<hr class="my-6 border-gray-200 sm:mx-auto dark:border-gray-700 lg:my-8" />
<span class="block text-sm text-gray-500 text-center dark:text-gray-400">
© 2025 Kostiantyn Klochko. All Rights Reserved.
</span>
<span class="block text-sm text-gray-500 text-center dark:text-gray-400">
<a href="https://git.kklochko.space/KKlochko/decentralised_book_index">Decentralised book index</a> is free software: you can redistribute it and/or modify it under the terms of <a href="https://www.gnu.org/licenses/agpl-3.0.en.html">the GNU Affero General Public License</a> as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
</span>
</div>
</footer>
"""
end
def selected_navbar_link_css(page_title, active_title) do
if active_title =~ page_title do
"block py-2 pr-4 pl-3 text-black dark:text-white rounded bg-primary-700 lg:bg-transparent lg:text-primary-700 lg:p-0 dark:text-white"
else
"block py-2 pr-4 pl-3 text-gray-700 border-b border-gray-100 hover:bg-gray-50 lg:hover:bg-transparent lg:border-0 lg:hover:text-primary-700 lg:p-0 dark:text-gray-400 lg:dark:hover:text-white dark:hover:bg-gray-700 dark:hover:text-white lg:dark:hover:bg-transparent dark:border-gray-700"
end
end
end

@ -0,0 +1,188 @@
defmodule DecentralisedBookIndexWeb.Components.MyPartials.Navbar do
use Phoenix.Component
use DecentralisedBookIndexWeb, :verified_routes
import DecentralisedBookIndexWeb.Components.MyComponents.Buttons
alias Phoenix.LiveView.JS
alias DecentralisedBookIndex.Accounts.Role
attr :page_title, :string, required: true
attr :current_user, :map, default: nil
def partial_navbar(assigns) do
~H"""
<nav class="bg-white border-gray-200 px-4 lg:px-6 py-2.5 dark:bg-gray-800">
<div class="flex flex-wrap justify-between items-center mx-auto max-w-screen-xl">
<.link patch={~p"/books"} class="flex items-center">
<svg
class="w-6 h-6 text-gray-800 dark:text-white"
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="none"
viewBox="0 0 24 24"
>
<path
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M12 6.03v13m0-13c-2.819-.831-4.715-1.076-8.029-1.023A.99.99 0 0 0 3 6v11c0 .563.466 1.014 1.03 1.007 3.122-.043 5.018.212 7.97 1.023m0-13c2.819-.831 4.715-1.076 8.029-1.023A.99.99 0 0 1 21 6v11c0 .563-.466 1.014-1.03 1.007-3.122-.043-5.018.212-7.97 1.023"
/>
</svg>
<span class="self-center text-xl font-semibold whitespace-nowrap dark:text-white">DBI</span>
</.link>
<div class="flex items-center lg:order-2">
<.user_info current_user={@current_user} />
<button
data-collapse-toggle="mobile-menu-2"
type="button"
class="inline-flex items-center p-2 ml-1 text-sm text-gray-500 rounded-lg lg:hidden hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:text-gray-400 dark:hover:bg-gray-700 dark:focus:ring-gray-600"
aria-controls="mobile-menu-2"
aria-expanded="false"
>
<span class="sr-only">Open main menu</span>
<svg
class="w-6 h-6"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
d="M3 5a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 10a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM3 15a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1z"
clip-rule="evenodd"
>
</path>
</svg>
<svg
class="hidden w-6 h-6"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z"
clip-rule="evenodd"
>
</path>
</svg>
</button>
</div>
<div
class="hidden justify-between items-center w-full lg:flex lg:w-auto lg:order-1"
id="mobile-menu-2"
>
<ul class="flex flex-col mt-4 font-medium lg:flex-row lg:space-x-8 lg:mt-0">
<li>
<a
href={~p"/books/"}
class={selected_navbar_link_css(@page_title, "Listing Books")}
aria-current="page"
>
Books
</a>
</li>
<li>
<a
href={~p"/authors/"}
class={selected_navbar_link_css(@page_title, "Listing Authors")}
aria-current="page"
>
Authors
</a>
</li>
<%= if @current_user != nil and Role.can_moderate?(@current_user.role) do %>
<li>
<a
href={~p"/publishers/"}
class={selected_navbar_link_css(@page_title, "Listing Publishers")}
aria-current="page"
>
Publishers
</a>
</li>
<% end %>
<%= if @current_user != nil and Role.can_moderate?(@current_user.role) do %>
<li>
<a
href={~p"/servers/"}
class={selected_navbar_link_css(@page_title, "Listing Server")}
aria-current="page"
>
Servers
</a>
</li>
<% end %>
<%= if @current_user != nil and Role.can_administrate?(@current_user.role) do %>
<li>
<a
href={~p"/users/"}
class={selected_navbar_link_css(@page_title, "Listing Users")}
aria-current="page"
>
Users
</a>
</li>
<% end %>
</ul>
</div>
</div>
</nav>
"""
end
attr :current_user, :map, default: nil
defp user_info(assigns) do
~H"""
<%= if @current_user != nil do %>
<div class="flex justify-end px-4">
<button
id="dropdownButton-user-info"
data-dropdown-toggle="dropdown-user-info"
class="inline-block text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 focus:ring-4 focus:outline-none focus:ring-gray-200 dark:focus:ring-gray-700 rounded-lg text-sm p-1.5"
type="button"
>
<span class="sr-only">Open dropdown</span>
{@current_user.email}
</button>
<!-- Dropdown menu -->
<div
id="dropdown-user-info"
class="z-10 hidden text-base list-none bg-white rounded-lg shadow-sm w-40 dark:bg-gray-700 flex flex-col items-center pt-2 border dark:border-gray-600"
>
<%= if @current_user.role != :user do %>
<p class="text-zinc-700 dark:text-white">
role: {@current_user.role}
</p>
<% end %>
<.link patch={~p"/sign-out"}>
<.primary_button>
Sign Out
</.primary_button>
</.link>
</div>
</div>
<% else %>
<a
href={~p"/sign-in"}
class="text-gray-800 dark:text-white hover:bg-gray-50 focus:ring-4 focus:ring-gray-300 font-medium rounded-lg text-sm px-4 lg:px-5 py-2 lg:py-2.5 mr-2 dark:hover:bg-gray-700 focus:outline-none dark:focus:ring-gray-800"
>
Sign in
</a>
<% end %>
"""
end
defp selected_navbar_link_css(page_title, active_title) do
if active_title =~ page_title do
"block py-2 pr-4 pl-3 text-black dark:text-white rounded bg-primary-700 lg:bg-transparent lg:text-primary-700 lg:p-0 dark:text-white"
else
"block py-2 pr-4 pl-3 text-gray-700 border-gray-100 hover:bg-gray-50 lg:hover:bg-transparent lg:border-0 lg:hover:text-primary-700 lg:p-0 dark:text-gray-400 lg:dark:hover:text-white dark:hover:bg-gray-700 dark:hover:text-white lg:dark:hover:bg-transparent dark:border-gray-700"
end
end
end

@ -13,7 +13,7 @@ defmodule DecentralisedBookIndexWeb.ErrorHTML do
# * lib/decentralised_book_index_web/controllers/error_html/404.html.heex
# * lib/decentralised_book_index_web/controllers/error_html/500.html.heex
#
# embed_templates "error_html/*"
embed_templates "error_html/*"
# The default is to render a plain text page based on
# the template name. For example, "404.html" becomes

@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="en" class="[scrollbar-gutter:stable]">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="csrf-token" content={get_csrf_token()} />
<.live_title default="DecentralisedBookIndex" suffix=" · Page not found">
{assigns[:page_title]}
</.live_title>
<link phx-track-static rel="stylesheet" href={~p"/assets/app.css"} />
<script defer phx-track-static type="text/javascript" src={~p"/assets/app.js"}>
</script>
</head>
<body class="bg-white dark:bg-gray-900 flex flex-col h-screen">
<header>
<.partial_navbar page_title="404" current_user={assigns[:current_user]} />
</header>
<main class="px-4 pt-20 pb-2 sm:px-6 lg:px-8 flex-grow">
<div class="mx-auto max-w-4xl">
<%= if Map.has_key?(assigns, :flash) do %>
<.flash_group flash={@flash} />
<% end %>
<section class="bg-white dark:bg-gray-900">
<div class="py-8 px-4 mx-auto max-w-screen-xl lg:py-16 lg:px-6">
<div class="mx-auto max-w-screen-sm text-center">
<h1 class="mb-4 text-7xl tracking-tight font-extrabold lg:text-9xl text-blue-600 dark:text-blue-500">
404
</h1>
<p class="mb-4 text-3xl tracking-tight font-bold text-gray-900 md:text-4xl dark:text-white">
Something's missing.
</p>
<p class="mb-4 text-lg font-light text-gray-500 dark:text-gray-400">
Sorry, we can't find that page.
</p>
<a
href="/books"
class="inline-flex text-white bg-blue-600 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:focus:ring-blue-900 my-4"
>
Go to books
</a>
</div>
</div>
</section>
</div>
</main>
<.partial_footer />
</body>
</html>

@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="en" class="[scrollbar-gutter:stable]">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="csrf-token" content={get_csrf_token()} />
<.live_title default="DecentralisedBookIndex" suffix=" · Something went wrong">
{assigns[:page_title]}
</.live_title>
<link phx-track-static rel="stylesheet" href={~p"/assets/app.css"} />
<script defer phx-track-static type="text/javascript" src={~p"/assets/app.js"}>
</script>
</head>
<body class="bg-white dark:bg-gray-900 flex flex-col h-screen">
<header>
<.partial_navbar page_title="505" current_user={assigns[:current_user]} />
</header>
<main class="px-4 pt-20 pb-2 sm:px-6 lg:px-8 flex-grow">
<div class="mx-auto max-w-4xl">
<%= if Map.has_key?(assigns, :flash) do %>
<.flash_group flash={@flash} />
<% end %>
<section class="bg-white dark:bg-gray-900">
<div class="py-8 px-4 mx-auto max-w-screen-xl lg:py-16 lg:px-6">
<div class="mx-auto max-w-screen-sm text-center">
<h1 class="mb-4 text-7xl tracking-tight font-extrabold lg:text-9xl text-blue-600 dark:text-blue-500">
500
</h1>
<p class="mb-4 text-3xl tracking-tight font-bold text-gray-900 md:text-4xl dark:text-white">
Something's went wrong.
</p>
<p class="mb-4 text-lg font-light text-gray-500 dark:text-gray-400">
Try to refresh the page. Feel free to contact us if the problem persists.
</p>
<a
href="/books"
class="inline-flex text-white bg-blue-600 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:focus:ring-blue-900 my-4"
>
Go to books
</a>
</div>
</div>
</section>
</div>
</main>
<.partial_footer />
</body>
</html>

@ -1,271 +1,11 @@
<.flash_group flash={@flash} />
<div class="left-[40rem] fixed inset-y-0 right-0 z-0 hidden lg:block xl:left-[50rem]">
<svg
viewBox="0 0 1480 957"
fill="none"
aria-hidden="true"
class="absolute inset-0 h-full w-full"
preserveAspectRatio="xMinYMid slice"
>
<path fill="#EE7868" d="M0 0h1480v957H0z" />
<path
d="M137.542 466.27c-582.851-48.41-988.806-82.127-1608.412 658.2l67.39 810 3083.15-256.51L1535.94-49.622l-98.36 8.183C1269.29 281.468 734.115 515.799 146.47 467.012l-8.928-.742Z"
fill="#FF9F92"
/>
<path
d="M371.028 528.664C-169.369 304.988-545.754 149.198-1361.45 665.565l-182.58 792.025 3014.73 694.98 389.42-1689.25-96.18-22.171C1505.28 697.438 924.153 757.586 379.305 532.09l-8.277-3.426Z"
fill="#FA8372"
/>
<path
d="M359.326 571.714C-104.765 215.795-428.003-32.102-1349.55 255.554l-282.3 1224.596 3047.04 722.01 312.24-1354.467C1411.25 1028.3 834.355 935.995 366.435 577.166l-7.109-5.452Z"
fill="#E96856"
fill-opacity=".6"
/>
<path
d="M1593.87 1236.88c-352.15 92.63-885.498-145.85-1244.602-613.557l-5.455-7.105C-12.347 152.31-260.41-170.8-1225-131.458l-368.63 1599.048 3057.19 704.76 130.31-935.47Z"
fill="#C42652"
fill-opacity=".2"
/>
<path
d="M1411.91 1526.93c-363.79 15.71-834.312-330.6-1085.883-863.909l-3.822-8.102C72.704 125.95-101.074-242.476-1052.01-408.907l-699.85 1484.267 2837.75 1338.01 326.02-886.44Z"
fill="#A41C42"
fill-opacity=".2"
/>
<path
d="M1116.26 1863.69c-355.457-78.98-720.318-535.27-825.287-1115.521l-1.594-8.816C185.286 163.833 112.786-237.016-762.678-643.898L-1822.83 608.665 571.922 2635.55l544.338-771.86Z"
fill="#A41C42"
fill-opacity=".2"
/>
</svg>
<div class="sm:py-28 xl:py-32">
<div class="relative px-8">
<div class="relative space-y-6 bg-black/50 px-6 pt-1 pb-6 rounded-xl">
<span class="flex absolute h-6 w-6 -top-1 -left-2 -mt-1 -mr-1">
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-white">
</span>
<span class="relative inline-flex rounded-full h-6 w-6 bg-white/80"></span>
</span>
<h2 class="text-4xl text-white font-semibold">
Finish your Elixir setup!
</h2>
<p class="text-lg text-gray-300">
Elixir has been installed to
<code class="text-[1rem] px-2 py-1 rounded-md bg-black/50">~/.elixir-install</code>
and activated in your current shell. <br />
<br /> Add to your
<code class="text-[1rem] px-2 py-1 rounded-md bg-black/50">~/.bashrc</code>
or similar to ensure it is always activated:
</p>
<div class="relative text-md text-gray-300 p-2 rounded-md bg-black/50">
<button
class="absolute -right-2 -top-2 p-1 bg-white/70 hover:bg-white rounded-full"
onclick="navigator.clipboard.writeText(document.getElementById('setup-elixir').innerText)"
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
class="size-5 stroke-black/80"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M15.666 3.888A2.25 2.25 0 0 0 13.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 0 1-.75.75H9a.75.75 0 0 1-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 0 1-2.25 2.25H6.75A2.25 2.25 0 0 1 4.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 0 1 1.927-.184"
/>
</svg>
</button>
<code
id="setup-elixir"
class="block px-1 overflow-x-auto whitespace-pre"
phx-no-format
>export PATH=$HOME//nix/store/imkmv8zssyq3nwbr8b3ilj1mg9jikqzy-erlang-25.3.2.12/lib/erlang/erts-13.2.2.9/bin:$PATH
export PATH=$HOME/.nix-profile/bin:$PATH</code>
</div>
</div>
</div>
</div>
</div>
<div class="px-4 py-10 sm:px-6 sm:py-28 lg:px-8 xl:px-28 xl:py-32">
<div class="mx-auto max-w-xl lg:mx-0">
<svg viewBox="0 0 71 48" class="h-12" aria-hidden="true">
<path
d="m26.371 33.477-.552-.1c-3.92-.729-6.397-3.1-7.57-6.829-.733-2.324.597-4.035 3.035-4.148 1.995-.092 3.362 1.055 4.57 2.39 1.557 1.72 2.984 3.558 4.514 5.305 2.202 2.515 4.797 4.134 8.347 3.634 3.183-.448 5.958-1.725 8.371-3.828.363-.316.761-.592 1.144-.886l-.241-.284c-2.027.63-4.093.841-6.205.735-3.195-.16-6.24-.828-8.964-2.582-2.486-1.601-4.319-3.746-5.19-6.611-.704-2.315.736-3.934 3.135-3.6.948.133 1.746.56 2.463 1.165.583.493 1.143 1.015 1.738 1.493 2.8 2.25 6.712 2.375 10.265-.068-5.842-.026-9.817-3.24-13.308-7.313-1.366-1.594-2.7-3.216-4.095-4.785-2.698-3.036-5.692-5.71-9.79-6.623C12.8-.623 7.745.14 2.893 2.361 1.926 2.804.997 3.319 0 4.149c.494 0 .763.006 1.032 0 2.446-.064 4.28 1.023 5.602 3.024.962 1.457 1.415 3.104 1.761 4.798.513 2.515.247 5.078.544 7.605.761 6.494 4.08 11.026 10.26 13.346 2.267.852 4.591 1.135 7.172.555ZM10.751 3.852c-.976.246-1.756-.148-2.56-.962 1.377-.343 2.592-.476 3.897-.528-.107.848-.607 1.306-1.336 1.49Zm32.002 37.924c-.085-.626-.62-.901-1.04-1.228-1.857-1.446-4.03-1.958-6.333-2-1.375-.026-2.735-.128-4.031-.61-.595-.22-1.26-.505-1.244-1.272.015-.78.693-1 1.31-1.184.505-.15 1.026-.247 1.6-.382-1.46-.936-2.886-1.065-4.787-.3-2.993 1.202-5.943 1.06-8.926-.017-1.684-.608-3.179-1.563-4.735-2.408l-.043.03a2.96 2.96 0 0 0 .04-.029c-.038-.117-.107-.12-.197-.054l.122.107c1.29 2.115 3.034 3.817 5.004 5.271 3.793 2.8 7.936 4.471 12.784 3.73A66.714 66.714 0 0 1 37 40.877c1.98-.16 3.866.398 5.753.899Zm-9.14-30.345c-.105-.076-.206-.266-.42-.069 1.745 2.36 3.985 4.098 6.683 5.193 4.354 1.767 8.773 2.07 13.293.51 3.51-1.21 6.033-.028 7.343 3.38.19-3.955-2.137-6.837-5.843-7.401-2.084-.318-4.01.373-5.962.94-5.434 1.575-10.485.798-15.094-2.553Zm27.085 15.425c.708.059 1.416.123 2.124.185-1.6-1.405-3.55-1.517-5.523-1.404-3.003.17-5.167 1.903-7.14 3.972-1.739 1.824-3.31 3.87-5.903 4.604.043.078.054.117.066.117.35.005.699.021 1.047.005 3.768-.17 7.317-.965 10.14-3.7.89-.86 1.685-1.817 2.544-2.71.716-.746 1.584-1.159 2.645-1.07Zm-8.753-4.67c-2.812.246-5.254 1.409-7.548 2.943-1.766 1.18-3.654 1.738-5.776 1.37-.374-.066-.75-.114-1.124-.17l-.013.156c.135.07.265.151.405.207.354.14.702.308 1.07.395 4.083.971 7.992.474 11.516-1.803 2.221-1.435 4.521-1.707 7.013-1.336.252.038.503.083.756.107.234.022.479.255.795.003-2.179-1.574-4.526-2.096-7.094-1.872Zm-10.049-9.544c1.475.051 2.943-.142 4.486-1.059-.452.04-.643.04-.827.076-2.126.424-4.033-.04-5.733-1.383-.623-.493-1.257-.974-1.889-1.457-2.503-1.914-5.374-2.555-8.514-2.5.05.154.054.26.108.315 3.417 3.455 7.371 5.836 12.369 6.008Zm24.727 17.731c-2.114-2.097-4.952-2.367-7.578-.537 1.738.078 3.043.632 4.101 1.728.374.388.763.768 1.182 1.106 1.6 1.29 4.311 1.352 5.896.155-1.861-.726-1.861-.726-3.601-2.452Zm-21.058 16.06c-1.858-3.46-4.981-4.24-8.59-4.008a9.667 9.667 0 0 1 2.977 1.39c.84.586 1.547 1.311 2.243 2.055 1.38 1.473 3.534 2.376 4.962 2.07-.656-.412-1.238-.848-1.592-1.507Zm17.29-19.32c0-.023.001-.045.003-.068l-.006.006.006-.006-.036-.004.021.018.012.053Zm-20 14.744a7.61 7.61 0 0 0-.072-.041.127.127 0 0 0 .015.043c.005.008.038 0 .058-.002Zm-.072-.041-.008-.034-.008.01.008-.01-.022-.006.005.026.024.014Z"
fill="#FD4F00"
/>
</svg>
<h1 class="text-brand mt-10 flex items-center text-sm font-semibold leading-6">
Phoenix Framework
<small class="bg-brand/5 text-[0.8125rem] ml-3 rounded-full px-2 font-medium leading-6">
v{Application.spec(:phoenix, :vsn)}
</small>
<h1 class="text-[2rem] mt-4 font-semibold leading-10 tracking-tighter text-zinc-900 text-balance">
Decentralised Book Index
</h1>
<p class="text-[2rem] mt-4 font-semibold leading-10 tracking-tighter text-zinc-900 text-balance">
Peace of mind from prototype to production.
</p>
<p class="mt-4 text-base leading-7 text-zinc-600">
Build rich, interactive web applications quickly, with less code and fewer moving parts. Join our growing community of developers using Phoenix to craft APIs, HTML5 apps and more, for fun or at scale.
Search the books.
</p>
<div class="flex">
<div class="w-full sm:w-auto">
<div class="mt-10 grid grid-cols-1 gap-x-6 gap-y-4 sm:grid-cols-3">
<a
href="https://hexdocs.pm/phoenix/overview.html"
class="group relative rounded-2xl px-6 py-4 text-sm font-semibold leading-6 text-zinc-900 sm:py-6"
>
<span class="absolute inset-0 rounded-2xl bg-zinc-50 transition group-hover:bg-zinc-100 sm:group-hover:scale-105">
</span>
<span class="relative flex items-center gap-4 sm:flex-col">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true" class="h-6 w-6">
<path d="m12 4 10-2v18l-10 2V4Z" fill="#18181B" fill-opacity=".15" />
<path
d="M12 4 2 2v18l10 2m0-18v18m0-18 10-2v18l-10 2"
stroke="#18181B"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
Guides &amp; Docs
</span>
</a>
<a
href="https://github.com/phoenixframework/phoenix"
class="group relative rounded-2xl px-6 py-4 text-sm font-semibold leading-6 text-zinc-900 sm:py-6"
>
<span class="absolute inset-0 rounded-2xl bg-zinc-50 transition group-hover:bg-zinc-100 sm:group-hover:scale-105">
</span>
<span class="relative flex items-center gap-4 sm:flex-col">
<svg viewBox="0 0 24 24" aria-hidden="true" class="h-6 w-6">
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M12 0C5.37 0 0 5.506 0 12.303c0 5.445 3.435 10.043 8.205 11.674.6.107.825-.262.825-.585 0-.292-.015-1.261-.015-2.291C6 21.67 5.22 20.346 4.98 19.654c-.135-.354-.72-1.446-1.23-1.738-.42-.23-1.02-.8-.015-.815.945-.015 1.62.892 1.845 1.261 1.08 1.86 2.805 1.338 3.495 1.015.105-.8.42-1.338.765-1.645-2.67-.308-5.46-1.37-5.46-6.075 0-1.338.465-2.446 1.23-3.307-.12-.308-.54-1.569.12-3.26 0 0 1.005-.323 3.3 1.26.96-.276 1.98-.415 3-.415s2.04.139 3 .416c2.295-1.6 3.3-1.261 3.3-1.261.66 1.691.24 2.952.12 3.26.765.861 1.23 1.953 1.23 3.307 0 4.721-2.805 5.767-5.475 6.075.435.384.81 1.122.81 2.276 0 1.645-.015 2.968-.015 3.383 0 .323.225.707.825.585a12.047 12.047 0 0 0 5.919-4.489A12.536 12.536 0 0 0 24 12.304C24 5.505 18.63 0 12 0Z"
fill="#18181B"
/>
</svg>
Source Code
</span>
</a>
<a
href={"https://github.com/phoenixframework/phoenix/blob/v#{Application.spec(:phoenix, :vsn)}/CHANGELOG.md"}
class="group relative rounded-2xl px-6 py-4 text-sm font-semibold leading-6 text-zinc-900 sm:py-6"
>
<span class="absolute inset-0 rounded-2xl bg-zinc-50 transition group-hover:bg-zinc-100 sm:group-hover:scale-105">
</span>
<span class="relative flex items-center gap-4 sm:flex-col">
<svg viewBox="0 0 24 24" fill="none" aria-hidden="true" class="h-6 w-6">
<path
d="M12 1v6M12 17v6"
stroke="#18181B"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
<circle
cx="12"
cy="12"
r="4"
fill="#18181B"
fill-opacity=".15"
stroke="#18181B"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
Changelog
</span>
</a>
</div>
<div class="mt-10 grid grid-cols-1 gap-y-4 text-sm leading-6 text-zinc-700 sm:grid-cols-2">
<div>
<a
href="https://twitter.com/elixirphoenix"
class="group -mx-2 -my-0.5 inline-flex items-center gap-3 rounded-lg px-2 py-0.5 hover:bg-zinc-50 hover:text-zinc-900"
>
<svg
viewBox="0 0 16 16"
aria-hidden="true"
class="h-4 w-4 fill-zinc-400 group-hover:fill-zinc-600"
>
<path d="M5.403 14c5.283 0 8.172-4.617 8.172-8.62 0-.131 0-.262-.008-.391A6.033 6.033 0 0 0 15 3.419a5.503 5.503 0 0 1-1.65.477 3.018 3.018 0 0 0 1.263-1.676 5.579 5.579 0 0 1-1.824.736 2.832 2.832 0 0 0-1.63-.916 2.746 2.746 0 0 0-1.821.319A2.973 2.973 0 0 0 8.076 3.78a3.185 3.185 0 0 0-.182 1.938 7.826 7.826 0 0 1-3.279-.918 8.253 8.253 0 0 1-2.64-2.247 3.176 3.176 0 0 0-.315 2.208 3.037 3.037 0 0 0 1.203 1.836A2.739 2.739 0 0 1 1.56 6.22v.038c0 .7.23 1.377.65 1.919.42.54 1.004.912 1.654 1.05-.423.122-.866.14-1.297.052.184.602.541 1.129 1.022 1.506a2.78 2.78 0 0 0 1.662.598 5.656 5.656 0 0 1-2.007 1.074A5.475 5.475 0 0 1 1 12.64a7.827 7.827 0 0 0 4.403 1.358" />
</svg>
Follow on Twitter
</a>
</div>
<div>
<a
href="https://elixirforum.com"
class="group -mx-2 -my-0.5 inline-flex items-center gap-3 rounded-lg px-2 py-0.5 hover:bg-zinc-50 hover:text-zinc-900"
>
<svg
viewBox="0 0 16 16"
aria-hidden="true"
class="h-4 w-4 fill-zinc-400 group-hover:fill-zinc-600"
>
<path d="M8 13.833c3.866 0 7-2.873 7-6.416C15 3.873 11.866 1 8 1S1 3.873 1 7.417c0 1.081.292 2.1.808 2.995.606 1.05.806 2.399.086 3.375l-.208.283c-.285.386-.01.905.465.85.852-.098 2.048-.318 3.137-.81a3.717 3.717 0 0 1 1.91-.318c.263.027.53.041.802.041Z" />
</svg>
Discuss on the Elixir Forum
</a>
</div>
<div>
<a
href="https://web.libera.chat/#elixir"
class="group -mx-2 -my-0.5 inline-flex items-center gap-3 rounded-lg px-2 py-0.5 hover:bg-zinc-50 hover:text-zinc-900"
>
<svg
viewBox="0 0 16 16"
aria-hidden="true"
class="h-4 w-4 fill-zinc-400 group-hover:fill-zinc-600"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M6.356 2.007a.75.75 0 0 1 .637.849l-1.5 10.5a.75.75 0 1 1-1.485-.212l1.5-10.5a.75.75 0 0 1 .848-.637ZM11.356 2.008a.75.75 0 0 1 .637.848l-1.5 10.5a.75.75 0 0 1-1.485-.212l1.5-10.5a.75.75 0 0 1 .848-.636Z"
/>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M14 5.25a.75.75 0 0 1-.75.75h-9.5a.75.75 0 0 1 0-1.5h9.5a.75.75 0 0 1 .75.75ZM13 10.75a.75.75 0 0 1-.75.75h-9.5a.75.75 0 0 1 0-1.5h9.5a.75.75 0 0 1 .75.75Z"
/>
</svg>
Chat on Libera IRC
</a>
</div>
<div>
<a
href="https://discord.gg/elixir"
class="group -mx-2 -my-0.5 inline-flex items-center gap-3 rounded-lg px-2 py-0.5 hover:bg-zinc-50 hover:text-zinc-900"
>
<svg
viewBox="0 0 16 16"
aria-hidden="true"
class="h-4 w-4 fill-zinc-400 group-hover:fill-zinc-600"
>
<path d="M13.545 2.995c-1.02-.46-2.114-.8-3.257-.994a.05.05 0 0 0-.052.024c-.141.246-.297.567-.406.82a12.377 12.377 0 0 0-3.658 0 8.238 8.238 0 0 0-.412-.82.052.052 0 0 0-.052-.024 13.315 13.315 0 0 0-3.257.994.046.046 0 0 0-.021.018C.356 6.063-.213 9.036.066 11.973c.001.015.01.029.02.038a13.353 13.353 0 0 0 3.996 1.987.052.052 0 0 0 .056-.018c.308-.414.582-.85.818-1.309a.05.05 0 0 0-.028-.069 8.808 8.808 0 0 1-1.248-.585.05.05 0 0 1-.005-.084c.084-.062.168-.126.248-.191a.05.05 0 0 1 .051-.007c2.619 1.176 5.454 1.176 8.041 0a.05.05 0 0 1 .053.006c.08.065.164.13.248.192a.05.05 0 0 1-.004.084c-.399.23-.813.423-1.249.585a.05.05 0 0 0-.027.07c.24.457.514.893.817 1.307a.051.051 0 0 0 .056.019 13.31 13.31 0 0 0 4.001-1.987.05.05 0 0 0 .021-.037c.334-3.396-.559-6.345-2.365-8.96a.04.04 0 0 0-.021-.02Zm-8.198 7.19c-.789 0-1.438-.712-1.438-1.587 0-.874.637-1.586 1.438-1.586.807 0 1.45.718 1.438 1.586 0 .875-.637 1.587-1.438 1.587Zm5.316 0c-.788 0-1.438-.712-1.438-1.587 0-.874.637-1.586 1.438-1.586.807 0 1.45.718 1.438 1.586 0 .875-.63 1.587-1.438 1.587Z" />
</svg>
Join our Discord server
</a>
</div>
<div>
<a
href="https://fly.io/docs/elixir/getting-started/"
class="group -mx-2 -my-0.5 inline-flex items-center gap-3 rounded-lg px-2 py-0.5 hover:bg-zinc-50 hover:text-zinc-900"
>
<svg
viewBox="0 0 20 20"
aria-hidden="true"
class="h-4 w-4 fill-zinc-400 group-hover:fill-zinc-600"
>
<path d="M1 12.5A4.5 4.5 0 005.5 17H15a4 4 0 001.866-7.539 3.504 3.504 0 00-4.504-4.272A4.5 4.5 0 004.06 8.235 4.502 4.502 0 001 12.5z" />
</svg>
Deploy your application
</a>
</div>
</div>
</div>
</div>
</div>
</div>

@ -0,0 +1,72 @@
defmodule DecentralisedBookIndexWeb.AuthorLive.Edit do
use DecentralisedBookIndexWeb, :live_view
alias DecentralisedBookIndex.Metadata
@impl true
def render(assigns) do
~H"""
<.live_component
module={DecentralisedBookIndexWeb.AuthorLive.FormComponent}
id={(@author && @author.id) || :new}
title={@page_title}
current_user={@current_user}
action={@live_action}
author={@author}
alternative_author_id={@alternative_author_id}
/>
"""
end
@impl true
def mount(params, _session, socket) do
alternative_author_id = Map.get(params, "alternative_author_id", nil)
{:ok,
socket
|> assign(:alternative_author_id, alternative_author_id)
|> assign_new(:current_user, fn -> nil end)}
end
@impl true
def handle_params(params, _url, socket) do
socket =
socket
|> assign(:params, params)
|> apply_action(socket.assigns.live_action, params)
{:noreply, socket}
end
defp apply_action(socket, :edit, %{"id" => id}) do
socket
|> assign(:page_title, "Edit Author")
|> assign(
:author,
Ash.get!(Metadata.Author, id, load: [:dbi_server], actor: socket.assigns.current_user)
)
|> redirect_if_not_editable()
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, "New Author")
|> assign(:author, nil)
end
@impl true
def handle_info({DecentralisedBookIndexWeb.AuthorLive.FormComponent, {:saved, _author}}, socket) do
{:noreply, socket}
end
defp redirect_if_not_editable(socket) do
if not is_nil(socket.assigns.author.dbi_server) do
socket =
socket
|> Phoenix.LiveView.put_flash(:error, "Can't edit other server's data!")
|> Phoenix.LiveView.redirect(to: ~p"/authors/#{socket.assigns.author}")
else
socket
end
end
end

@ -0,0 +1,187 @@
defmodule DecentralisedBookIndexWeb.AuthorLive.FormComponent do
use DecentralisedBookIndexWeb, :live_component
alias DecentralisedBookIndex.Metadata
@impl true
def render(assigns) do
~H"""
<div>
<.header>
{@title}
</.header>
<.simple_form
for={@form}
id="author-form"
phx-target={@myself}
phx-change="validate"
phx-submit="save"
>
<%= if @form.source.type == :create do %>
<.input field={@form[:name]} type="text" label="Name" />
<.input field={@form[:avatar_url]} type="text" label="Cover image url" />
<.input field={@form[:description]} type="textarea" label="Description" />
<div>
<.input field={@form[:author_alias_registry_id]} type="hidden" label="Author alias registry" />
<.selected_author_alias author_alias_registry_form={@form[:author_alias_registry_id]} notify_component={@myself} />
</div>
<% end %>
<%= if @form.source.type == :update do %>
<.input field={@form[:name]} type="text" label="Name" />
<.input field={@form[:avatar_url]} type="text" label="Cover image url" />
<.input field={@form[:description]} type="textarea" label="Description" />
<div>
<.input field={@form[:author_alias_registry_id]} type="hidden" label="Author alias registry" />
<.selected_author_alias author_alias_registry_form={@form[:author_alias_registry_id]} notify_component={@myself} />
</div>
<% end %>
<:actions>
<.save_button phx-disable-with="Saving...">
Save
</.save_button>
<.cancel_button phx-click="cancel" phx-target={@myself}>
Cancel
</.cancel_button>
</:actions>
</.simple_form>
<.modal
:if={@select_author_alias_open? == true}
id="select-author-alias-modal"
show
on_cancel={JS.push("close-select-author-alias", target: @myself)}
>
<.live_component
id="select-author-alias"
module={SelectAuthorAlias}
current_user={@current_user}
notify_component={@myself}
/>
</.modal>
</div>
"""
end
@impl true
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign(:select_author_alias_open?, false)
|> assign_form()}
end
@impl true
def handle_event("validate", %{"author" => author_params}, socket) do
{:noreply, assign(socket, form: AshPhoenix.Form.validate(socket.assigns.form, author_params))}
end
def handle_event("save", %{"author" => author_params}, socket) do
case AshPhoenix.Form.submit(socket.assigns.form,
params: author_params,
actor: socket.assigns.current_user
) do
{:ok, author} ->
notify_parent({:saved, author})
socket =
socket
|> put_flash(:info, "Author #{socket.assigns.form.source.type}d successfully")
|> redirect(to: patch_url(socket.assigns.action, author.id))
{:noreply, socket}
{:error, form} ->
{:noreply, assign(socket, form: form)}
end
end
def handle_event("cancel", _params, socket) do
author = socket.assigns.author
author_id = if author == nil, do: nil, else: author.id
socket =
socket
|> push_navigate(to: patch_url(socket.assigns.action, author_id))
{:noreply, socket}
end
defp notify_parent(msg), do: send(self(), {__MODULE__, msg})
defp assign_form(
%{assigns: %{author: author, alternative_author_id: alternative_author_id}} = socket
) do
alias_id =
if alternative_author_id == nil do
nil
else
alternative_author = Metadata.get_author_by_id!(alternative_author_id)
alternative_author.author_alias_registry_id
end
form =
if author do
AshPhoenix.Form.for_update(author, :update,
as: "author",
actor: socket.assigns.current_user
)
else
form =
AshPhoenix.Form.for_create(Metadata.Author, :create,
as: "author",
actor: socket.assigns.current_user
)
|> set_author_alias_registry_id(alias_id)
end
assign(socket, form: to_form(form))
end
defp set_author_alias_registry_id(form, alias_id) do
if alias_id != nil do
form
|> AshPhoenix.Form.update_params(&Map.put(&1, "author_alias_registry_id", alias_id))
else
form
end
end
defp patch_url(action, author_id) do
case action do
:edit -> ~p"/authors/#{author_id}"
:new -> ~p"/authors"
_ -> ~p"/authors"
end
end
def handle_event("select-author-alias", %{"author-alias" => author_alias_id}, socket) do
socket =
socket
|> update(:form, fn form ->
form
|> AshPhoenix.Form.update_params(&Map.put(&1, "author_alias_registry_id", author_alias_id))
end)
|> assign(:select_author_alias_open?, false)
{:noreply, socket}
end
def handle_event("open-select-author-alias", _params, socket) do
socket =
socket
|> assign(:select_author_alias_open?, true)
{:noreply, socket}
end
def handle_event("close-select-author-alias", _params, socket) do
socket =
socket
|> assign(:select_author_alias_open?, false)
{:noreply, socket}
end
end

@ -0,0 +1,146 @@
defmodule DecentralisedBookIndexWeb.AuthorLive.Index do
use DecentralisedBookIndexWeb, :live_view
alias DecentralisedBookIndex.Metadata
@impl true
def render(assigns) do
~H"""
<.header class="pb-2">
Listing Authors
</.header>
<.search_resources
search_query={@search_query}
select_options={@select_options}
selected_option={@sort_by}
current_user={@current_user}
resource_type="author"
resource_new_url={~p"/authors/new"}
/>
<%= if Enum.empty?(@page.results) do %>
<div class="flex justify-center ">
<div>
<p class="text-xl font-semibold py-5 dark:text-white">
No Authors
</p>
</div>
</div>
<% else %>
<div class="flex flex-wrap flex-[3_1_auto]">
<%= for author <- @page.results do %>
<.author_card
author={author}
current_user={@current_user}
/>
<% end %>
</div>
<.pagination
endpoint={~p"/authors"}
page={@page}
page_params={@page_params}
params={@params}
/>
<% end %>
"""
end
@impl true
def mount(_params, _session, socket) do
{:ok,
socket
|> assign_new(:current_user, fn -> nil end)}
end
@impl true
def handle_params(params, _url, socket) do
search_query = Map.get(params, "query", "")
sort_by = Map.get(params, "sort_by", "name") |> validate_sort_by()
page_params = AshPhoenix.LiveView.page_from_params(params, 10)
page =
Metadata.search_author!(
search_query,
load: [:brief_description, :dbi_server],
query: [sort_input: sort_by],
page: page_params ++ [count: true],
actor: socket.assigns.current_user
)
socket =
socket
|> assign(:sort_by, sort_by)
|> assign(:search_query, search_query)
|> assign(:select_options, sort_options())
|> assign(:page_params, page_params)
|> assign(:page, page)
|> assign(:params, params)
|> apply_action(socket.assigns.live_action, params)
{:noreply, socket}
end
defp apply_action(socket, :edit, %{"id" => id}) do
socket
|> assign(:page_title, "Edit Author")
|> assign(
:author,
Ash.get!(DecentralisedBookIndex.Metadata.Author, id, actor: socket.assigns.current_user)
)
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, "New Author")
|> assign(:author, nil)
end
defp apply_action(socket, :index, _params) do
socket
|> assign(:page_title, "Listing Authors")
|> assign(:author, nil)
end
@impl true
def handle_info({DecentralisedBookIndexWeb.AuthorLive.FormComponent, {:saved, _author}}, socket) do
{:noreply, socket}
end
defp sort_options do
[
{"Sort by name", "name"},
{"Sort by recently updated", "-updated_at"},
{"Sort by recently added", "-inserted_at"}
]
end
def validate_sort_by(key) do
valid_keys = Enum.map(sort_options(), &elem(&1, 1))
if key in valid_keys do
key
else
List.first(valid_keys)
end
end
@impl true
def handle_event("change-sort", %{"sort_by" => sort_by}, socket) do
params =
socket.assigns.params
|> Map.put("sort_by", sort_by)
{:noreply, push_patch(socket, to: ~p"/authors?#{params}")}
end
@impl true
def handle_event("search", %{"query" => query}, socket) do
params =
socket.assigns.params
|> Map.put("query", query)
{:noreply, push_patch(socket, to: ~p"/authors?#{params}")}
end
end

@ -0,0 +1,124 @@
defmodule DecentralisedBookIndexWeb.AuthorLive.Show do
use DecentralisedBookIndexWeb, :live_view
alias DecentralisedBookIndex.Accounts.Role
@impl true
def render(assigns) do
~H"""
<.header class="flex-col lg:flex-row">
{@author.name}
<:actions>
<%= if @current_user != nil and Role.can_moderate?(@current_user.role) do %>
<div class="flex flex-row gap-2">
<.add_button_link patch={~p"/authors/#{@author}/new"}>
Alias
</.add_button_link>
<%= if is_nil(@author.dbi_server) do %>
<.link patch={~p"/authors/#{@author}/edit"}>
<.edit_button>
Edit
</.edit_button>
</.link>
<% end %>
</div>
<% end %>
</:actions>
</.header>
<div class="flex flex-col items-start gap-6 max-w-6xl mx-auto p-4 bg-gray-900 rounded-lg transition-all duration-300 md:prose md:block">
<%= if @author.avatar_url != nil do %>
<img
class="w-36 h-36 mb-3 rounded-full shadow-lg mx-auto md:float-left md:mr-4"
src={@author.avatar_url}
alt={"#{@author.name} image"}
/>
<% else %>
<div class="relative w-36 h-36 overflow-hidden bg-gray-100 rounded-full dark:bg-gray-600 mx-auto md:float-left md:mr-4">
<svg
class="absolute w-36 h-36 text-gray-400"
fill="currentColor"
viewBox="0 0 20 20"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z"
clip-rule="evenodd"
>
</path>
</svg>
</div>
<% end %>
<div class="flex-1 pt-2 lg:pt-0 min-h-36">
<h2 class="mb-2 font-semibold leading-none text-gray-900 dark:text-white">Description</h2>
<p class="text-gray-300 leading-relaxed">
{@author.description}
</p>
<%= if not is_nil(@author.dbi_server) do %>
<dl>
<dt class="mt-4 mb-2 font-semibold leading-none text-gray-900 dark:text-white">
From Server
</dt>
<dd class="mb-4 font-light text-gray-500 sm:mb-5 dark:text-gray-400">
<%= if @current_user != nil and Role.can_moderate?(@current_user.role) do %>
<.link navigate={~p"/servers/#{@author.dbi_server.id}/"} class="hover:underline">
{@author.dbi_server.name}
</.link>
<% else %>
<.link navigate={@author.dbi_server.url} class="hover:underline">
{@author.dbi_server.name}
</.link>
<% end %>
</dd>
</dl>
<% end %>
</div>
</div>
<%= if @alternative_names != [] do %>
<h2 class="mb-2 text-lg font-semibold text-gray-900 dark:text-white mt-10">
Alternatives names
</h2>
<ul class="max-w-md space-y-1 text-gray-700 list-disc list-inside dark:text-white">
<%= for alias_author <- @alternative_names do %>
<.link navigate={~p"/authors/#{alias_author.id}"}>
<li>
<span class="no-underline hover:underline">
{alias_author.name}
</span>
</li>
</.link>
<% end %>
</ul>
<% end %>
<.back navigate={~p"/authors"}>Back to authors</.back>
"""
end
@impl true
def mount(_params, _session, socket) do
{:ok, socket}
end
@impl true
def handle_params(%{"id" => id}, _, socket) do
author =
Ash.get!(DecentralisedBookIndex.Metadata.Author, id, load: [:dbi_server], actor: socket.assigns.current_user)
alternative_names = DecentralisedBookIndex.Metadata.get_author_alternative_names!(author)
{:noreply,
socket
|> assign(:page_title, page_title(socket.assigns.live_action))
|> assign(:author, author)
|> assign(:alternative_names, alternative_names)}
end
defp page_title(:show), do: "Show Author"
defp page_title(:edit), do: "Edit Author"
end

@ -0,0 +1,69 @@
defmodule DecentralisedBookIndexWeb.BookLive.Edit do
use DecentralisedBookIndexWeb, :live_view
@impl true
def render(assigns) do
~H"""
<.live_component
module={DecentralisedBookIndexWeb.BookLive.FormComponent}
id={(@book && @book.id) || :new}
title={@page_title}
current_user={@current_user}
action={@live_action}
book={@book}
alternative_book_id={@alternative_book_id}
/>
"""
end
@impl true
def mount(params, _session, socket) do
alternative_book_id = Map.get(params, "alternative_book_id", nil)
{:ok,
socket
|> assign(:alternative_book_id, alternative_book_id)
|> assign_new(:current_user, fn -> nil end)}
end
@impl true
def handle_params(params, _url, socket) do
socket =
socket
|> apply_action(socket.assigns.live_action, params)
{:noreply, socket}
end
defp apply_action(socket, :edit, %{"id" => id}) do
socket
|> assign(:page_title, "Edit Book")
|> assign(
:book,
Ash.get!(DecentralisedBookIndex.Metadata.Book, id, load: [:dbi_server], actor: socket.assigns.current_user)
)
|> redirect_if_not_editable()
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, "New Book")
|> assign(:book, nil)
end
@impl true
def handle_info({DecentralisedBookIndexWeb.BookLive.FormComponent, {:saved, _book}}, socket) do
{:noreply, socket}
end
defp redirect_if_not_editable(socket) do
if not is_nil(socket.assigns.book.dbi_server) do
socket =
socket
|> Phoenix.LiveView.put_flash(:error, "Can't edit other server's data!")
|> Phoenix.LiveView.redirect(to: ~p"/books/#{socket.assigns.book}")
else
socket
end
end
end

@ -0,0 +1,488 @@
defmodule DecentralisedBookIndexWeb.BookLive.FormComponent do
use DecentralisedBookIndexWeb, :live_component
alias DecentralisedBookIndex.Metadata
@impl true
def render(assigns) do
~H"""
<div>
<.header>
{@title}
</.header>
<.simple_form
for={@form}
id="book-form"
phx-target={@myself}
phx-change="validate"
phx-submit="save"
>
<%= if @form.source.type == :create do %>
<.input field={@form[:title]} type="text" label="Title" />
<.input field={@form[:cover_image_url]} type="text" label="Cover image url" />
<.input
field={@form[:description]}
type="textarea"
label="Description"
/>
<.bids_inputs form={@form} myself={@myself} />
<.author_roles_inputs form={@form} myself={@myself} notify_component={@myself} />
<.input field={@form[:format]} type="text" label="Format" />
<.input
field={@form[:language]}
type="text"
label="Language"
/>
<.input field={@form[:page_count]} type="number" label="Page count" />
<div>
<.input field={@form[:publisher_id]} type="text" label="Publisher" type="hidden" show_errors?={false} />
<.selected_publisher publisher_form={@form[:publisher_id]} notify_component={@myself} />
</div>
<.input field={@form[:published]} type="date" label="Published" />
<div>
<.input field={@form[:book_editions_registry_id]} type="hidden" label="Book Editions" />
<.selected_book_edition book_editions_registry_form={@form[:book_editions_registry_id]} notify_component={@myself} />
</div>
<% end %>
<%= if @form.source.type == :update do %>
<.input field={@form[:title]} type="text" label="Title" />
<.input field={@form[:cover_image_url]} type="text" label="Cover image url" />
<.input
field={@form[:description]}
type="textarea"
label="Description"
/>
<.bids_inputs form={@form} myself={@myself} />
<.author_roles_inputs form={@form} myself={@myself} notify_component={@myself} />
<.input field={@form[:format]} type="text" label="Format" />
<.input
field={@form[:language]}
type="text"
label="Language"
/>
<.input field={@form[:page_count]} type="number" label="Page count" />
<div>
<.input field={@form[:publisher_id]} type="text" label="Publisher" type="hidden" show_errors?={false} />
<.selected_publisher publisher_form={@form[:publisher_id]} notify_component={@myself} />
</div>
<.input field={@form[:published]} type="date" label="Published" />
<div>
<.input field={@form[:book_editions_registry_id]} type="hidden" label="Book Editions" />
<.selected_book_edition book_editions_registry_form={@form[:book_editions_registry_id]} notify_component={@myself} />
</div>
<% end %>
<:actions>
<.save_button phx-disable-with="Saving...">
Save
</.save_button>
<.cancel_button phx-click="cancel" phx-target={@myself}>
Cancel
</.cancel_button>
</:actions>
</.simple_form>
<.modal
:if={@select_publisher_open? == true}
id="select-publisher-modal"
show
on_cancel={JS.push("close-select-publisher", target: @myself)}
>
<.live_component
id="select-publisher"
module={SelectPublisher}
current_user={@current_user}
notify_component={@myself}
/>
</.modal>
<.modal
:if={@select_book_edition_open? == true}
id="select-book-edition-modal"
show
on_cancel={JS.push("close-select-book-edition", target: @myself)}
>
<.live_component
id="select-book-edition"
module={SelectBookEdition}
current_user={@current_user}
notify_component={@myself}
/>
</.modal>
<.modal
:if={@select_author_open? == true}
id="select-author-modal"
show
on_cancel={JS.push("close-select-author", target: @myself)}
>
<.live_component
id="select-author"
module={SelectAuthor}
current_user={@current_user}
notify_component={@myself}
form_path={@form_path}
/>
</.modal>
</div>
"""
end
def bids_inputs(assigns) do
~H"""
<h2 class="font-semibold leading-8 text-zinc-800 dark:text-white">Book ids</h2>
<table class="w-full">
<thead class="border-b border-zinc-100">
<tr>
<th class="text-left font-medium text-sm pb-1 px-3 w-10"></th>
<th class="text-left font-medium text-sm pb-1 px-3 w-36 dark:text-white">Type</th>
<th class="text-left font-medium text-sm pb-1 px-3 dark:text-white">Id</th>
<th class="text-left font-medium text-sm pb-1 px-3 w-12"></th>
</tr>
</thead>
<tbody phx-hook="bidSort" id="bidSort" phx-target={@myself}>
<.inputs_for :let={bid_form} field={@form[:bids]}>
<tr data-id={bid_form.index}>
<td class="px-3 w-10 pt-2">
<svg class="w-6 h-6 text-gray-800 dark:text-white handle cursor-pointer" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m8 15 4 4 4-4m0-6-4-4-4 4"/>
</svg>
</td>
<td class="px-3 w-36">
<label for={bid_form[:type].id} class="hidden">Type</label>
<.input field={bid_form[:type]} />
</td>
<td class="px-3">
<label for={bid_form[:bid].id} class="hidden">Id</label>
<.input field={bid_form[:bid]} />
</td>
<td class="flex items-center justify-center w-12 pt-2">
<.button_link
phx-click="remove-bid"
phx-value-path={bid_form.name}
phx-target={@myself}
kind="error"
size="xs"
inverse
>
<svg class="w-6 h-6 text-gray-800 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M8.586 2.586A2 2 0 0 1 10 2h4a2 2 0 0 1 2 2v2h3a1 1 0 1 1 0 2v12a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V8a1 1 0 0 1 0-2h3V4a2 2 0 0 1 .586-1.414ZM10 6h4V4h-4v2Zm1 4a1 1 0 1 0-2 0v8a1 1 0 1 0 2 0v-8Zm4 0a1 1 0 1 0-2 0v8a1 1 0 1 0 2 0v-8Z" clip-rule="evenodd"/>
</svg>
</.button_link>
</td>
</tr>
</.inputs_for>
</tbody>
</table>
<.add_button_link phx-click="add-bid" phx-target={@myself} class="w-44">
Add Book Id
</.add_button_link>
"""
end
@impl true
def handle_event("add-bid", _params, socket) do
socket =
update(socket, :form, fn form ->
AshPhoenix.Form.add_form(form, :bids)
end)
{:noreply, socket}
end
@impl true
def handle_event("remove-bid", %{"path" => path}, socket) do
socket =
update(socket, :form, fn form ->
AshPhoenix.Form.remove_form(form, path)
end)
{:noreply, socket}
end
@impl true
def handle_event("reorder-bids", %{"order" => order}, socket) do
socket =
update(socket, :form, fn form ->
AshPhoenix.Form.sort_forms(form, [:bids], order)
end)
{:noreply, socket}
end
def author_roles_inputs(assigns) do
~H"""
<h2 class="font-semibold leading-8 text-zinc-800 dark:text-white">Authors</h2>
<table class="w-full">
<thead class="border-b border-zinc-100">
<tr>
<th class="text-left font-medium text-sm pb-1 px-3 w-10"></th>
<th class="text-left font-medium text-sm pb-1 px-3 w-48 dark:text-white">Author</th>
<th class="text-left font-medium text-sm pb-1 px-3 dark:text-white">Role</th>
<th class="text-left font-medium text-sm pb-1 px-3 w-12"></th>
</tr>
</thead>
<tbody phx-hook="authorRoleSort" id="authorRoleSort" phx-target={@myself}>
<.inputs_for :let={author_roles_form} field={@form[:author_roles]}>
<tr data-id={author_roles_form.index}>
<td class="px-3 w-10 pt-2">
<svg class="w-6 h-6 text-gray-800 dark:text-white handle cursor-pointer" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="none" viewBox="0 0 24 24">
<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m8 15 4 4 4-4m0-6-4-4-4 4"/>
</svg>
</td>
<td class="px-3 w-48">
<label for={author_roles_form[:author_id].id} class="hidden">Type</label>
<.input field={author_roles_form[:author_id]} type="hidden" show_errors?={false} />
<.selected_author
author_form={author_roles_form[:author_id]}
notify_component={@notify_component}
form_path={author_roles_form.name}
class="mt-2 w-full"
/>
</td>
<td class="px-3">
<label for={author_roles_form[:role].id} class="hidden">Id</label>
<.input field={author_roles_form[:role]} />
</td>
<td class="flex items-center justify-center w-12 pt-2">
<.button_link
phx-click="remove-author-role"
phx-value-path={author_roles_form.name}
phx-target={@myself}
kind="error"
size="xs"
inverse
>
<svg class="w-6 h-6 text-gray-800 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M8.586 2.586A2 2 0 0 1 10 2h4a2 2 0 0 1 2 2v2h3a1 1 0 1 1 0 2v12a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V8a1 1 0 0 1 0-2h3V4a2 2 0 0 1 .586-1.414ZM10 6h4V4h-4v2Zm1 4a1 1 0 1 0-2 0v8a1 1 0 1 0 2 0v-8Zm4 0a1 1 0 1 0-2 0v8a1 1 0 1 0 2 0v-8Z" clip-rule="evenodd"/>
</svg>
</.button_link>
</td>
</tr>
</.inputs_for>
</tbody>
</table>
<.add_button_link phx-click="add-author-role" phx-target={@myself} class="w-40">
Add Author
</.add_button_link>
"""
end
@impl true
def handle_event("add-author-role", _params, socket) do
socket =
update(socket, :form, fn form ->
AshPhoenix.Form.add_form(form, :author_roles)
end)
{:noreply, socket}
end
@impl true
def handle_event("remove-author-role", %{"path" => path}, socket) do
socket =
update(socket, :form, fn form ->
AshPhoenix.Form.remove_form(form, path)
end)
{:noreply, socket}
end
@impl true
def handle_event("reorder-author-role", %{"order" => order}, socket) do
socket =
update(socket, :form, fn form ->
AshPhoenix.Form.sort_forms(form, [:author_roles], order)
end)
{:noreply, socket}
end
@impl true
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign(:select_publisher_open?, false)
|> assign(:select_author_open?, false)
|> assign(:select_book_edition_open?, false)
|> assign(:form_path, nil)
|> assign_form()}
end
@impl true
def handle_event("validate", %{"book" => book_params}, socket) do
{:noreply, assign(socket, form: AshPhoenix.Form.validate(socket.assigns.form, book_params))}
end
def handle_event("save", %{"book" => book_params}, socket) do
case AshPhoenix.Form.submit(socket.assigns.form, params: book_params) do
{:ok, book} ->
notify_parent({:saved, book})
socket =
socket
|> put_flash(:info, "Book #{socket.assigns.form.source.type}d successfully")
|> redirect(to: patch_url(socket.assigns.action, book.id))
{:noreply, socket}
{:error, form} ->
{:noreply, assign(socket, form: form)}
end
end
def handle_event("cancel", _params, socket) do
book = socket.assigns.book
book_id = if book == nil, do: nil, else: book.id
socket =
socket
|> push_navigate(to: patch_url(socket.assigns.action, book_id))
{:noreply, socket}
end
defp notify_parent(msg), do: send(self(), {__MODULE__, msg})
defp assign_form(%{assigns: %{book: book, alternative_book_id: alternative_book_id}} = socket) do
alternative_edition_id =
if alternative_book_id == nil do
nil
else
alternative_book = Metadata.get_book_by_id!(alternative_book_id)
alternative_book.book_editions_registry_id
end
form =
if book do
book =
book
|> Ash.load!([:bids, :author_roles, :publisher])
AshPhoenix.Form.for_update(book, :update, as: "book", actor: socket.assigns.current_user)
else
form =
AshPhoenix.Form.for_create(DecentralisedBookIndex.Metadata.Book, :create,
as: "book",
actor: socket.assigns.current_user
)
|> set_book_edition_registry_id(alternative_edition_id)
end
assign(socket, form: to_form(form))
end
defp set_book_edition_registry_id(form, alternative_edition_id) do
if alternative_edition_id != nil do
form
|> AshPhoenix.Form.update_params(
&Map.put(&1, "book_editions_registry_id", alternative_edition_id)
)
else
form
end
end
defp patch_url(action, book_id) do
case action do
:edit -> ~p"/books/#{book_id}"
:new -> ~p"/books"
_ -> ~p"/books"
end
end
def handle_event("select-publisher", %{"publisher" => publisher_id}, socket) do
socket =
socket
|> update(:form, fn form ->
form
|> AshPhoenix.Form.update_params(&Map.put(&1, "publisher_id", publisher_id))
end)
|> assign(:select_publisher_open?, false)
{:noreply, socket}
end
def handle_event("open-select-publisher", _params, socket) do
socket =
socket
|> assign(:select_publisher_open?, true)
{:noreply, socket}
end
def handle_event("close-select-publisher", _params, socket) do
socket =
socket
|> assign(:select_publisher_open?, false)
{:noreply, socket}
end
def handle_event("select-author", %{"author" => author_id, "path" => path}, socket) do
socket =
socket
|> update(:form, fn form ->
form
|> AshPhoenix.Form.update_form(path, fn nested_form ->
params = Map.put(nested_form.params, "author_id", author_id)
AshPhoenix.Form.validate(nested_form, params)
end)
end)
|> assign(:select_author_open?, false)
{:noreply, socket}
end
def handle_event("open-select-author", %{"path" => path}, socket) do
socket =
socket
|> assign(:select_author_open?, true)
|> assign(:form_path, path)
{:noreply, socket}
end
def handle_event("close-select-author", _params, socket) do
socket =
socket
|> assign(:select_author_open?, false)
|> assign(:form_path, nil)
{:noreply, socket}
end
def handle_event("select-book-edition", %{"book-edition" => book_edition_id}, socket) do
socket =
socket
|> update(:form, fn form ->
form
|> AshPhoenix.Form.update_params(&Map.put(&1, "book_editions_registry_id", book_edition_id))
end)
|> assign(:select_book_edition_open?, false)
{:noreply, socket}
end
def handle_event("open-select-book-edition", _params, socket) do
socket =
socket
|> assign(:select_book_edition_open?, true)
{:noreply, socket}
end
def handle_event("close-select-book-edition", _params, socket) do
socket =
socket
|> assign(:select_book_edition_open?, false)
{:noreply, socket}
end
end

@ -0,0 +1,218 @@
defmodule DecentralisedBookIndexWeb.BookLive.Index do
use DecentralisedBookIndexWeb, :live_view
alias DecentralisedBookIndex.Metadata
@impl true
def render(assigns) do
~H"""
<.header class="pb-2">
Listing Books
</.header>
<.book_search
search_query={@search_query}
search_mode={@search_mode}
search_mode_options={@search_mode_options}
select_options={@select_options}
selected_option={@sort_by}
current_user={@current_user}
/>
<%= if Enum.empty?(@page.results) do %>
<div class="flex justify-center ">
<div>
<p class="text-xl font-semibold py-5 dark:text-white">
No Books
</p>
</div>
</div>
<% else %>
<div class="flex flex-wrap flex-[3_1_auto]">
<%= for book <- @page.results do %>
<.book_card
book={book}
current_user={@current_user}
/>
<% end %>
</div>
<.pagination
endpoint={~p"/books"}
page={@page}
page_params={@page_params}
params={@params}
/>
<% end %>
<.modal :if={@live_action in [:new, :edit]} id="book-modal" show on_cancel={JS.patch(~p"/books")}>
<.live_component
module={DecentralisedBookIndexWeb.BookLive.FormComponent}
id={(@book && @book.id) || :new}
title={@page_title}
current_user={@current_user}
action={@live_action}
book={@book}
patch={~p"/books"}
/>
</.modal>
"""
end
@impl true
def mount(_params, _session, socket) do
{:ok, socket}
end
@impl true
def handle_params(params, _url, socket) do
search_query = Map.get(params, "query", "")
sort_by = Map.get(params, "sort_by", "title") |> validate_sort_by()
search_mode = Map.get(params, "search_mode", "title") |> validate_search_mode()
page_params = AshPhoenix.LiveView.page_from_params(params, 10)
page =
search(
search_mode,
search_query,
page_params,
sort_by: sort_by,
actor: socket.assigns[:current_user]
)
socket =
socket
|> stream(
:books,
Ash.read!(DecentralisedBookIndex.Metadata.Book, actor: socket.assigns[:current_user])
)
|> assign(:sort_by, sort_by)
|> assign(:search_query, search_query)
|> assign(:search_mode, search_mode)
|> assign(:search_mode_options, search_mode_options())
|> assign(:select_options, sort_options())
|> assign(:page_params, page_params)
|> assign(:page, page)
|> assign(:params, params)
|> assign_new(:current_user, fn -> nil end)
|> apply_action(socket.assigns.live_action, params)
{:noreply, socket}
end
defp apply_action(socket, :edit, %{"id" => id}) do
socket
|> assign(:page_title, "Edit Book")
|> assign(
:book,
Ash.get!(DecentralisedBookIndex.Metadata.Book, id, actor: socket.assigns.current_user)
)
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, "New Book")
|> assign(:book, nil)
end
defp apply_action(socket, :index, _params) do
socket
|> assign(:page_title, "Listing Books")
|> assign(:book, nil)
end
@impl true
def handle_info({DecentralisedBookIndexWeb.BookLive.FormComponent, {:saved, _book}}, socket) do
{:noreply, socket}
end
defp sort_options do
[
{"Sort by title", "title"},
{"Sort by recently updated", "-updated_at"},
{"Sort by recently added", "-inserted_at"}
]
end
def validate_sort_by(key) do
valid_keys = Enum.map(sort_options(), &elem(&1, 1))
if key in valid_keys do
key
else
List.first(valid_keys)
end
end
@impl true
def handle_event("change-sort", %{"sort_by" => sort_by}, socket) do
params =
socket.assigns.params
|> Map.put("sort_by", sort_by)
{:noreply, push_patch(socket, to: ~p"/books?#{params}")}
end
defp search_mode_options do
[
{"Search by title", "title"},
{"Search by isbn13", "isbn13"},
{"Search by isbn", "isbn"},
{"Search by asin", "asin"}
]
end
def validate_search_mode(key) do
valid_keys = Enum.map(search_mode_options(), &elem(&1, 1))
if key in valid_keys do
key
else
List.first(valid_keys)
end
end
@impl true
def handle_event("change-search-mode", %{"search_mode" => search_mode}, socket) do
params =
socket.assigns.params
|> Map.put("search_mode", search_mode)
{:noreply, push_patch(socket, to: ~p"/books?#{params}")}
end
def search(search_mode, search_query, page_params, opts \\ []) do
sort_by = Keyword.get(opts, :sort_by, nil)
actor = Keyword.get(opts, :actor, nil)
case search_mode do
"title" ->
Metadata.search_book!(
search_query,
load: [:brief_description, :dbi_server],
query: [sort_input: sort_by],
page: page_params ++ [count: true],
actor: actor
)
type ->
Metadata.search_book_by_bid!(
type,
search_query,
load: [:brief_description, :dbi_server],
query: [sort_input: sort_by],
page: page_params ++ [count: true],
actor: actor
)
end
end
@impl true
def handle_event("search", %{"query" => query}, socket) do
params =
socket.assigns.params
|> Map.put("query", query)
{:noreply, push_patch(socket, to: ~p"/books?#{params}")}
end
end

@ -0,0 +1,165 @@
defmodule DecentralisedBookIndexWeb.BookLive.Show do
use DecentralisedBookIndexWeb, :live_view
alias DecentralisedBookIndex.Metadata
alias DecentralisedBookIndex.Accounts.Role
@impl true
def render(assigns) do
~H"""
<.header class="flex-col lg:flex-row">
{@book.title}
<:subtitle>
<.authors book={@book} />
</:subtitle>
<:actions>
<%= if @current_user != nil and Role.can_moderate?(@current_user.role) do %>
<div class="flex flex-row gap-2">
<.add_button_link patch={~p"/books/#{@book}/new"}>
Edition
</.add_button_link>
<%= if is_nil(@book.dbi_server) do %>
<.link patch={~p"/books/#{@book}/edit"}>
<.edit_button>
Edit
</.edit_button>
</.link>
<% end %>
</div>
<% end %>
</:actions>
</.header>
<div class="mb-4">
<%= if @book.cover_image_url != nil do %>
<img class="w-36 shadow-lg mt-14 mx-auto object-cover" src={@book.cover_image_url} alt={"#{@book.title} image"}/>
<% else %>
<div class="relative w-36 h-36 overflow-hidden mt-14 mx-auto">
<svg class="w-36 h-36 text-gray-800 dark:text-white" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M6 2a2 2 0 0 0-2 2v15a3 3 0 0 0 3 3h12a1 1 0 1 0 0-2h-2v-2h2a1 1 0 0 0 1-1V4a2 2 0 0 0-2-2h-8v16h5v2H7a1 1 0 1 1 0-2h1V2H6Z" clip-rule="evenodd"/>
</svg>
</div>
<% end %>
</div>
<div>
<dl>
<dt class="mb-2 font-semibold leading-none text-gray-900 dark:text-white">Description</dt>
<dd class="mb-4 font-light text-gray-500 sm:mb-5 dark:text-gray-400">{@book.description}</dd>
</dl>
<dl>
<dt class="mb-2 font-semibold leading-none text-gray-900 dark:text-white">Publisher</dt>
<dd class="mb-4 font-light text-gray-500 sm:mb-5 dark:text-gray-400">{@book.publisher.name}</dd>
</dl>
<dl>
<dt class="mb-2 font-semibold leading-none text-gray-900 dark:text-white">Published</dt>
<dd class="mb-4 font-light text-gray-500 sm:mb-5 dark:text-gray-400">{@book.published}</dd>
</dl>
<dl>
<dt class="mb-2 font-semibold leading-none text-gray-900 dark:text-white">Format</dt>
<dd class="mb-4 font-light text-gray-500 sm:mb-5 dark:text-gray-400">{@book.format}</dd>
</dl>
<dl>
<dt class="mb-2 font-semibold leading-none text-gray-900 dark:text-white">Page Count</dt>
<dd class="mb-4 font-light text-gray-500 sm:mb-5 dark:text-gray-400">{@book.page_count}</dd>
</dl>
<dl>
<dt class="mb-2 font-semibold leading-none text-gray-900 dark:text-white">Language</dt>
<dd class="mb-4 font-light text-gray-500 sm:mb-5 dark:text-gray-400">{@book.language}</dd>
</dl>
<dl>
<dt class="mb-2 font-semibold leading-none text-gray-900 dark:text-white">Identifiers</dt>
<%= for bid <- @book.bids do %>
<dd class="mb-4 font-light text-gray-500 sm:mb-5 dark:text-gray-400">{bid.type}: {bid.bid}</dd>
<% end %>
</dl>
<%= if not is_nil(@book.dbi_server) do %>
<dl>
<dt class="mb-2 font-semibold leading-none text-gray-900 dark:text-white">From Server</dt>
<dd class="mb-4 font-light text-gray-500 sm:mb-5 dark:text-gray-400">
<%= if @current_user != nil and Role.can_moderate?(@current_user.role) do %>
<.link navigate={~p"/servers/#{@book.dbi_server.id}/"} class="hover:underline">
{@book.dbi_server.name}
</.link>
<% else %>
<.link navigate={@book.dbi_server.url} class="hover:underline">
{@book.dbi_server.name}
</.link>
<% end %>
</dd>
</dl>
<% end %>
</div>
<%= if not Enum.empty?(@alternative_editions) do %>
<h1 class="text-lg font-semibold leading-8 text-zinc-800 dark:text-white">Editions</h1>
<div class="flex flex-wrap flex-[3_1_auto]">
<%= for book <- @alternative_editions do %>
<.book_card
book={book}
current_user={@current_user}
/>
<% end %>
</div>
<% end %>
<.back navigate={~p"/books"}>Back to books</.back>
"""
end
@impl true
def mount(_params, _session, socket) do
{:ok, socket}
end
@impl true
def handle_params(%{"id" => id}, _, socket) do
book =
Ash.get!(Metadata.Book, id,
actor: socket.assigns.current_user,
load: [:bids, :author_roles, :publisher, :dbi_server]
)
alternative_editions = Metadata.get_book_alternative_editions!(book)
{:noreply,
socket
|> assign(:page_title, page_title(socket.assigns.live_action))
|> assign(:book, book)
|> assign(:alternative_editions, alternative_editions)}
end
defp page_title(:show), do: "Show Book"
defp page_title(:edit), do: "Edit Book"
attr :book, :map, required: true
def authors(assigns) do
author_roles = Metadata.get_author_roles_by_book_id!(assigns.book.id, load: [:author])
author_count = length(author_roles)
authors_string =
author_roles
|> Enum.map(fn author_role ->
if author_role.role in ["", nil] do
{"#{author_role.author.name}", author_role.author.id}
else
{"#{author_role.author.name} (#{author_role.role})", author_role.author.id}
end
end)
|> Enum.zip(1..author_count)
assigns =
assigns
|> assign(:authors_string, authors_string)
|> assign(:author_count, author_count)
~H"""
<%= for {{name, id}, index} <- @authors_string do %>
<.link navigate={~p"/authors/#{id}/"} class="hover:underline">
{name}</.link><%= if {index} != {@author_count} do %>,<% end %>
<% end %>
"""
end
end

@ -0,0 +1,59 @@
defmodule DecentralisedBookIndexWeb.DbiServerLive.Edit do
use DecentralisedBookIndexWeb, :live_view
alias DecentralisedBookIndex.Metadata
@impl true
def render(assigns) do
~H"""
<.live_component
module={DecentralisedBookIndexWeb.DbiServerLive.FormComponent}
id={(@dbi_server && @dbi_server.id) || :new}
title={@page_title}
current_user={@current_user}
action={@live_action}
dbi_server={@dbi_server}
/>
"""
end
@impl true
def mount(_params, _session, socket) do
{:ok,
socket
|> assign_new(:current_user, fn -> nil end)}
end
@impl true
def handle_params(params, _url, socket) do
socket =
socket
|> assign(:params, params)
|> apply_action(socket.assigns.live_action, params)
{:noreply, socket}
end
defp apply_action(socket, :edit, %{"id" => id}) do
socket
|> assign(:page_title, "Edit Server")
|> assign(
:dbi_server,
Ash.get!(Metadata.DBIServer, id, actor: socket.assigns.current_user)
)
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, "New Server")
|> assign(:dbi_server, nil)
end
@impl true
def handle_info(
{DecentralisedBookIndexWeb.DbiServerLive.FormComponent, {:saved, _dbi_server}},
socket
) do
{:noreply, socket}
end
end

@ -0,0 +1,110 @@
defmodule DecentralisedBookIndexWeb.DbiServerLive.FormComponent do
use DecentralisedBookIndexWeb, :live_component
@impl true
def render(assigns) do
~H"""
<div>
<.header>
{@title}
</.header>
<.simple_form
for={@form}
id="dbi_server-form"
phx-target={@myself}
phx-change="validate"
phx-submit="save"
>
<%= if @form.source.type == :create do %>
<.input field={@form[:name]} type="text" label="Name" />
<.input field={@form[:url]} type="text" label="Url" />
<% end %>
<%= if @form.source.type == :update and is_nil(@form[:dbi_server_id].value) do %>
<.input field={@form[:name]} type="text" label="Name" />
<.input field={@form[:url]} type="text" label="Url" />
<% end %>
<.input field={@form[:sync_on?]} type="checkbox" label="Sync on" />
<:actions>
<.save_button phx-disable-with="Saving...">
Save
</.save_button>
<.cancel_button phx-click="cancel" phx-target={@myself}>
Cancel
</.cancel_button>
</:actions>
</.simple_form>
</div>
"""
end
@impl true
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign_form()}
end
@impl true
def handle_event("validate", %{"dbi_server" => dbi_server_params}, socket) do
{:noreply,
assign(socket, form: AshPhoenix.Form.validate(socket.assigns.form, dbi_server_params))}
end
def handle_event("save", %{"dbi_server" => dbi_server_params}, socket) do
case AshPhoenix.Form.submit(socket.assigns.form, params: dbi_server_params) do
{:ok, dbi_server} ->
notify_parent({:saved, dbi_server})
socket =
socket
|> put_flash(:info, "Server #{socket.assigns.form.source.type}d successfully")
|> redirect(to: patch_url(socket.assigns.action, dbi_server.id))
{:noreply, socket}
{:error, form} ->
{:noreply, assign(socket, form: form)}
end
end
def handle_event("cancel", _params, socket) do
dbi_server = socket.assigns.dbi_server
dbi_server_id = if dbi_server == nil, do: nil, else: dbi_server.id
socket =
socket
|> push_navigate(to: patch_url(socket.assigns.action, dbi_server_id))
{:noreply, socket}
end
defp notify_parent(msg), do: send(self(), {__MODULE__, msg})
defp assign_form(%{assigns: %{dbi_server: dbi_server}} = socket) do
form =
if dbi_server do
AshPhoenix.Form.for_update(dbi_server, :update,
as: "dbi_server",
actor: socket.assigns.current_user
)
else
AshPhoenix.Form.for_create(DecentralisedBookIndex.Metadata.DBIServer, :create,
as: "dbi_server",
actor: socket.assigns.current_user
)
end
assign(socket, form: to_form(form))
end
defp patch_url(action, server_id) do
case action do
:edit -> ~p"/servers/#{server_id}"
:new -> ~p"/servers"
_ -> ~p"/servers"
end
end
end

@ -0,0 +1,229 @@
defmodule DecentralisedBookIndexWeb.DbiServerLive.Index do
use DecentralisedBookIndexWeb, :live_view
alias DecentralisedBookIndex.Metadata
alias DecentralisedBookIndex.SyncTasks.SyncServerTask
alias DecentralisedBookIndex.Accounts.Role
@impl true
def render(assigns) do
~H"""
<.header>
Listing Servers
<:actions>
<%= if @current_user != nil and Role.can_administrate?(@current_user.role) do %>
<div class="flex flex-row gap-2">
<div class="flex flex-row gap-2">
<.primary_button phx-click="sync">
Sync now
</.primary_button>
</div>
<div class="flex flex-row gap-2">
<.link patch={~p"/oban"}>
<.primary_button>
Task dashboard
</.primary_button>
</.link>
</div>
</div>
<% end %>
</:actions>
</.header>
<div class="pt-2">
<.search_resources
search_query={@search_query}
select_options={@select_options}
selected_option={@sort_by}
current_user={@current_user}
resource_type="server"
resource_new_url={~p"/servers/new"}
moderator_role={:admin}
/>
</div>
<%= if Enum.empty?(@page.results) do %>
<div class="flex justify-center ">
<div>
<p class="text-xl font-semibold py-5 dark:text-white">
No Servers
</p>
</div>
</div>
<% else %>
<div class="pt-2 flex flex-col gap-2">
<.table
id="dbi_servers"
rows={@page.results}
row_click={fn dbi_server -> JS.navigate(~p"/servers/#{dbi_server}") end}
>
<:col :let={dbi_server} label="Name">{dbi_server.name}</:col>
<:col :let={dbi_server} label="Url">{dbi_server.url}</:col>
<:action :let={dbi_server}>
<div class="sr-only">
<.link navigate={~p"/servers/#{dbi_server}"}>Show</.link>
</div>
<%= if @current_user != nil and Role.can_administrate?(@current_user.role) do %>
<.link patch={~p"/servers/#{dbi_server}/edit"}>Edit</.link>
<% end %>
</:action>
</.table>
<.pagination
endpoint={~p"/servers"}
page={@page}
page_params={@page_params}
params={@params}
/>
</div>
<% end %>
"""
end
@impl true
def mount(_params, _session, socket) do
if connected?(socket) do
Phoenix.PubSub.subscribe(DecentralisedBookIndex.PubSub, DecentralisedBookIndex.SyncWorkerManual.topic())
end
{:ok,
socket
|> assign_new(:current_user, fn -> nil end)}
end
@impl true
def handle_params(params, _url, socket) do
search_query = Map.get(params, "query", "")
sort_by = Map.get(params, "sort_by", "name") |> validate_sort_by()
page_params = AshPhoenix.LiveView.page_from_params(params, 10)
page =
Metadata.search_dbi_server!(
search_query,
query: [sort_input: sort_by],
page: page_params ++ [count: true],
actor: socket.assigns.current_user
)
socket =
socket
|> assign(:sort_by, sort_by)
|> assign(:search_query, search_query)
|> assign(:select_options, sort_options())
|> assign(:page_params, page_params)
|> assign(:page, page)
|> assign(:params, params)
|> apply_action(socket.assigns.live_action, params)
{:noreply, socket}
end
defp apply_action(socket, :edit, %{"id" => id}) do
socket
|> assign(:page_title, "Edit server")
|> assign(
:dbi_server,
Ash.get!(DecentralisedBookIndex.Metadata.DBIServer, id, actor: socket.assigns.current_user)
)
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, "New server")
|> assign(:dbi_server, nil)
end
defp apply_action(socket, :index, _params) do
socket
|> assign(:page_title, "Listing servers")
|> assign(:dbi_server, nil)
end
@impl true
def handle_info(
{DecentralisedBookIndexWeb.DbiServerLive.FormComponent, {:saved, _dbi_server}},
socket
) do
{:noreply, socket}
end
@impl true
def handle_event("delete", %{"id" => id}, socket) do
dbi_server =
Ash.get!(DecentralisedBookIndex.Metadata.DBIServer, id, actor: socket.assigns.current_user)
Ash.destroy!(dbi_server, actor: socket.assigns.current_user)
{:noreply, socket}
end
defp sort_options do
[
{"Sort by name", "name"},
{"Sort by recently updated", "-updated_at"},
{"Sort by recently added", "-inserted_at"}
]
end
def validate_sort_by(key) do
valid_keys = Enum.map(sort_options(), &elem(&1, 1))
if key in valid_keys do
key
else
List.first(valid_keys)
end
end
@impl true
def handle_event("change-sort", %{"sort_by" => sort_by}, socket) do
params =
socket.assigns.params
|> Map.put("sort_by", sort_by)
{:noreply, push_patch(socket, to: ~p"/servers?#{params}")}
end
@impl true
def handle_event("search", %{"query" => query}, socket) do
params =
socket.assigns.params
|> Map.put("query", query)
{:noreply, push_patch(socket, to: ~p"/servers?#{params}")}
end
@impl true
def handle_event("sync", _params, socket) do
case DecentralisedBookIndex.SyncWorkerManual.new(%{}) |> Oban.insert() do
{:ok, _job} ->
{:noreply, put_flash(socket, :info, "Task started")}
{:error, reason} ->
{:noreply, put_flash(socket, :error, "Failed to start task: #{inspect(reason)}")}
end
end
@impl true
def handle_info({:manual_sync_completed, result}, socket) do
socket =
if result == :ok do
socket
|> put_flash(:info, "Task completed")
else
socket
|> put_flash(:error, "Task failed")
end
{:noreply, socket}
end
@impl true
def handle_info(_params, socket) do
{:noreply, socket}
end
end

@ -0,0 +1,66 @@
defmodule DecentralisedBookIndexWeb.DbiServerLive.Show do
use DecentralisedBookIndexWeb, :live_view
alias DecentralisedBookIndex.Accounts.Role
@impl true
def render(assigns) do
~H"""
<.header class="flex-col lg:flex-row">
{@dbi_server.name}
<:actions>
<%= if is_nil(@dbi_server.dbi_server) and @current_user != nil and Role.can_administrate?(@current_user.role) do %>
<.link patch={~p"/servers/#{@dbi_server}/edit"} phx-click={JS.push_focus()}>
<.edit_button>
Edit
</.edit_button>
</.link>
<% end %>
</:actions>
</.header>
<div>
<dl>
<dt class="mb-2 font-semibold leading-none text-gray-900 dark:text-white">Url</dt>
<dd class="mb-4 font-light text-gray-500 sm:mb-5 dark:text-gray-400">{@dbi_server.url}</dd>
</dl>
<dl>
<dt class="mb-2 font-semibold leading-none text-gray-900 dark:text-white">Sync on?</dt>
<dd class="mb-4 font-light text-gray-500 sm:mb-5 dark:text-gray-400">{@dbi_server.sync_on?}</dd>
</dl>
<%= if not is_nil(@dbi_server.dbi_server) do %>
<dl>
<dt class="mb-2 font-semibold leading-none text-gray-900 dark:text-white">From Server</dt>
<dd class="mb-4 font-light text-gray-500 sm:mb-5 dark:text-gray-400">
<.link navigate={~p"/servers/#{@dbi_server.dbi_server.id}/"} class="hover:underline">
{@dbi_server.dbi_server.name}
</.link>
</dd>
</dl>
<% end %>
</div>
<.back navigate={~p"/servers"}>Back to servers</.back>
"""
end
@impl true
def mount(_params, _session, socket) do
{:ok, socket}
end
@impl true
def handle_params(%{"id" => id}, _, socket) do
{:noreply,
socket
|> assign(:page_title, page_title(socket.assigns.live_action))
|> assign(
:dbi_server,
Ash.get!(DecentralisedBookIndex.Metadata.DBIServer, id, load: [:dbi_server], actor: socket.assigns.current_user)
)}
end
defp page_title(:show), do: "Show server"
defp page_title(:edit), do: "Edit server"
end

@ -0,0 +1,71 @@
defmodule DecentralisedBookIndexWeb.PublisherLive.Edit do
use DecentralisedBookIndexWeb, :live_view
alias DecentralisedBookIndex.Metadata
@impl true
def render(assigns) do
~H"""
<.live_component
module={DecentralisedBookIndexWeb.PublisherLive.FormComponent}
id={(@publisher && @publisher.id) || :new}
title={@page_title}
current_user={@current_user}
action={@live_action}
publisher={@publisher}
/>
"""
end
@impl true
def mount(_params, _session, socket) do
{:ok,
socket
|> assign_new(:current_user, fn -> nil end)}
end
@impl true
def handle_params(params, _url, socket) do
socket =
socket
|> assign(:params, params)
|> apply_action(socket.assigns.live_action, params)
{:noreply, socket}
end
defp apply_action(socket, :edit, %{"id" => id}) do
socket
|> assign(:page_title, "Edit Publisher")
|> assign(
:publisher,
Ash.get!(Metadata.Publisher, id, load: [:dbi_server], actor: socket.assigns.current_user)
)
|> redirect_if_not_editable()
end
defp apply_action(socket, :new, _params) do
socket
|> assign(:page_title, "New Publisher")
|> assign(:publisher, nil)
end
@impl true
def handle_info(
{DecentralisedBookIndexWeb.PublisherLive.FormComponent, {:saved, _publisher}},
socket
) do
{:noreply, socket}
end
defp redirect_if_not_editable(socket) do
if not is_nil(socket.assigns.publisher.dbi_server) do
socket =
socket
|> Phoenix.LiveView.put_flash(:error, "Can't edit other server's data!")
|> Phoenix.LiveView.redirect(to: ~p"/publishers/#{socket.assigns.publisher}")
else
socket
end
end
end

@ -0,0 +1,107 @@
defmodule DecentralisedBookIndexWeb.PublisherLive.FormComponent do
use DecentralisedBookIndexWeb, :live_component
@impl true
def render(assigns) do
~H"""
<div>
<.header>
{@title}
</.header>
<.simple_form
for={@form}
id="publisher-form"
phx-target={@myself}
phx-change="validate"
phx-submit="save"
>
<%= if @form.source.type == :create do %>
<.input field={@form[:name]} type="text" label="Name" />
<% end %>
<%= if @form.source.type == :update do %>
<.input field={@form[:name]} type="text" label="Name" />
<% end %>
<:actions>
<.save_button phx-disable-with="Saving...">
Save
</.save_button>
<.cancel_button phx-click="cancel" phx-target={@myself}>
Cancel
</.cancel_button>
</:actions>
</.simple_form>
</div>
"""
end
@impl true
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)
|> assign_form()}
end
@impl true
def handle_event("validate", %{"publisher" => publisher_params}, socket) do
{:noreply,
assign(socket, form: AshPhoenix.Form.validate(socket.assigns.form, publisher_params))}
end
def handle_event("save", %{"publisher" => publisher_params}, socket) do
case AshPhoenix.Form.submit(socket.assigns.form, params: publisher_params) do
{:ok, publisher} ->
notify_parent({:saved, publisher})
socket =
socket
|> put_flash(:info, "Publisher #{socket.assigns.form.source.type}d successfully")
|> push_navigate(to: patch_url(socket.assigns.action, publisher.id))
{:noreply, socket}
{:error, form} ->
{:noreply, assign(socket, form: form)}
end
end
def handle_event("cancel", _params, socket) do
publisher = socket.assigns.publisher
publisher_id = if publisher == nil, do: nil, else: publisher.id
socket =
socket
|> push_navigate(to: patch_url(socket.assigns.action, publisher_id))
{:noreply, socket}
end
defp notify_parent(msg), do: send(self(), {__MODULE__, msg})
defp assign_form(%{assigns: %{publisher: publisher}} = socket) do
form =
if publisher do
AshPhoenix.Form.for_update(publisher, :update,
as: "publisher",
actor: socket.assigns.current_user
)
else
AshPhoenix.Form.for_create(DecentralisedBookIndex.Metadata.Publisher, :create,
as: "publisher",
actor: socket.assigns.current_user
)
end
assign(socket, form: to_form(form))
end
defp patch_url(action, publisher_id) do
case action do
:edit -> ~p"/publishers/#{publisher_id}"
:new -> ~p"/publishers"
_ -> ~p"/publishers"
end
end
end

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save