IMDb Search

Search on imdb.com

目前為 2015-10-20 提交的版本,檢視 最新版本

// ==UserScript==
// @name         IMDb Search
// @version      1
// @description  Search on imdb.com
// @author       FuSiOn
// @match        https://*/*
// @match        http://*/*
// @require      http://code.jquery.com/jquery-latest.js
// @grant        GM_xmlhttpRequest
// @namespace https://greasyfork.org/users/10999
// ==/UserScript==

var IMDb = function(title,year,section,callback,item,retry) {
	section  = section || "movies"
    retry    = retry || false;	
    var GetInfo = function(result, item) {
        GM_xmlhttpRequest({
            method: "GET",
            url: result,
            onload: function(response) {
                if (response.status == 200) {
					if(/\/combined$/.test(response.finalUrl)){
						console.log('Please disable the setting "Always display full cast and crew credits" in your account.');
						return;
					}
                    var responseData = response.responseText.match(/<div id="title-overview-widget">[\w\W]+?<\/tbody>[\w\W]+?<\/table>[\w\W]+?<\/div>/i)[0]
											   			    .replace(/(<img[\w\W]+?src)="http:\/\/ia\.media-imdb\.com([^"]+")/g, '$1New="$2'),
                        Info = {
                            "Title":  	   $('.header [itemprop="name"]',responseData).text(),
							"Year":		   $('.header .nobr',responseData).text().replace(/\(|\)/g,""),
							"ID":     	   result.match(/tt\d+/)[0],
                            "Rating": 	   $('span[itemprop="ratingValue"]', responseData).text(),
                            "Count":  	   $('span[itemprop="ratingCount"]', responseData).text(),
                            "Genre":  	   "",
                            "URL":    	   result,
							"Poster": 	   "http://ia.media-imdb.com" + $('img[alt*="Poster"]',responseData).attr('srcNew'),
							"Trailer":	   typeof($("[itemprop=trailer]",responseData).attr("href")) == 'undefined' ? '' : "http://imdb.com" + $("[itemprop=trailer]",responseData).attr("href"),
							"InWatchList": null,
							"InLists":	   null,
							"Description": $('[itemprop="description"]', responseData).text(),
							"Stars":	   $('[itemprop="actors"] a', responseData)
                        },
                        logged = /nblogout/.test(response.responseText);
                    $('span[itemprop="genre"]', responseData).each(function() {
                        if (Info.Genre !== "") {
                            Info.Genre += " | ";
                        }
                        Info.Genre += $(this).text();
                    });
					if(logged){
						GM_xmlhttpRequest({
							method:  "POST",
							url:     "http://www.imdb.com/list/_ajax/watchlist_has",
							data:    "consts%5B%5D=" + Info.ID + "&tracking_tag=wlb-lite",
							headers:    {
								"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
							},
							onload:  function(response) {
								if(response.status == 200){
									var obj = JSON.parse(response.responseText);
									if(obj.status === 200){
										if(typeof(obj.has[Info.ID]) !== "undefined"){
											Info.InWatchList = true;
										}else Info.InWatchList = false;
										GM_xmlhttpRequest({
											method:  "POST",
											url:     "http://www.imdb.com/list/_ajax/wlb_dropdown",
											data:    "tconst=" + Info.ID,
											headers:    {
												"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
											},
											onload:  function(response) {
												if(response.status == 200){
													var obj = JSON.parse(response.responseText);
													if(obj.status === 200){
														obj.items.forEach(function(item){
															if(item.data_list_item_ids != null){
																if(Info.InLists == null) Info.InLists = [];
																Info.InLists.push(item.data_list_id)
															}
														})	
														setIMDB(Info, item);
													}
												}
											}
										}); 								  
									}
								}
							}
						});   
					}else setIMDB(Info, item);
                }
            }
        });
    };
    var setIMDB = function(Info, item) {
		if(typeof(callback) != 'function'){
			console.log(Info)
			return;
		}
		callback(Info,item);
    };
	if(!/^tt\d+$/.test(title)){
		(function() {
			GM_xmlhttpRequest({
				method: "GET",
				url: "http://akas.imdb.com/find?ref_=nv_sr_fn&s=all&q=" + encodeURIComponent(title) + ((section === "tv")? "&ttype=tv":"&ttype=ft"),
				onload: function(response) {
					if (response.status == 200) {
						if (!/<a name="tt"><\/a>[\w\W]+?<\/table>/i.test(response.responseText)) {
							if (/No results found for/.test(response.responseText)) {
								console.log("IMDB_Search: No result found for:", title, year);
							} else {
								console.log("IMDB_Search: A unknown error has occured:", title, year);
							}
							return;
						}
						var responseData = response.responseText.match(/<a name="tt"><\/a>[\w\W]+?<\/table>/i)[0]
												   .replace(/(<img[\w\W]+?src=)"[^"]+"/g, '$1""'),
							selector = {
								 "movies" :'.findResult:containsX("' + title + '"):not(:containsI("(video game)"),:containsI("(tv episode)"),:containsI("(tv series)"),:containsI("(tv mini-series)"),:containsI("(short)"))',
								 "tv":'.findResult:containsX("' + title + '"):containsI("(TV Series)"),.findResult:containsX("' + title + '"):containsI("(tv series)"),.findResult:containsX("' + title + '"):containsI("(tv mini-series)")',
								 "console": '.findResult:containsX("' + title + '"):containsI("(Video Game)")'
							},
							result,
							results = $(selector[section], responseData);
						if (results.length > 0) {
							if (results.length > 1) {
								if (year) {
									if (results.find(":contains('" + year + "')").length === 0) {
										if (results.find(":contains('" + (parseInt(year) - 1) + "')").length === 0) {
											results = results.find(":contains('" + (parseInt(year) + 1) + "')");
										}else{
											results = results.find(":contains('" + (parseInt(year) - 1).toString() + "')");
										}
									} else {
										results = results.find(":contains('" + year + "')");
									}
								}
								if (results.length > 0) {
									$('small',results[0]).remove();
									result = $(results[0]).find("a").attr("href").replace(/(.+)?\?.+$/, "http://imdb.com$1");
									GetInfo(result, item);
								} else {
									console.log("IMDB_Search: ", "Found no match with the given query and year:", title, year);
								}
							} else {
								$('small',results[0]).remove();
								result = $(results[0]).find("a").attr("href").replace(/(.+)?\?.+$/, "http://imdb.com$1");
								GetInfo(result, item);
							}
						} else {
							if ($('.findResult', responseData).length === 1) {
								results = $('.findResult', responseData);
								$('small',results[0]).remove();
								result = $(results[0]).find("a").attr("href").replace(/(.+)?\?.+$/, "http://imdb.com$1");
								GetInfo(result, item);
							} else {
								if(section === 'movies' && retry === false && /[\[(][^\])]+[\])]/.test(title)){
									IMDB(title.replace(/[\[(][^\])]+[\])]/,""), year, item,true);
								}else{
									console.log("IMDB_Search: ", "Found no match with the given query:", title, year);
								}
							}
						}
					} else {
						console.log(response.status + " " + response.statusText);
					}
				}
			});
		})();
	}else{
		GetInfo("http://www.imdb.com/title/" + title,item);
	}
};
unsafeWindow.IMDb = IMDb;

