Tải bản đầy đủ (.docx) (23 trang)

Báo cáo tìm hiểu WEB API

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (600.19 KB, 23 trang )

Báo cáo đề tài tìm hiểu
Web API -Youtube API
N-L-S
Báo cáo giới thiệu sơ bộ về web api, cách sử dụng chung cho một web api và cuối cùng là giới thiệu một
web api cụ thể (Youtube API).
Thành viên:
− Nguyễn Quốc Nhã – 0912317
− Huỳnh Văn Lộc - 0912268
− Châu Hoàn Sơn – 0912392
Mục lục:
I. Web API
1. Khái niệm 3

2. Tương tác 3

3. Tại sao sử dụng 3

4. Hỗ trợ - đóng gói 4
2 | P a g e
II. Cách sử dụng chung
1. Đối với Web API dạng Link 4
2. Đối với WEB API dạng SDK 4
3. Đối với dạng Thư viện Java Script 5
III. Youtube API
1. Giới thiệu chung 6
2. Một số api mà youtube hỗ trợ (v2/.Net)
1. Xác thực tài khoản 7
2. Video feed và entry 7
3. Truy xuất và tìm kiếm video 10
4. Upload video 14
5. Cập nhật và xoá video 15


6. Sử dụng tính năng cộng đồng 16
7. Lưu trữ và thu thập video 17
8. Kích hoạt tương tác người dùng 19
9. Xử lý theo lô 21
3 | P a g e
I. Web API:
1. Khái niệm:
− API: Application Programming Interface: (Giao diện lập trình ứng dụng): là 1 dạng
thể hiện, giúp phát triển ứng dụng 1 cách dễ dàng qua việc hỗ trợ rất nhiều những
hoạt động / dịch vụ giúp cho người dùng có thể tương tác với hệ thống. Việc tương
tác đó có thể được định nghĩa qua các hàm, các tham số, các biến có liên quan đến hệ
thống chính.
VD: Window có các API để tương tác với các service của hệ thống, các phần mềm
mặc định.
− Web API: Tương tự như API, WEB API cung cấp cho người dùng 1 dạng các thể
hiện, giúp cho người dùng có thể tương tác được với dịch vụ được cung cấp trên web.
Người dùng thông qua API để sử dụng các dịnh vụ đó.
VD: các hàm, các giao thức, gói tin gửi đi, các URL,
2. Tương tác:
WEB API là hệ thống thiết lập các thông điệp dạng HTTP, NET/TCP, để gửi lên web, sau đó
nhận các thông điệp phản hồi về (thường là dạng JSON, XML có cấu trúc rõ ràng).
3. Tại sao sử dụng:
− Nguyên nhân hình thành các dịch vụ web:
• Hệ thống Internet ngày càng phát triển, phần mềm sử dụng hệ thống internet càng
nhiều
• 1 số phần mềm đòi hỏi về lượng thông tin lớn, dữ liệu lớn, nên không thể lưu
trực tiếp tại thiết bị sử dụng.
• 1 số loại xử lý cần được cập nhật realtime (theo thời gian thực) để đảm bảo sự
đúng đắn của thông tin (chứng khoán, tiền tệ, giá cả, ngân hàng, )
• 1 số phần mềm đòi hỏi xử lý nhanh và mạnh, mà các thiết bị lại không thể thực

hiện được do cấu hình không đủ.
• Các dịch vụ mạng xã hội, cần sự giao tiếp với rất nhiều người cùng lúc
− Thông thường, để sử dụng các dịch vụ đó thì người dùng cần dùng trình duyệt, truy
cập web và thực hiện.Nhưng họ chỉ có thể sử dụng các giao diện mà nhà cung cấp họ
thiết kế sẵn, có thể rườm rà, rắc rối. Lúc đó thì họ lại nghĩ đến việc tự viết 1 ứng
dung, có thể thực hiện các thao tác như giao diện trên web đó, nhưng được tùy chỉnh
cho dễ sử dụng hơn, giao diện đẹp hơn, chạy nhanh hơn các trình duyệt web (tránh
load những phần thừa), thì họ phải sử dụng những dịch vụ riêng biệt để tương tác
với hệ thống cung cấp các dịch vụ trên, nói cách khác là phải sử dụng Web API.
 Đó là nguyên nhân chính dẫn đến việc sử dụng web API.
