Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

social media links using web4 #111

Merged
merged 19 commits into from
May 16, 2024

Conversation

petersalomonsen
Copy link
Collaborator

@petersalomonsen petersalomonsen commented Apr 27, 2024

This PR adds the web4_get method to the contract, so that when merged, there will be a website at https://devhub.near.page

You can preview it at https://devhublink.testnet.page/

image

Note that the preview deployment does not have access to content, so it will not be able to display proper content for preview links, which is provided by the contract. A test community "webassemblymusic" is created for the preview deployment, to demonstrate the preview links. You can test it at https://devhublink.testnet.page/community/webassemblymusic. You may also call the preview contract to create proposals and other communities to verify that social media headers are also populated with the content.

For now the first part of the part is always mapped to the page property, so that e.g. /proposals are translated to /devhub.near/widget/app?page=proposals. Also the second part translates to handle for community ( /community/webassemblymusic -> /devhub.near/widget/app?page=community&handle=webassemblymusic ), or to id for proposal /proposal/5 -> /devhub.near/widget/app?page=proposal&id=5

In addition to metadata for social media links, and SEO friendly URLs, the actual content is viewed as well. This is done using near-bos-webcomponent which is also used for playwright tests in the DevHub frontend. A PR have also been created there to support the SEO friendly URL paths created here.

The html-escape crate is added to ensure that descriptions with html tags are escaped for the generated HTML ( to avoid malicious scripts etc ).

Examples:

Part of NEAR-DevHub/neardevhub-bos#724

Summary by CodeRabbit

  • New Features

    • Introduced a new web4 module to handle web requests, dynamically generate HTML content, and encode responses.
    • Added a public function for fetching web content based on request paths, enhancing user interaction with community and proposal pages.
  • Documentation

    • Enhanced documentation for new web request handling functionality.
  • Dependencies

    • Added html-escape library to support HTML content generation.

@petersalomonsen petersalomonsen marked this pull request as draft April 27, 2024 07:10
@petersalomonsen petersalomonsen changed the title wip: social media links using web4 social media links using web4 Apr 27, 2024
@petersalomonsen petersalomonsen marked this pull request as ready for review April 28, 2024 19:21
src/web4/handler.rs Outdated Show resolved Hide resolved
src/web4/handler.rs Outdated Show resolved Hide resolved
src/web4/handler.rs Outdated Show resolved Hide resolved
src/web4/handler.rs Outdated Show resolved Hide resolved
src/web4/handler.rs Outdated Show resolved Hide resolved
Copy link

coderabbitai bot commented May 1, 2024

Walkthrough

The update enhances web request handling in a Rust application by introducing the web4 module. This includes new types for managing web requests and responses, a handler for dynamic HTML content creation based on request paths, and the addition of the html-escape dependency for HTML processing. The web4 module is now publicly accessible with a specific function web4_get for fetching web content.

Changes

File Changes
Cargo.toml Added html-escape dependency version 0.2.13.
src/lib.rs Added web4 module to public exports, imported relevant types, and included web4_get function.
src/web4/handler.rs Introduced handler.rs with web request handling functionality, including web4_get.

🐇✨
In the code's meadow, under the bright moon,
A new module blooms, none too soon.
Web4 dances, with requests it plays,
Crafting HTML in wondrous ways.
Cheers to the coders, with each line they write,
In Rust we trust, by day and night. 🌟
🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

src/web4/handler.rs Outdated Show resolved Hide resolved
Copy link
Collaborator

@Tguntenaar Tguntenaar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LG

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Out of diff range and nitpick comments (3)
src/web4/handler.rs (3)

1-5: Consider grouping the near_sdk::base64 imports into a single line for better readability.

use near_sdk::base64::{alphabet, engine::{self, general_purpose}, Engine};

13-14: The BASE64_ENGINE constant is well-defined, but consider adding a comment to explain its purpose for future maintainability.

/// Base64 engine for encoding HTML responses without padding.
pub const BASE64_ENGINE: engine::GeneralPurpose = engine::GeneralPurpose::new(&alphabet::URL_SAFE, general_purpose::NO_PAD);

