Работа с веб-каналами социальных сетей в SharePoint

Узнайте о распространенных задачах программирования для работы с социальными каналами и публикациями микроблогов в SharePoint.

API для работы с веб-каналами социальных параметров в SharePoint

В локальных фермах SharePoint интерактивные социальные каналы предназначены для того, чтобы побудить людей делиться информацией и оставаться на связи с людьми и содержимым. You can see many of the feed features on the Newsfeed page on a user's personal site. Feeds contain collections of threads that represent microblog posts, conversations, status updates, and other notifications.

SharePoint предоставляет следующие API- интерфейсы, которые можно использовать для программной работы с социальными каналами:

  • Клиентские объектные модели для управляемого кода

    • Клиентская объектная модель .NET

    • Клиентская объектная модель Silverlight

    • Клиентская объектная модель для мобильных устройств.

  • Объектная модель JavaScript

  • Служба передачи репрезентативного состояния (REST).

  • Объектная модель сервера

Согласно передовой практике в разработке SharePoint, используйте клиентские интерфейсы API, когда это возможно. Client APIs include the client object models, the JavaScript object model, and the REST service. Дополнительные сведения об API в SharePoint и их использовании см. в статье Выбор правильного набора API в SharePoint.

Each API includes a manager object that you use to perform core feed-related tasks. Table 1 shows the manager and other key objects (or REST resources) in the APIs and the class library (or endpoint URI) where you can find them.

Примечание.

[!Примечание] The Silverlight and mobile client object models are not explicitly mentioned in Table 1 or Table 2 because they provide the same core functionality as the .NET client object model and use the same signatures. The Silverlight client object model is defined in Microsoft.SharePoint.Client.UserProfiles.Silverlight.dll, and the mobile client object model is defined in Microsoft.SharePoint.Client.UserProfiles.Phone.dll.

Таблица 1. API SharePoint, используемые для программной работы с социальными каналами

API Ключевые объекты
Клиентская объектная модель .NET
См. статью Практическое руководство. Создание и удаление записей и получение веб-канала социальных сетей с помощью клиентской объектной модели .NET в SharePoint
Объект Manager: SocialFeedManager
Основное пространство имен: Microsoft.SharePoint.Client.Social
Другие ключевые объекты: SocialFeed , SocialThread , SocialPost , SocialPost , SocialPostCreationData , SocialFeedOptions , SocialActor
Библиотека классов: Microsoft.SharePoint.Client.UserProfiles.dll
Объектная модель JavaScript
См . статью Практическое руководство. Создание и удаление записей и получение веб-канала социальных ролей с помощью объектной модели JavaScript в SharePoint
Объект Manager: SocialFeedManager
Основное пространство имен: SP. Социальных
Другие ключевые объекты: SocialFeed, SocialThread, SocialPost, SocialPost, SocialPostCreationData, SocialFeedOptions, SocialActor
Библиотека классов: SP.UserProfiles.js
Служба REST
См. статью Практическое руководство. Обучение чтению и записи в веб-канал социальных ленты с помощью службы REST в SharePoint
Ресурс manager: social.feed (SocialRestFeedManager)
Основное пространство имен (OData): SP. Социальных
Другие ключевые ресурсы: SocialFeed, SocialRestFeed, SocialThread, SocialRestThread, SocialPost, SocialPostCreationData, SocialRestPostCreationData, SocialFeedOptions, SocialActor, SociaRestActor
Точка доступа: <siteUri>/_api/social.feed
Объектная модель сервера
Примечание. Код, который использует серверную объектную модель для доступа к данным веб-канала и выполняется удаленно, должен использовать объект SPServiceContextScope .
Объект manager: SPSocialFeedManager
Основное пространство имен: Microsoft.Office.Server.Social
Другие ключевые объекты: SPSocialFeed , SPSocialThread , SPSocialPost , SPSocialFeedOptions , SPSocialActor
Библиотека классов: Microsoft.Office.Server.UserProfiles.dll

Если вы используете серверную объектную модель для доступа к содержимому веб-канала и код не выполняется в экземпляре SharePoint (иными словами, если расширение не установлено в папке LAYOUTS на сервере приложений), используйте в коде объект SPServiceContextScope . The following code example shows one way to incorporate the SPServiceContextScope object into your code.


using (SPSite site = new SPSite(<siteURL>))
{
    using (new Microsoft.SharePoint.SPServiceContextScope(SPServiceContext.GetContext(site)))
    {
        // code
    }
}

Распространенные задачи программирования для работы с социальными каналами в SharePoint

Table 2 shows common programming tasks for working with social feeds and the members that you use to perform them. Members are from the .NET client object model (CSOM), JavaScript object model (JSOM), REST service, and server object model (SSOM).

Табл. 2. API для распространенных задач программирования для работы с социальными каналами в SharePoint

