Giter VIP home page Giter VIP logo

Comments (1)

opsdemon avatar opsdemon commented on July 26, 2024

For anyone who's interested, here's the code I ended up using to create a post with an image from the page's metatags using Jsoup and commons-io FileUtils:

import java.io.IOException;
import java.net.URL;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import org.apache.commons.io.FileUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Document;
import com.echobox.api.linkedin.client.VersionedLinkedInClient;
import com.echobox.api.linkedin.client.DefaultVersionedLinkedInClient;
import com.echobox.api.linkedin.version.Version;
import com.echobox.api.linkedin.types.urn.URN;
import com.echobox.api.linkedin.types.urn.URNEntityType;
import com.echobox.api.linkedin.types.posts.Post;
import com.echobox.api.linkedin.types.posts.Distribution;
import com.echobox.api.linkedin.types.images.InitializeUploadRequestBody;
import com.echobox.api.linkedin.types.images.InitializeUpload;
import com.echobox.api.linkedin.connection.versioned.VersionedPostConnection;
import com.echobox.api.linkedin.connection.versioned.VersionedImageConnection;
import com.echobox.api.linkedin.util.PostUtils;

import static com.echobox.api.linkedin.types.images.InitializeUploadRequestBody.*;

    // Pattern to detect URLs in strings
    private static final String URL_REGEX = "\\(?\\b(https?://|www[.])[-A-Za-z0-9+&@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&@#/%=~_()|]";
    private static final Pattern urlPattern = Pattern.compile(URL_REGEX);

    private static final int READ_TIMEOUT = 10000;
    private static final int CONNECT_TIMEOUT = 5000;

    private URN organizationURN;
    private VersionedPostConnection postConnection;
    private VersionedImageConnection imageConnection;

    public void init(String organizationId, String accessToken) throws IOException
    {
        VersionedLinkedInClient client = new DefaultVersionedLinkedInClient(accessToken, Version.DEFAULT_VERSION);
        postConnection = new VersionedPostConnection(client);
        imageConnection = new VersionedImageConnection(client);
        organizationURN = new URN(URNEntityType.ORGANIZATION, organizationId);
    }

    public String sendPost(String text) throws IOException
    {
        String link = extractUrl(text);

        // Crawl the link's page to get the metatags
        URL url = new URL(link);
        Document doc = Jsoup.parse(url, READ_TIMEOUT);
        List<Element> tags = doc.getElementsByTag("meta");
        String title = getMetatag(tags, "og:title");
        String description = getMetatag(tags, "og:description");
        String image = getMetatag(tags, "og:image");

        // Download the image file
        String filename = image.substring(image.lastIndexOf("/")+1);
        File file = File.createTempFile("image-", null);
        FileUtils.copyURLToFile(new URL(image), file, CONNECT_TIMEOUT, READ_TIMEOUT);

        // Upload the image file and delete the downloaded file
        InitializeUploadRequest request = new InitializeUploadRequest(organizationURN);
        URN imageURN = imageConnection.uploadImage(new InitializeUploadRequestBody(request), filename, file);
        file.delete();

        // Create the post and send it
        Distribution distribution = new Distribution(Distribution.FeedDistribution.MAIN_FEED);
        Post post = new Post(organizationURN, text, distribution,
            Post.LifecycleState.PUBLISHED, Post.Visibility.PUBLIC);
        PostUtils.fillArticleContent(post, link, imageURN, title, description);
        URN postURN = postConnection.createPost(post);
        return postURN.getId();
    }

    private String getMetatag(List<Element> tags, String name)
    {
        String ret = null;
        for(Element tag : tags)
        {
            String attr = tag.attr("property");
            if(attr != null && attr.equals(name))
            {
                ret = tag.attr("content");
                break;
            }
        }

        return ret;
    }

    private String extractUrl(String text)
    {
        Matcher m = urlPattern.matcher(text);
        return m.find() ? m.group() : null;
    }

from ebx-linkedin-sdk.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.