4. Hỗ trợ - Đóng gói:
WEB API thường được cung cấp dưới các dạng sau:
4 | P a g e
− Địa chỉ web của API.Mỗi API sẽ có địa chỉ web tương ứng. Ta truy vấn các địa chỉ này và các
tham số truyền vào để sử dụng.
VD: Google map: />Google Translator: />Yahoo! Map Service: />− Các thư viện động: Web API được đóng gói trong 1 bộ thư viện. Khi sử dụng thì ta gọi các
hàm trong đó để sử dung, tương tác với dịch vụ ở trên Net.
VD: Facebook SDK, Youtube Data API
− Các thư viện Javascript để dùng cho việc sử dụng Web API nhúng vào trong website của
người dùng (có dạng gần giống với cách sử dụng địa chỉ web API)
VD: Google, Youtube, Youtube Player API,
II. Cách sử dụng chung:
1. Đối với Web API dạng Link:
− Ta sử dụng các http request để thực hiện việc truy vấn đến web service và nhận dữ
liệu.
− Các http Request là các link tương ứng từng dịch vụ mà hệ thống đó hỗ trợ. Ta truyền
vào các tham số, sau đó dùng nó để truy vấn lên hệ thống trên Web. Hệ thống sẽ xử lý
và trả về kết quả.
VD: đoạn code sau sẽ truy vấn lên Yahoo API, tìm và lấy “Tên” của tỉnh ở tọa độ
Kinh độ, Vĩ độ được truyền vào. Kết quả trả về là 1 file Json, trong đó có tên của