30-41: The match statement for handling different paths is clear, but consider adding comments to explain each case for better readability and maintainability.

match (page, path_parts.get(2)) {
    // Handle community path
    ("community", Some(handle)) => {
        if let Some(community) = contract.get_community(handle.to_string()) {
            title = html_escape::encode_text(community.name.as_str()).to_string();
            description = html_escape::encode_text(community.description.as_str()).to_string();
            image = community.logo_url;
        }
        redirect_path = format!("devhub.near/widget/app?page={}&handle={}", page, handle);
        initial_props_json = json!({"page": page, "handle": handle}).to_string();
    }
    // Handle proposal path
    ("proposal", Some(id)) => {
        if let Ok(id) = id.parse::<u32>() {
            if let Some(versioned_proposal) = contract.proposals.get(id.into()) {
                let proposal_body = Proposal::from(versioned_proposal).snapshot.body.latest_version();
                title = html_escape::encode_text(proposal_body.name.as_str()).to_string();
                description = html_escape::encode_text(proposal_body.summary.as_str()).to_string();
            }
        }
        redirect_path = format!("devhub.near/widget/app?page={}&id={}", page, id);
        initial_props_json = json!({"page": page, "id": id}).to_string();
    }
    // Handle unknown paths
    _ => {
        redirect_path = "devhub.near/widget/app".to_string();
        initial_props_json = json!({"page": page}).to_string();
    }
}
Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 92265f6 and b1efce0.
Files selected for processing (1)
  • src/web4/handler.rs (1 hunks)
Additional comments not posted (1)
src/web4/handler.rs (1)

121-480: The tests cover a wide range of scenarios and are well-structured. Ensure that all edge cases are considered, especially for path parsing and metadata setting.