Задача Участники
Create an instance of the manager object in the context of the current user CSOM: SocialFeedManager
JSOM: SocialFeedManager
REST: GET<siteUri>/_api/social.feed
SSOM: SPSocialFeedManager
Create an instance of the manager object in the context of a particular user CSOM: не реализовано
JSOM: не реализовано
REST: не реализовано
SSOM: SPSocialFeedManager
Get the user for the current context CSOM: Владелец
JSOM: владелец
REST: GET<siteUri>/_api/social.feed/my
SSOM: Владелец
Get the feed for the current user
(specify the feed type)
CSOM: GetFeed
JSOM: getFeed
REST: GET<siteUri>/_api/social.feed/my/Feed (личный feed.md), <siteUri>/_api/social.feed/my/News, <siteUri>/_api/social.feed/my/TimelineFeedили <siteUri>/_api/social.feed/my/Likes
SSOM: GetFeed
Get the personal feed for a particular user CSOM: GetFeedFor
JSOM: getFeedFor
REST: GET<siteUri>/_api/social.feed/actor(item='domain\\user')/Feed
SSOM: GetFeedFor
Get the site feed for a team site
(укажите URL-адрес веб-канала сайта в качестве субъекта (например, http://< siteCollection>/<teamSite>/newsfeed.aspx))
CSOM: GetFeedFor
JSOM: getFeedFor
REST: GET<siteUri>/_api/social.feed/actor(item=@v)/Feed?@v='http://<siteCollection>/<teamSite>/newsfeed.aspx'
SSOM: GetFeedFor
Publish a root post to the current user's feed
(specify null for the target)
CSOM: CreatePost
JSOM: createPost
REST: POST<siteUri>/_api/social.feed/my/Feed/Post и передайте параметр restCreationData в тексте запроса.
SSOM: CreatePost
Publish a post to a site feed
(укажите URL-адрес веб-канала сайта в качестве целевого (например, http://< siteCollection>/teamSite>/newsfeed.aspx))
CSOM: CreatePost
JSOM: createPost
REST: POST<siteUri>/_api/social.feed/actor(item=@av)/feed/post/?@av='<teamSiteUri>/newsfeed.aspx' и передайте параметр restCreationData в тексте запроса (укажите null для параметра ID ).
SSOM: CreatePost
Publish a reply to a post
(specify the ID of the target thread)
CSOM: CreatePost
JSOM: createPost
REST: POST<siteUri>/_api/social.feed/Post/Reply и передайте параметр restCreationData в тексте запроса.
SSOM: CreatePost
Delete a post, reply, or thread in the current user's feed (deleting a root post deletes the whole thread) CSOM: DeletePost
JSOM: deletePost
REST: POST<siteUri>/_api/social.feed/Post/Delete и передача параметра ID в тексте запроса
SSOM: DeletePost
Get a thread (a root post and all its replies) from the user's feed CSOM: GetFullThread
JSOM: getFullThread
REST: POST<siteUri>/_api/social.feed/Post и передача параметра ID в тексте запроса
SSOM: GetFullThread
Have the user like (unlike) a post or reply CSOM: LikePost ( UnlikePost )
JSOM: likePost ( unlikePost)
REST: POST<siteUri>/_api/social.feed/Post/Like ( <siteUri>/_api/social.feed/Post/Unlike) и передача параметра ID в тексте запроса
SSOM: LikePost ( UnlikePost )
Get all likers for a post CSOM: GetAllLikers
JSOM: getAllLikers
REST: POST<siteUri>/_api/social.feed/Post/Likers и передача параметра ID в тексте запроса
SSOM: GetAllLikers
Get the posts that mention a user CSOM: GetMentions
JSOM: getMentions
REST: GET<siteUri>/_api/social.feed/my/MentionFeed
SSOM: GetMentions
Get the number of unread mentions for the current user CSOM: GetUnreadMentionCount
JSOM: getUnreadMentionCount
REST: GET<siteUri>/_api/social.feed/my/UnreadMentionCount
SSOM: GetUnreadMentionCount
Lock (unlock) a thread in the current user's feed CSOM: LockThread ( UnlockThread )
JSOM: lockThread ( unlockThread)
REST: POST<siteUri>/_api/social.feed/Post/Lock ( <siteUri>/_api/social.feed/Post/Unlock) и передача параметра ID в тексте запроса
SSOM: LockThread ( UnlockThread .md)

Примечание.

Значение заполнителя "домен\пользователь " в примере REST должно быть заменено именем учетной записи фактического пользователя. To see how to pass a REST parameter in a request body, see the examples in the Social feed REST API reference.

SharePoint не предоставляет API для настройки макета или отрисовки записей микроблога напрямую. SharePoint предоставляет только данные и позволяет кроссплатформенным и междоменным клиентским приложениям определять макеты, соответствующие их форм-факторам и потребностям. При разработке для SharePoint можно использовать переопределения JavaScript для отрисовки на стороне клиента, как описано в разделе Настройка представления списка в надстройках SharePoint с помощью отрисовки на стороне клиента.

Overview of feed types in the Личный сайт API

Feed types represent slices of feed data. When you retrieve a feed for the current user, you can specify one of the following feed types:

  • Personal contains the posts and updates that are generated from a user. On Личный сайт, this feed is shown on a user's About me page.

  • News contains the posts and updates that are generated from the current user and from the people and the content that the user is following. When you retrieve the News feed type, use the ByModifiedTime sort order option to get the most recent (cached) activities from the people who the user is following. On Личный сайт, this feed is shown on a user's Newsfeed page.

  • Timeline contains the posts and updates that are generated from the current user and from the people and the content that the user is following. Timeline is particularly useful when you want feed data from a specific time range or when you want to sort with the ByCreatedTime option (which includes the largest sampling of people).

  • Likes contains reference threads with a PostReference property that represents a post that the current user has flagged with the Like attribute.

  • Everyone contains the threads from the current user's whole organization.

The server, client, and JavaScript object models provide the GetFeed method that you can use to retrieve any feed type for the current user and the GetFeedFor method that you can use to retrieve the Personal feed type (only) for a specified user. Both methods take a SocialFeedOptions object as a parameter, which you use to specify the time-based sort order, date range, and maximum number of threads to return.

Примечание.

[!Примечание] The REST service provides separate resources to retrieve each feed type, as shown in Table 2.

If a thread contains more than two replies, the server returns a digest of the thread that contains only the two most recent replies. (Для дайджестов потоков применяется атрибут потока IsDigest .) Если вы хотите получить все ответы в потоке, вызовите метод GetFullThread из объекта диспетчера канала и передайте идентификатор потока.

См. также