$.expr[":"].containsI = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().trim().toUpperCase()
                .indexOf(arg.trim().toUpperCase()) >= 0;
    };
});       
$.expr[":"].containsX = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().trim()
                .replace(/\s\([IVX]+\)\s/," ")
                .replace(/\sII(?:\s|$)/g,"2")
                .replace(/\sIII(?:\s|$)/g,"3")
                .replace(/\sIV(?:\s|$)/g,"4")
                .replace(/\sV(?:\s|$)/g,"5")
                .replace(/\sVI(?:\s|$)/g,"6")
                .replace(/\sVII(?:\s|$)/g,"7")
                .replace(/\sIIX(?:\s|$)/g,"8")
                .replace(/\sIX(?:\s|$)/g,"9")
                .replace(/\sX(?:\s|$)/g,"10")
				.replace(/the\b|part(?=\s?\d)/ig,"")
                .replace(/and/ig,"&")
                .replace(/äàâ/ig,"A")
                .replace(/ç/ig,"C")
                .replace(/éèëê/ig,"E")
                .replace(/\W/g,"")
                .toUpperCase()
                .indexOf(arg.trim().replace(/\sII(?:\s|$)/g,"2")
                                   .replace(/\sIII(?:\s|$)/g,"3")
                                   .replace(/\sIV(?:\s|$)/g,"4")
                                   .replace(/\sV(?:\s|$)/g,"5")
                                   .replace(/\sVI(?:\s|$)/g,"6")
                                   .replace(/\sVII(?:\s|$)/g,"7")
                                   .replace(/\sIIX(?:\s|$)/g,"8")
                                   .replace(/\sIX(?:\s|$)/g,"9")
                                   .replace(/\sX(?:\s|$)/g,"10")     
						 		   .replace(/the\b|part(?=\s?\d)|p(?=\d)|3d/ig,"")
                                   .replace(/and/ig,"&")
                                   .replace(/äàâ/ig,"A")
                                   .replace(/ç/ig,"C")
                                   .replace(/éèëê/ig,"E")
                                   .replace(/\W/g,"")
                                   .toUpperCase()) >= 0;
    };
});