package com.tubeilike.service;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import com.google.gdata.client.youtube.YouTubeQuery;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.VideoFeed;
import com.google.gdata.util.ServiceException;
import com.tubeilike.entity.Tube;
import com.tubeilike.entity.TubesFeed;
public class TubeService {
private static int itemPerPage = 12;
public static YouTubeService service = new YouTubeService("tubeilike"); // can
// change
// service
// name.
public static TubesFeed searchByKey(String key, int page, int type) {
TubesFeed result = new TubesFeed();
List<Tube> listTube = new ArrayList<Tube>();
System.out.println("Searching...");
try {
YouTubeQuery query = new YouTubeQuery(new URL(
"https://gdata.youtube.com/feeds/api/videos"));
query.setFullTextQuery(key);
query.setMaxResults(itemPerPage);
query.setStartIndex(itemPerPage * page);
query.setSafeSearch(YouTubeQuery.SafeSearch.NONE);
VideoFeed videoFeed = service.query(query, VideoFeed.class);
result.setTotalResult(videoFeed.getTotalResults());
result.setCurrentPage(page);
for (VideoEntry videoEntry : videoFeed.getEntries()) {
Tube tub = new Tube();
tub.transformHalfVideoEntry(videoEntry);
listTube.add(tub);
}
} catch (MalformedURLException e) {
System.out.println("Error when searching with key : + " + key);
e.printStackTrace();
} catch (IOException e) {
System.out.println("Error when searching with key : + " + key);
e.printStackTrace();
} catch (ServiceException e) {
System.out.println("Error when searching with key : + " + key);
e.printStackTrace();
}
result.setListTube(listTube);
return result;
}
public static Tube searchById(String id, boolean fullContent) {
Tube tub = new Tube();
try {
System.out.println("Update from youtube : " + id);
String videoEntryUrl = "http://gdata.youtube.com/feeds/api/videos/"
+ id;
VideoEntry videoEntry = service.getEntry(new URL(videoEntryUrl),
VideoEntry.class);
if (fullContent) {
tub.transformVideoEntry(videoEntry);
} else {
tub.transformHalfVideoEntry(videoEntry);
}
tub.setViewCount(0);
return tub;
} catch (MalformedURLException e) {
System.out.println("Error when searching with id : + " + id);
e.printStackTrace();
} catch (IOException e) {
System.out.println("Error when searching with id : + " + id);
e.printStackTrace();
} catch (ServiceException e) {
System.out.println("Error when searching with id : + " + id);
e.printStackTrace();
}
return tub;
}
}