tỉnh cần lấy.
publicWebClient webClient;
Uri uri = newUri(" /> + [kinh độ] + "+" + [vĩ độ]);
webClient.DownloadStringAsync(uri);
2. Đối với WEB API dạng SDK:
− Ta download và cài đặt các SDK đó vào máy.
− Add reference file dll vao project sau đó sử dụng các đối tượng và phương thức
cung cấp để thực hiện các thao tác cần thiết
VD: Đoạn code sau dùng để tìm kiếm video trên youtube:
- YouTubeQuery query
=newYouTubeQuery(YouTubeQuery.DefaultVideoUri);
//order results by the number of views (most viewed first)
query.OrderBy="viewCount";
// search for puppies and include restricted content in the search results
// query.SafeSearch could also be set to
YouTubeQuery.SafeSearchValues.Moderate
5 | P a g e
query.Query="puppy";
query.SafeSearch=YouTubeQuery.SafeSearchValues.None;
Feed<Video> videoFeed = request.Get<Video>(query);
printVideoFeed(videoFeed);
3. Đối với dạng Thư viện Java Script:
− Ta sử dụng chính các link đến Web API đó để lấy thông tin, khởi tạo các giá trị cho
đối tượng và thực hiện.
VD: đoạn code sau thực hiện việc hiên thị giao diện của Google map, hiển thị
map và các phím control trên trình duyệt. Trong đây, ta sử dụng link đến Google
Map API để lấy file javascript, sử dụng nó để hiển thị bản đồ với các thông số
tương ứng.
6 | P a g e
III. Youtube API

1. Giới thiệu chung
− Như chúng ta đã biết, Youtube hiện hay đang là website chia sẻ video hàng đầu của
thế giới.Số lượt sử dụng hàng ngày của Youtube đến hơn 200.000 lượt (thống kê
2010). Người dùng Youtube có thể đăng tải các video, comment, lưu video vào danh
sách ưa thích, tạo page riêng, và nhiều ứng dụng khác nữa.
− Để giúp cho Youtube ngày càng phát triển, họ đã đưa ra bộ công cụ, giúp cho người
dùng có thể dễ dàng thực hiện các thao tác đã nêu trên 1 cách dễ dàng trên ứng dụng
riêng của họ, đó chính là Youtube API.
− Để sử dụng Youtube API, người dùng chỉ cần sử dụng các thẻ HTMl và Javascript là
có thể đưa các đoạn Video, các thao tác Comment hay Upload và chính ứng dụng web
của mình.
− Youtube Api hiện nay cung cấp cho người dùng 2 dạng: Data API và Player API.
1. Data API
• Data API cho phép người dùng có thể thực hiện nhiều thao tác tương tự trên
website Youtube: Upload video, Sửa đổi danh sách ưa thích, tìm kiếm,
comment, đánh giá,
2. Player API:
• Player API là 1 dạng API cho phép người dùng nhúng đoạn video vào trong
trang web của họ.
7 | P a g e
• Người dùng có thể xem Video, có thể thực hiện các thao tác Play, Pause,
Stop, tăng giảm âm lượng, trực tiếp từ web của họ mà không phải thông qua
Youtube.
2. Một số api mà youtube hỗ trợ (v2/.Net)
1. Xác thực tài khoản
DeveloperKey: />YouTubeRequestSettings settings =
newYouTubeRequestSettings("example app", developerKey);
YouTubeRequest request =newYouTubeRequest(settings);
1. Video feed và entry
1.1 Hiện video feed

Feed<Video> videoFeed = request.Get<Video>(new Uri(feedUrl));
printVideoFeed(videoFeed);
static void printVideoFeed(Feed<Video> feed)
{
foreach (Video entry in feed.Entries)
{
printVideoEntry(entry); //xem mục 1.3 video entry contents
}
}
8 | P a g e
1.2 Truy xuất video entry qua id
Uri videoEntryUrl=
newUri(" />Video video = request.Retrieve<Video>(videoEntryUrl);
printVideoEntry(videoEntry);
1.3 Nội dung của video entry
staticvoid printVideoEntry(Video video)
{
Console.WriteLine("Title: "+ video.Title);
Console.WriteLine(video.Description);
Console.WriteLine("Keywords: "+ video.Keywords);
Console.WriteLine("Uploaded by: "+ video.Uploader);
if(video.YouTubeEntry.Location!=null)
{
Console.WriteLine("Latitude: "+ video.YouTubeEntry.Location.Latitude);
Console.WriteLine("Longitude: "+ video.YouTubeEntry.Location.Longitude);
}
if(video.Media!=null&& video.Media.Rating!=null)
9 | P a g e
{
Console.WriteLine("Restricted in: "+ video.Media.Rating.Country);

}
if(video.IsDraft)
{
Console.WriteLine("Video is not live.");
string stateName = video.Status.Name;
if(stateName =="processing")
{
Console.WriteLine("Video is still being processed.");
}
elseif(stateName =="rejected")
{
Console.Write("Video has been rejected because: ");
Console.WriteLine(video.Status.Value);
Console.Write("For help visit: ");
Console.WriteLine(video.Status.Help);
}
elseif(stateName =="failed")
{
Console.Write("Video failed uploading because:");
Console.WriteLine(video.Status.Value);
Console.Write("For help visit: ");
Console.WriteLine(video.Status.Help);
}
if(video.ReadOnly==false)
{
Console.WriteLine("Video is editable by the current user.");
}
if(video.RatingAverage!=-1)
{
Console.WriteLine("Average rating: "+ video.RatingAverage);

}
if(video.ViewCount!=-1)
{
Console.WriteLine("View count: "+ video.ViewCount);
}
Console.WriteLine("Thumbnails:");
foreach(MediaThumbnail thumbnail in video.Thumbnails)
{
Console.WriteLine("\tThumbnail URL: "+ thumbnail.Url);
10 | P a g e
Console.WriteLine("\tThumbnail time index: "+ thumbnail.Time);
}
Console.WriteLine("Media:");
foreach(Google.GData.YouTube.MediaContent mediaContent in video.Contents)
{
Console.WriteLine("\tMedia Location: "+ mediaContent.Url);
Console.WriteLine("\tMedia Type: "+ mediaContent.Format);
Console.WriteLine("\tDuration: "+ mediaContent.Duration);
}
}
2. Truy xuất và tìm kiếm video
2.1 Truy xuất feed theo chuẩn
*Lấy feed theo feed id
/>Feed Name Feed Identifier
Most Viewed most_viewed
Top Rated top_rated
Recently Featured recently_featured
Watch On Mobile watch_on_mobile
Most Discussed most_discussed
Top Favorites top_favorites

Most Responded most_responded
Most Recent most_recent
*Lấy feed theo tên vùng và loại:
/>feedID_CATEGORY_NAME
vd: />11 | P a g e
(Standard:mostpopular)
Feed<Video> videoFeed =request.GetStandardFeed(YouTubeQuery.MostPopular);
printVideoFeed(videoFeed);
2.2 Truy xuất video feed upload bởi người dùng
/> /> (lấy feed dựa vào quyền user đã
chứng thực)
(user: GoogleDevelopers)
Uri uri =new
Uri(" />Feed<Video> videoFeed = request.Get<Video>(uri);
printVideoFeed(videoFeed);
2.3 Lấy những video liên quan
12 | P a g e
Uri videoEntryUrl =
newUri(" />Video video = request.Retrieve<Video>(videoEntryUrl);
Feed<Video> relatedVideos = request.GetRelatedVideos(video);
printVideoFeed(relatedVideos)
2.4 Tìm kiếm video
(từ khoá: puppy)
YouTubeQuery query =newYouTubeQuery(YouTubeQuery.DefaultVideoUri);
//order results by the number of views (most viewed first)
query.OrderBy="viewCount";
// search for puppies and include restricted content in the search results
// query.SafeSearch could also be set to YouTubeQuery.SafeSearchValues.Moderate
query.Query="puppy";
query.SafeSearch=YouTubeQuery.SafeSearchValues.None;

Feed<Video> videoFeed = request.Get<Video>(query);
printVideoFeed(videoFeed);
( />q=keyword&safeSearch=none&orderby=viewCount)
13 | P a g e
*Tìm kiếm video sử dụng category và keyword
(loại: news, sports, football)
YouTubeQuery query =newYouTubeQuery(YouTubeQuery.DefaultVideoUri);
AtomCategory category1
=newAtomCategory("News",YouTubeNameTable.CategorySchema);
AtomCategory category2
=newAtomCategory("sports",YouTubeNameTable.KeywordSchema);
AtomCategory category3
=newAtomCategory("football",YouTubeNameTable.KeywordSchema);
query.Categories.Add(newQueryCategory(category1));
query.Categories.Add(newQueryCategory(category2));
query.Categories.Add(newQueryCategory(category3));
Feed<Video> videoFeed = request.Get<Video>(query);
printVideoFeed(videoFeed);
YouTubeQuery query =newYouTubeQuery(YouTubeQuery.DefaultVideoUri);
AtomCategory category1
=newAtomCategory("News",YouTubeNameTable.CategorySchema);
AtomCategory category2
=newAtomCategory("sports",YouTubeNameTable.KeywordSchema);
AtomCategory category3
=newAtomCategory("football",YouTubeNameTable.KeywordSchema);
query.Categories.Add(newQueryCategory(category1));
query.Categories.Add(newQueryCategory(category2.UriString,QueryCategoryOperator.
OR));
query.Categories.Add(newQueryCategory(category3));
14 | P a g e

Feed<Video> videoFeed = request.Get<Video>(query);
printVideoFeed(videoFeed);
*Tìm kiếm video sử dụng developer tag
YouTubeQuery query =newYouTubeQuery(YouTubeQuery.DefaultVideoUri);
AtomCategory category
=newAtomCategory("uploaded_on_example.com",YouTubeNameTable.DeveloperTagS
chema);
query.Categories.Add(newQueryCategory(category));
YouTubeFeed videoFeed = service.Query(query);
printVideoFeed(videoFeed);
3. Upload video
3.1 Upload trực tiếp
Video newVideo =newVideo();
newVideo.Title="My Test Movie";
newVideo.Tags.Add(newMediaCategory("Autos",YouTubeNameTable.CategorySchema
));
newVideo.Keywords="cars, funny";
newVideo.Description="My description";
newVideo.YouTubeEntry.Private=false;
newVideo.Tags.Add(newMediaCategory("mydevtag, anotherdevtag",
YouTubeNameTable.DeveloperTagSchema));
newVideo.YouTubeEntry.Location=newGeoRssWhere(37,-122);
// alternatively, you could just specify a descriptive string
// newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");
newVideo.YouTubeEntry.MediaSource=newMediaFileSource("c:\\file.mov",
"video/quicktime");
Video createdVideo = request.Upload(newVideo);
3.2 Upload dựa vào trình duyệt
Video newVideo =newVideo();
newVideo.Title="My Test Movie";

newVideo.Tags.Add(newMediaCategory("Autos",YouTubeNameTable.CategorySchema
));
newVideo.Keywords="cars, funny";
15 | P a g e
newVideo.Description="My description";
newVideo.YouTubeEntry.Private=false;
newVideo.Tags.Add(newMediaCategory("mydevtag, anotherdevtag",
YouTubeNameTable.DeveloperTagSchema));
newVideo.YouTubeEntry.Location=newGeoRssWhere(37,-122);
// alternatively, you could just specify a descriptive string
// newVideo.YouTubeEntry.setYouTubeExtension("location", "Mountain View, CA");
FormUploadToken token = request.CreateFormUploadToken(newVideo);
Console.WriteLine(token.Url);
Console.WriteLine(token.Token);
3.3 Kiểm tra trạng thái upload
if(video.IsDraft)
{
Console.WriteLine("Video is not live.");
string stateName = video.Status.Name;
if(stateName =="processing")
{
Console.WriteLine("Video is still being processed.");
}
elseif(stateName =="rejected")
{
Console.Write("Video has been rejected because: ");
Console.WriteLine(video.Status.Value);
Console.Write("For help visit: ");
Console.WriteLine(video.Status.Help);
}

elseif(stateName =="failed")
{
Console.Write("Video failed uploading because:");
Console.WriteLine(video.Status.Value);
Console.Write("For help visit: ");
Console.WriteLine(video.Status.Help);
}
4. Cập nhật và xoá video
*Cập nhật thông tin video
video.Description="new description";
Video updatedVideo = request.Update(video);
*Xoá video
request.Delete(video);
16 | P a g e
5. Sử dụng tính năng cộng đồng
5.1 Đánh giá video
video.Rating = 5;
request.Insert(video.RatingsUri, video);
5.2 Comment
*Truy xuất video comment
Feed comments = request.GetComments(v);
foreach (Comment c in comments.Entries)
{
Console.WriteLine(c.Content);
}
*Thêm comment
Comment c = new Comment();
c.Content = "This is my comment.";
request.AddComment(video, c);
// retrieve the comments for the video

Feed fc = request.GetComments(video);
List comments = new List(fc.Entries);
// create a reply to the third comment
Comment c = comments[2];
Comment reply = new Comment();
reply.ReplyTo(c);
reply.Content = "This is the reply text";
request.AddComment(video, reply);
5.3 Video Response
*Truy xuất video responses
Uri videoEntryUrl =
new Uri(" />Video video = request.Retrieve<Video>(videoEntryUrl);
Feed<Video> responses = request.GetResponseVideos(video);
printVideoFeed(responses);
*Thêm video response
request.Insert(video.ResponseUri, responseVideo);
17 | P a g e
request.Insert(videoFeed, responseVideo);
*Xoá video response
request.Delete(responseVideo);
5.4 Đánh đấu video
Complaint c =newComplaint();
c.Type=ComplaintEntry.ComplaintType.PORN;
c.Content="This video offends my better sensibilities.";
request.Insert(video.ComplaintUri, c);
6. Lưu trữ và thu thập video
6.1 Video yêu thích
*Truy xuất video yêu thích của người dùng
Feed<Video> feed = request.GetFavoriteVideo(username);
printVideoFeed(videoFeed);

*Thêm video yêu thích
string videoEntryUrl = " />YouTubeEntry videoEntry = (YouTubeEntry) service.Get(videoEntryUrl);
service.Insert(new Uri(feedUrl), videoEntry);
*Xoá video yêu thích
request.Delete(favoriteVideo);
6.2 Playlist
*Truy xuất playlist của người dùng
Feed<Playlist> userPlaylists =request.GetPlaylistsFeed(username);
foreach(Playlist p in userPlaylists.Entries)
{
Console.WriteLine("Title: "+ p.Title);
Console.WriteLine(p.Summary);
Console.WriteLine("Number of entries: "+ p.CountHint);
}
*Truy xuất thông tin playlist
Feed<PlayListMember> list = request.GetPlaylist(p);
foreach (Video v in list.Entries)
{
18 | P a g e
printVideoEntry(v);
}
*Thêm playlist
Playlist pl =newPlaylist();
pl.Title="this is the title";
pl.Summary="this is my new playlist";
Playlist createdPlaylist = request.Insert(
newUri(" pl);
*Cập nhật playlist
pl.Summary = "updated summary";
request.Update(pl);

+Thêm video vào playlist
// For Playlist object p
PlayListMember pm =newPlayListMember();
// Insert <id> or <videoid> for video here
pm.Id= VIDEOID;
request.AddToPlaylist(p, pm);
+Sửa thông tin của playlist
// move PlayListMember pm to the top of the playlist
pm.Position=1;
request.Update(pm);
+Xoá video trong playlist
request.Delete(playListMember);
*Xoá playlist
request.Delete(playlist);
6.3 Subscription
*Lấy subscription của người dùng
string feedUrl =
" />YouTubeQuery query = new YouTubeQuery(feedUrl);
SubscriptionFeed subFeed = service.GetSubscriptions(query);
foreach (SubscriptionEntry entry in subFeed.Entries)
{
Console.WriteLine("Title: " + entry.Title.Text);
19 | P a g e
Console.WriteLine(entry.Content.Src.Content);
}
*Thêm subscription
Subscription s =newSubscription();
s.Type=SubscriptionEntry.SubcriptionType.channel;
s.UserName="GoogleDevelopers";
request.Insert(newUri(YouTubeQuery.CreateSubscriptionUri(null)), s);

+Theo dõi 1 danh sách các video yêu thích
Subscription s =newSubscription();
s.Type=SubscriptionEntry.SubcriptionType.favorites;
s.UserName="GoogleDevelopers";
request.Insert(newUri(YouTubeQuery.CreateSubscriptionUri(null)), s);
+Theo dõi playlist
Subscription s =newSubscription();
s.Type=SubscriptionEntry.SubcriptionType.playlist;
string playlistId ="586D322B5E2764CF";
s.PlaylistId= playlistId;
request.Insert(newUri(YouTubeQuery.CreateSubscriptionUri(null)), s);
+Theo dõi theo từ khoá tìm kiếm
Subscription s =newSubscription();
s.Type=SubscriptionEntry.SubcriptionType.query;
s.QueryString="puppies";
request.Insert(newUri(YouTubeQuery.CreateSubscriptionUri(null)), s);
*Xoá subscription
request.Delete(s);
7. Kích hoạt tương tác người dùng
7.1 Profile
*Truy xuất profile của người dùng
string feedUrl =" />ProfileEntry profile =(ProfileEntry) service.Get(feedUrl);
Console.WriteLine("Username : "+ profile.UserName);
Console.WriteLine("Age : "+ profile.Age);
Console.WriteLine("Gender : "+ profile.Gender);
Console.WriteLine("Single? : "+ profile.Relationship);
Console.WriteLine("Books : "+ profile.Books);
Console.WriteLine("Company : "+ profile.Company);
20 | P a g e
Console.WriteLine("Description: "+ profile.Description);

Console.WriteLine("Hobbies : "+ profile.Hobbies);
Console.WriteLine("Hometown : "+ profile.Hometown);
Console.WriteLine("Location : "+ profile.Location);
Console.WriteLine("Movies : "+ profile.Movies);
Console.WriteLine("Music : "+ profile.Music);
Console.WriteLine("Job : "+ profile.Occupation);
Console.WriteLine("School : "+ profile.School);
Console.WriteLine("Subscriber count: "+ profile.Statistics.SubscriberCount);
Console.WriteLine("View count: "+ profile.Statistics.ViewCount);
Console.WriteLine("Watch count: "+ profile.Statistics.WatchCount);
Console.WriteLine("Last web access: "+ profile.Statistics.LastWebAccess);
7.2 Contacts
*Truy xuất contact của người dùng
string feedUrl =" />YouTubeQuery query =newYouTubeQuery(feedUrl);
FriendsFeed friendFeed = service.GetFriends(query);
foreach(FriendsEntry entry in friendFeed.Entries)
{
Console.WriteLine("Username: "+ entry.UserName);
Console.WriteLine("Status: "+ entry.Status);
}
*Thêm contact
string feedUrl =" />FriendsEntry newFriend =newFriendsEntry();
newFriend.UserName="GoogleDevelopers";
newFriend.Categories.Add(newAtomCategory("Cool
Dudes",YouTubeNameTable.FriendsCategorySchema));
service.Insert(newUri(feedUrl), newFriend);
*Chấp nhận hoặc từ chối contact
entry.Status="accepted";
entry.Update();
entry.Status="rejected";

entry.Update();
*Xoá contact
friendEntry.Delete();
21 | P a g e
7.3 Messages
*Truy xuất tin nhắn
string feedUrl =" />YouTubeQuery query =newYouTubeQuery(feedUrl);
MessageFeed messagesFeed = service.GetMessages(query);
foreach(MessageEntry entry in messagesFeed.Entries)
{
Console.WriteLine("Message from: "+ entry.Authors[0].Name);
Console.WriteLine("Subject: "+ entry.Title.Text);
Console.WriteLine(entry.Summary.Text);
Console.WriteLine("Attached video: "+ entry.AlternateUri.Content);
}
*Gửi tin nhắn
string friendsInbox =" receivingUser
+"/inbox";
string videoEntryUrl =" />YouTubeEntry videoEntry =(YouTubeEntry) service.Get(videoEntryUrl);
MessageEntry newMessage =newMessageEntry();
newMessage.Title.Text="My Subject";
newMessage.Summary.Text="This is the message body.";
newMessage.Id= videoEntry.Id;
service.Insert(newUri(friendsInbox), newMessage);
*Xoá tin nhắn
entry.Delete();
8. Xử lý theo lô (batch processing)
YouTubeRequestSettings settings =newYouTubeRequestSettings("NETUnittests",
this.ytClient,this.ytDevKey,this.ytUser,this.ytPwd);
YouTubeRequest request =newYouTubeRequest(settings);

// Retrieve the user's playlists feed and create a list of playlists
Feed<Playlist> playlistsFeed = request.GetPlaylistsFeed(null);
List<Playlist> playlists =newList(playlistsFeed.Entries);
// Retrieve a list of the videos in the third playlist in the feed.
// (You could choose another playlist.)
Feed<PlayListMember> playListMembersFeed =
request.GetPlaylist(playlists[2]);
22 | P a g e
List<PlayListMember> playListMembers =
newList<PlayListMember>(playlistsMembersFeed.Entries);
List<PlayListMember> batch =newList<PlayListMember>();
// Delete the third item in the list
toBatch = playListMembers[2];
toBatch.BatchData=newGDataBatchEntryData();
toBatch.BatchData.Id="DELETED_PLAYLIST_ENTRY";
toBatch.BatchData.Type=GDataBatchOperationType.delete;
batch.Add(toBatch);
// Add a video to the playlist
PlayListMember toBatch =newPlayListMember();
// Set videoid to the videoid of video being added to the playlist
toBatch.VideoId= videoid;
toBatch.BatchData=newGDataBatchEntryData();
toBatch.BatchData.Id="NEW_PLAYLIST_ENTRY";
toBatch.BatchData.Type=GDataBatchOperationType.insert;
batch.Add(toBatch);
// Change the second video to be the first video in the playlist
toBatch = playListMembers[1];
toBatch.YouTubeEntry.Position=1;
toBatch.BatchData=newGDataBatchEntryData();
toBatch.BatchData.Id="UPDATED_PLAYLIST_ENTRY";

toBatch.BatchData.Type=GDataBatchOperationType.update;
batch.Add(toBatch);
// Update the list of videos in the playlist by performing the batch operations.
Feed updatedPlayListMembers =
request.Batch(batch, playListMembersFeed);
23 | P a g e

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×