Comment on lines +16 to +18
pub fn web4_get(contract: &Contract, request: Web4Request) -> Web4Response {
let path_parts: Vec<&str> = request.path.split('/').collect();

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The path parsing logic assumes that the path will always contain at least two elements. This assumption might not hold in all cases, leading to potential panics. Consider adding a check to ensure the path has the expected number of elements.

let path_parts: Vec<&str> = request.path.split('/').collect();
if path_parts.len() < 2 {
    return Web4Response::Body {
        content_type: "text/html; charset=UTF-8".to_owned(),
        body: BASE64_ENGINE.encode("Invalid path".to_string()),
    };
}

Comment on lines +63 to +111
let body = format!(
r#"<!DOCTYPE html>
<html>
<head>
<title>{title}</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta property="og:url" content="{url}" />
<meta property="og:type" content="website" />
<meta property="og:title" content="{title}" />
<meta property="og:description" content="{description}" />
<meta property="og:image" content="{image}" />

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="{title}">
<meta name="twitter:description" content="{description}">
<meta name="twitter:image" content="{image}">
<script src="https://ipfs.web4.near.page/ipfs/bafybeic6aeztkdlthx5uwehltxmn5i6owm47b7b2jxbbpwmydv2mwxdfca/main.794b6347ae264789bc61.bundle.js"></script>
<script src="https://ipfs.web4.near.page/ipfs/bafybeic6aeztkdlthx5uwehltxmn5i6owm47b7b2jxbbpwmydv2mwxdfca/runtime.25b143da327a5371509f.bundle.js"></script>
<style>
@media screen and (max-width: 600px) {{
.gatewaylinks .nav-link {{
padding-top: 0px!important;
padding-bottom: 0px!important;
margin: 0px;
}}
.gatewaylinks img {{
height: 30px;
}}
}}
</style>
</head>
<body>
<nav class="navbar navbar-expand-sm navbar-light bg-dark" style="display: flex; flex-wrap: nowrap; padding-left: 5px; padding-right: 5px; height: 73px; border-bottom: rgb(0, 236, 151) solid 5px;">
<a class="navbar-brand" href="/""><img src="https://i.near.social/magic/large/https://near.social/magic/img/account/devhub.near" style="height: 68px" /></a>
<p class="nav-text" style="flex-grow: 1"></p>
<p class="nav-text text-light" style="margin-top: 1rem; margin-right: 1rem">Choose your gateway</p>
<div class="navbar-nav gatewaylinks">
<a href="https://near.org/{redirect_path}" class="nav-link">
<img src="https://ipfs.web4.near.page/ipfs/bafybeia2ptgyoz7b6oxu3k57jmiras2pgigmw7a3cp6osjog67rndmf36y/nearorg.svg" />
</a>
<a href="https://near.social/{redirect_path}" class="nav-link">
<img src="https://ipfs.web4.near.page/ipfs/bafybeia2ptgyoz7b6oxu3k57jmiras2pgigmw7a3cp6osjog67rndmf36y/nearsocial.svg" />
</a>
</div>
</nav>
<near-social-viewer src="devhub.near/widget/app" initialProps='{initial_props_json}'></near-social-viewer>
</body>
</html>"#,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The HTML response construction is well-structured, but consider extracting the HTML template into a separate function or constant for better readability and maintainability.

const HTML_TEMPLATE: &str = r#"<!DOCTYPE html>
<html>
<head>
    <title>{title}</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <meta property="og:url" content="{url}" />
    <meta property="og:type" content="website" />
    <meta property="og:title" content="{title}" />
    <meta property="og:description" content="{description}" />
    <meta property="og:image" content="{image}" />
    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:title" content="{title}">
    <meta name="twitter:description" content="{description}">
    <meta name="twitter:image" content="{image}">
    <script src="https://ipfs.web4.near.page/ipfs/bafybeic6aeztkdlthx5uwehltxmn5i6owm47b7b2jxbbpwmydv2mwxdfca/main.794b6347ae264789bc61.bundle.js"></script>
    <script src="https://ipfs.web4.near.page/ipfs/bafybeic6aeztkdlthx5uwehltxmn5i6owm47b7b2jxbbpwmydv2mwxdfca/runtime.25b143da327a5371509f.bundle.js"></script>
    <style>
        @media screen and (max-width: 600px) {{
            .gatewaylinks .nav-link {{
                padding-top: 0px!important;
                padding-bottom: 0px!important;
                margin: 0px;
            }}
            .gatewaylinks img {{
                height: 30px;
            }}
        }}
    </style>
</head>
<body>
<nav class="navbar navbar-expand-sm navbar-light bg-dark" style="display: flex; flex-wrap: nowrap; padding-left: 5px; padding-right: 5px; height: 73px; border-bottom: rgb(0, 236, 151) solid 5px;">
    <a class="navbar-brand" href="/""><img src="https://i.near.social/magic/large/https://near.social/magic/img/account/devhub.near" style="height: 68px" /></a>
    <p class="nav-text" style="flex-grow: 1"></p>
    <p class="nav-text text-light" style="margin-top: 1rem; margin-right: 1rem">Choose your gateway</p>
    <div class="navbar-nav gatewaylinks">
        <a href="https://near.org/{redirect_path}" class="nav-link">
            <img src="https://ipfs.web4.near.page/ipfs/bafybeia2ptgyoz7b6oxu3k57jmiras2pgigmw7a3cp6osjog67rndmf36y/nearorg.svg" />
        </a>
        <a href="https://near.social/{redirect_path}" class="nav-link">
            <img src="https://ipfs.web4.near.page/ipfs/bafybeia2ptgyoz7b6oxu3k57jmiras2pgigmw7a3cp6osjog67rndmf36y/nearsocial.svg" />
        </a>
    </div>
</nav>
<near-social-viewer src="devhub.near/widget/app" initialProps='{initial_props_json}'></near-social-viewer>
</body>
</html>"#;

let body = HTML_TEMPLATE
    .replace("{title}", &title)
    .replace("{url}", &redirect_path)
    .replace("{description}", &description)
    .replace("{image}", &image)
    .replace("{redirect_path}", &redirect_path)
    .replace("{initial_props_json}", &initial_props_json);

@frol frol merged commit 19c15a3 into NEAR-DevHub:main May 16, 2024
1 check passed
@petersalomonsen petersalomonsen deleted the feat/web4-social-media-links branch May 16, 2024 15:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants