diff --git a/.classpath b/.classpath deleted file mode 100644 index caa633c..0000000 --- a/.classpath +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/.gitignore b/.gitignore index 2cc5405..cac862b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ bin/ **.orig +/.classpath diff --git a/src/com/sharkhunter/channel/CH_plugin.java b/src/com/sharkhunter/channel/CH_plugin.java index 0bc1c63..09402c7 100644 --- a/src/com/sharkhunter/channel/CH_plugin.java +++ b/src/com/sharkhunter/channel/CH_plugin.java @@ -3,23 +3,18 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; - import javax.swing.JComponent; - import org.apache.commons.configuration.ConfigurationException; - +import org.slf4j.LoggerFactory; import com.sun.jna.Platform; - import net.pms.PMS; import net.pms.configuration.PmsConfiguration; import net.pms.dlna.DLNAMediaInfo; import net.pms.dlna.DLNAResource; -import net.pms.dlna.WebStream; import net.pms.dlna.virtual.VirtualFolder; import net.pms.encoders.Player; import net.pms.external.AdditionalFolderAtRoot; @@ -29,9 +24,10 @@ import net.pms.external.StartStopListener; import net.pms.io.OutputParams; -public class CH_plugin implements AdditionalFolderAtRoot, StartStopListener, +public class CH_plugin implements AdditionalFolderAtRoot, StartStopListener, FinalizeTranscoderArgsListener, URLResolver { + private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(CH_plugin.class); private static final long DEFAULT_POLL_INTERVAL=20000; private static boolean initFetchPending=false; private Channels chRoot; @@ -53,7 +49,7 @@ public CH_plugin() { chFolder.mkdir(); path=chFolder.toString(); } - else + else path=confPath; String save=(String)PMS.getConfiguration().getCustomProperty("channels.save"); chRoot=new Channels(path,pluginName,img); @@ -83,7 +79,7 @@ public CH_plugin() { } catch (Exception e) { chRoot.debug("init exp "+e); - PMS.debug("exp "+e) ; + LOGGER.debug("{Channel} Exception: {}", e); } } @@ -95,7 +91,7 @@ private long getInterval() { return l.longValue(); } catch (Exception e) { - PMS.minimal("Illegal interval value "+e.toString()); + LOGGER.warn("{Channel} Illegal interval value \"{}\": {}", interval, e); } } return CH_plugin.DEFAULT_POLL_INTERVAL; @@ -129,12 +125,12 @@ public void nowPlaying(DLNAMediaInfo arg0, DLNAResource arg1) { if(arg1 instanceof ChannelMediaStream) ((ChannelMediaStream)arg1).nowPlaying(); } - + private static String linuxPath(String program) { ProcessBuilder pb=new ProcessBuilder("which",program); return ChannelUtil.execute(pb); } - + public static void unzip(String path,File f) { try { ZipInputStream zis = new ZipInputStream(new FileInputStream(f)); @@ -157,10 +153,10 @@ public static void unzip(String path,File f) { } zis.close(); } catch (Exception e) { - PMS.info("unzip error "+e); + LOGGER.info("{Channel} Unzip error: {}", e); } } - + public static void postInstall() { initFetchPending=true; PMS.getConfiguration().setCustomProperty("channels.path", "extras\\channels"); @@ -200,11 +196,11 @@ else if(Platform.isLinux()) { } catch (ConfigurationException e) { } } - + private void removeArg(List list,String arg) { removeArg(list,arg,false); } - + private void removeArg(List list,String arg,boolean boolOp) { int pos; if((pos=list.indexOf(arg))!=-1) { @@ -216,7 +212,7 @@ private void removeArg(List list,String arg,boolean boolOp) { list.set(pos+1,"copy"); } } - + private void dbgArg(List cmdList) { for(int i=0;i finalizeTranscoderArgs(Player player, String name, ChannelMediaStream cms=(ChannelMediaStream)res; return cms.addStreamvars(cmdList,params); } - + /*public DLNAResource fromPlaylist(String name,String uri,String thumb, String extra,String className) { Channels.debug("call from pl "+name+" "+uri+" "+extra); @@ -253,9 +249,9 @@ public List finalizeTranscoderArgs(Player player, String name, type=ChannelUtil.getFormat(es[1]); if(ChannelUtil.empty(name)) name="Unknown"; - return (new ChannelMediaStream(ch,name,uri,thumb,proc,type,asx,(ChannelScraper)null)); + return (new ChannelMediaStream(ch,name,uri,thumb,proc,type,asx,(ChannelScraper)null)); }*/ - + public static void main(String[] args) { try { PMS.setConfiguration(new PmsConfiguration()); @@ -311,7 +307,7 @@ public static void main(String[] args) { if(ChannelUtil.empty(ChannelUtil.extension(outFile))) outFile=outFile+Channels.cfg().getCrawlFormat(); } - + Thread t=ChannelUtil.newBackgroundDownload(outFile,url); t.start(); threads.add(t); @@ -325,7 +321,7 @@ public static void main(String[] args) { System.out.println("Done"); System.exit(0); } - + private static final String DUMMY_URL = "http://dummy_url.dummy.dummy/"; public DLNAResource create(String arg0) { @@ -351,7 +347,7 @@ public DLNAResource create(String arg0) { return new ChannelMediaStream(tmp[2],tmp[0],ch,format,thumb); } - + public URLResult urlResolve(String url) { URLResult res = new URLResult(); boolean dummyOnly=url.contains(DUMMY_URL); @@ -373,5 +369,5 @@ public URLResult urlResolve(String url) { } return res; } - + } diff --git a/src/com/sharkhunter/channel/Channel.java b/src/com/sharkhunter/channel/Channel.java index 01d0c91..89cfaab 100644 --- a/src/com/sharkhunter/channel/Channel.java +++ b/src/com/sharkhunter/channel/Channel.java @@ -4,68 +4,62 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; -import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.MalformedURLException; -import java.net.Proxy; -import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.regex.Pattern; - import org.apache.commons.io.FileUtils; - -import net.pms.PMS; +import org.slf4j.LoggerFactory; import net.pms.dlna.DLNAResource; import net.pms.dlna.virtual.VirtualFolder; -import net.pms.dlna.virtual.VirtualVideoAction; import net.pms.formats.Format; import net.pms.formats.v2.SubtitleType; import net.pms.network.HTTPResource; public class Channel extends VirtualFolder { - + + private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Channel.class); public boolean Ok; private String name; private int format; - + private ArrayList folders; private ArrayList macros; private ArrayList actions; - + private ChannelCred cred; private ChannelLogin logObj; - + private int searchId; private HashMap searchFolders; - + private String[] subScript; - + private String[] proxies; private ChannelProxy activeProxy; - + private String[] prop; - + private HashMap hdrs; - + private ChannelFolder favorite; private String videoFormat; - + private HashMap vars; private HashMap trashVars; - + private ChannelStreamVars streamVars; - + private SubtitleType embedSubType; private ChannelMatcher subConv; private boolean subConvTimeMs; - + private ArrayList urlResolve; - + public Channel(String name) { super(name,null); Ok=false; @@ -89,7 +83,7 @@ public Channel(String name) { urlResolve=new ArrayList(); Ok=true; } - + public void parse(ArrayList data,ArrayList macros) { folders.clear(); vars.clear(); @@ -138,7 +132,7 @@ public void parse(ArrayList data,ArrayList macros) { if(m!=null) parse(m.getMacro(),macros); else - PMS.debug("unknown macro "+keyval[1]); + LOGGER.debug("{Channel} Unknown macro {}", keyval[1]); } if(keyval[0].equalsIgnoreCase("format")) { format=ChannelUtil.getFormat(keyval[1],format); @@ -173,7 +167,7 @@ public void parse(ArrayList data,ArrayList macros) { } mkFavFolder(); } - + private void mkFavFolder() { if(noFavorite()) return; @@ -185,7 +179,7 @@ private void mkFavFolder() { favorite=f; } } - + public void addFavorite(ArrayList data) { if(data.size()<3) return; @@ -208,14 +202,14 @@ public void addFavorite(ArrayList data) { } } } - + public void addFavorite(ChannelFolder cf) { if(cf.Ok) { cf.setIgnoreFav(); favorite.addSubFolder(cf); } } - + public boolean isFavorized(String name) { for(ChannelFolder f : favorite.subfolders()) { if(name.equals(f.getName())) @@ -223,38 +217,38 @@ public boolean isFavorized(String name) { } return false; } - + public String nxtSearchId() { return String.valueOf(searchId++); } - + public ChannelMacro getMacro(String macro) { return ChannelUtil.findMacro(macros, macro); } - + public int getMediaFormat() { return format; } - + public String getThumb() { return thumbnailIcon; } - + public HashMap getHdrs() { return hdrs; } - + public void resolve() { // this.getChildren().clear(); } - + public void discoverChildren(String s) { discoverChildren(); } public void discoverChildren() { discoverChildren(this); } - + public void discoverChildren(DLNAResource res) { final Channel me=this; addChild(new VirtualFolder("Variables",null) { @@ -275,7 +269,7 @@ public void discoverChildren() { ChannelFolder cf=folders.get(i); if(cf.isActionOnly()) continue; - if(cf.isATZ()) + if(cf.isATZ()) addChild(new ChannelATZ(cf)); else if(cf.isSearch()) addChild(new SearchFolder(cf.getName(),cf)); @@ -286,11 +280,11 @@ else if(cf.isSearch()) } } } - + public boolean isRefreshNeeded() { return true; } - + public InputStream getThumbnailInputStream() { try { return downloadAndSend(thumbnailIcon,true); @@ -299,37 +293,37 @@ public InputStream getThumbnailInputStream() { return super.getThumbnailInputStream(); } } - + public void debug(String msg) { Channels.debug(msg); } - + public String name() { return name; } - + public boolean login() { return (logObj!=null); } - + public void addCred(ChannelCred c) { cred=c; if(logObj!=null) logObj.reset(); } - + public String user() { if(cred!=null) return cred.user; return null; } - + public String pwd() { if(cred!=null) return cred.pwd; return null; } - + private ChannelAuth getAuth(ChannelProxy p) { ChannelAuth a=new ChannelAuth(); a.proxy=p; @@ -338,7 +332,7 @@ private ChannelAuth getAuth(ChannelProxy p) { return a; return logObj.getAuthStr(user(),pwd(),a); } - + public ChannelAuth prepareCom() { Channels.setProxyDNS(ChannelUtil.getProperty(prop, "proxy_dns")); if(proxies==null) // no proxy, just regular login @@ -357,13 +351,13 @@ public ChannelAuth prepareCom() { activeProxy=p; return getAuth(p); } - return getAuth(ChannelProxy.NULL_PROXY); + return getAuth(ChannelProxy.NULL_PROXY); } - + public void addSearcher(String id,SearchObj obj) { searchFolders.put(id, obj); } - + public void research(String str,String id,DLNAResource res) { if(id.startsWith("navix:")) { id=id.substring(6); @@ -383,7 +377,7 @@ public void research(String str,String id,DLNAResource res) { if(obj==null) return; obj.search(str, res); - } + } public void searchAll(String str, DLNAResource res) { for(String id : searchFolders.keySet()) { SearchObj sobj = searchFolders.get(id); @@ -391,7 +385,7 @@ public void searchAll(String str, DLNAResource res) { sobj.search(str,res); } } - + public HashMap getSubMap(String realName,int id) { HashMap res=new HashMap(); res.put("url", realName); @@ -407,24 +401,24 @@ public HashMap getSubMap(String realName,int id) { return null; return ChannelNaviXProc.lite(realName,s,res); } - + public boolean noFavorite() { return ChannelUtil.getProperty(prop, "no_favorite")||Channels.noFavorite(); } - + public ChannelFolder favorite() { return favorite; } - + /////////////////////////////////////////////// // Action handling /////////////////////////////////////////////// - + public void addAction(ChannelFolder cf) { debug("adding action "+cf.actionName()); actions.add(cf); } - + public ChannelFolder action(ChannelSwitch swi,String name,String url,String thumb,DLNAResource res,int form) { String action=swi.getAction(); String rUrl=swi.runScript(url); @@ -445,7 +439,7 @@ public ChannelFolder action(ChannelSwitch swi,String name,String url,String thum } return null; } - + public ChannelFolder getAction(String action) { for(int i=0;i children=child.getChildren(); for(int j=0;j vars() { return vars; } - + public String[] trashVar(String var) { return trashVars.get(var); } - + public ChannelStreamVars defStreamVars() { return streamVars; } - + public String embSubExt() { return embedSubType.getExtension(); } - + public SubtitleType getEmbSub() { return embedSubType; } - + public String convSub(String subFile,boolean braviaFix) { if(subConv==null) { if(braviaFix) @@ -537,7 +531,7 @@ public String convSub(String subFile,boolean braviaFix) { return subFile; } } - + private String convSub_i(String subFile,boolean braviaFix) throws IOException { File src=new File(subFile); String oFile=Channels.dataEntry(src.getName()+".srt"+(braviaFix?".bravia":"")); @@ -557,7 +551,7 @@ private String convSub_i(String subFile,boolean braviaFix) throws IOException { continue; if(braviaFix) { // real odd ball trick - // we add a line to the end of each text to pull up the + // we add a line to the end of each text to pull up the // text (and only on BRAVIA) text=ChannelUtil.append(text, "\n", DOTS+"\n"); } @@ -573,7 +567,7 @@ private String convSub_i(String subFile,boolean braviaFix) throws IOException { return ""; } } - + private void parseSubConv(ArrayList data) { for(int i=0;i data) { } } } - - private static final String DOTS = "..."; - + + private static final String DOTS = "..."; + private String braviafySubs(String subFile) { try { File outFile=new File(subFile+".bravia"); @@ -626,7 +620,7 @@ private String braviafySubs(String subFile) { return outFile.getAbsolutePath(); String cp=ChannelUtil.getCodePage(); BufferedReader in=new BufferedReader(new InputStreamReader( - new FileInputStream(subFile),cp)); + new FileInputStream(subFile),cp)); String str; StringBuffer sb=new StringBuffer(); while ((str = in.readLine()) != null) { @@ -645,15 +639,15 @@ private String braviafySubs(String subFile) { } return subFile; } - + ///////////////////////////////////////////////////////// - + private String resolved(DLNAResource r) { ChannelMediaStream cms=(ChannelMediaStream)r; cms.scrape(null); return cms.urlResolve(); } - + public String urlResolve(String url,boolean dummyOnly) { for(ChannelSwitch resolver : urlResolve) { boolean dummy_match=ChannelUtil.getProperty(resolver.getProps(), "dummy_match"); diff --git a/src/com/sharkhunter/channel/ChannelAuth.java b/src/com/sharkhunter/channel/ChannelAuth.java index 57feccd..3ee0e69 100644 --- a/src/com/sharkhunter/channel/ChannelAuth.java +++ b/src/com/sharkhunter/channel/ChannelAuth.java @@ -1,16 +1,14 @@ package com.sharkhunter.channel; -import java.net.Proxy; - public class ChannelAuth { public int method; public String authStr; public long ttd; public ChannelProxy proxy; - + public ChannelAuth() { } - + public ChannelAuth(ChannelAuth a) { method=a.method; authStr=a.authStr; diff --git a/src/com/sharkhunter/channel/ChannelCfg.java b/src/com/sharkhunter/channel/ChannelCfg.java index 3ba7363..ce59371 100644 --- a/src/com/sharkhunter/channel/ChannelCfg.java +++ b/src/com/sharkhunter/channel/ChannelCfg.java @@ -19,11 +19,11 @@ import net.pms.PMS; public class ChannelCfg { - + public static final int PROXY_DNS_NONE=0; public static final int PROXY_DNS_ALL=1; public static final int PROXY_DNS_CHANNEL=2; - + private String chPath; private String saPath; private String rtmpPath; @@ -65,7 +65,7 @@ public class ChannelCfg { private String badUrl; private boolean subBravia; private boolean clearCookies; - + public ChannelCfg(Channels top) { chPath=null; saPath=null; @@ -104,59 +104,59 @@ public ChannelCfg(Channels top) { subBravia=true; clearCookies=false; } - + /////////////////////////////////// // Set methods /////////////////////////////////// - + public void setPath(String p) { chPath=p; } - + public void setSavePath(String p) { saPath=p; } - + public void setRtmpPath(String p) { rtmpPath=p; } - + public void setScriptPath(String p) { scriptPath=p; } - + public void setSopPath(String p) { sopcastPath=p; } - + public void setPPLivePath(String p) { pplivePath=p; } - + public void setPerlPath(String p) { perlPath=p; } - + public void setPythPath(String p) { pythonPath=p; } - + public void setGetFlPath(String p) { get_flPath=p; } - + public void setYouTubePath(String p) { ytPath=p; } - + public void setCookiePath(String p) { cookiePath=p; } - + public void setCredPath(String p) { credPath=p; } - + public void setNaviXUpload(String p) { String[] tmp=p.split(","); navixUploadList=p; @@ -166,41 +166,41 @@ public void setNaviXUpload(String p) { navixUploadList2=tmp[1]; } } - + public void setFavorite(boolean b) { favorite=b; } - + public void setLongSvaeName(boolean b) { longSaveName=b; } - + public void setCrawl(boolean b) { crawl=b; } - + public void setCrawlFL(String str) { setCrawlFL(ChannelCrawl.parseCrawlMode(ChannelCrawl.CRAWL_FLA, str)); } - + public void setCrawlFL(int t) { if(t!=ChannelCrawl.CRAWL_UNKNOWN) crawlFL=t; } - + public void setCrawlHL(String str) { setCrawlHL(ChannelCrawl.parseCrawlMode(ChannelCrawl.CRAWL_HML, str)); } - + public void setCrawlHL(int t) { if(t!=ChannelCrawl.CRAWL_UNKNOWN) crawlHL=t; } - + public void setStdAlone(boolean b) { stdAlone=b; } - + //////////////////////////////////////// // Get methods //////////////////////////////////////// @@ -208,175 +208,175 @@ public void setStdAlone(boolean b) { public String getPath() { return chPath; } - + public String getSavePath() { return saPath; } - + public String getRtmpPath() { return rtmpPath; } - + public String getScriptPath() { return scriptPath; } - + public String getSopPath() { return sopcastPath; } - + public String getPPLivePath() { return pplivePath; } - + public String getPerlPath() { return perlPath; } - + public String getPythonPath() { return pythonPath; } - + public String getFlashPath() { if(ChannelUtil.empty(get_flPath)) return getScriptPath(); return get_flPath; } - + public String getYouTubePath() { if(ChannelUtil.empty(ytPath)) return getScriptPath(); return ytPath; } - + public boolean getCache() { return cache; } - + public String getCookiePath() { return cookiePath; } - + public String getCredPath() { return credPath; } - + public boolean favorite() { return favorite; } - + public String getNaviXUpload() { return navixUploadList; } - + public String getNaviXUpload2() { return navixUploadList2; } - + public boolean noPlay() { return noPlay; } - + public boolean netDiscStyle() { return netDisc; } - + public boolean rawSave() { return rawSave; } - + public boolean allPlay() { return allPlay; } - + public int proxyDNSMode() { return proxyDNSMode; } - + public String proxyDNS() { return proxyDNS; } - + public boolean longSaveName() { return longSaveName; } - + public boolean oldSub() { return oldSub; } - + public String getCurlPath() { return (String) PMS.getConfiguration().getCustomProperty("curl.path"); } - + public boolean mp2Force() { return mp2force; } - + public boolean fileBuffer() { return fileBuffer; } - + public int getCrawlHLMode() { return crawlHL; } - + public int getCrawlFLMode() { return crawlFL; } - + public String getCrawlFormat() { return crawlFormat; } - + public boolean crawl() { return crawl; } - + public boolean stdAlone() { return stdAlone; - } - + } + public boolean monitor() { return monitor; } - + public boolean usePMSEncoder() { return pmsenc; } - + public boolean useStreamVar() { return streamVar; } - + public String nullURL() { return nullUrl; } - + public String badURL() { return badUrl; } - + public boolean subBravia() { return subBravia; } - + public boolean clearCookies() { return clearCookies; } - + //////////////////////////////////////// // Misc. methods //////////////////////////////////////// - + public String scriptFile(String file) { return scriptPath+File.separator+file; } - + ////////////////////////////////////// // Other methods ////////////////////////////////////// - + public void init() { // Paths chPath=Channels.getPath(); @@ -392,7 +392,7 @@ public void init() { cookiePath=(String) PMS.getConfiguration().getCustomProperty("cookie.path"); credPath=(String) PMS.getConfiguration().getCustomProperty("cred.path"); chZipUrl=(String) PMS.getConfiguration().getCustomProperty("channels.ch_zip"); - + // Other String dbg=(String)PMS.getConfiguration().getCustomProperty("channels.debug"); String sub=(String) PMS.getConfiguration().getCustomProperty("channels.subtitles"); @@ -421,10 +421,10 @@ public void init() { String bu=(String)PMS.getConfiguration().getCustomProperty("channels.bad_url"); String bs=(String)PMS.getConfiguration().getCustomProperty("channels.bravia_sub"); String cc=(String)PMS.getConfiguration().getCustomProperty("channels.clear_cookies"); - + if(!ChannelUtil.empty(cf)) crawlFormat=cf; - + if(rtmpMode!=null) { if(rtmpMode.trim().equalsIgnoreCase("1")) Channels.rtmpMethod(Channels.RTMP_MAGIC_TOKEN); @@ -446,11 +446,11 @@ public void init() { Channels.setCache(true); else Channels.setCache(false); - + // Defaults if(ChannelUtil.empty(rtmpPath)) { File plugPath=new File(PMS.getConfiguration().getMplayerPath()); - String ext=(PMS.get().isWindows()?".exe":""); + String ext=(Platform.isWindows()?".exe":""); File f=new File(plugPath.getParent()+File.separator+"rtmpdump"+ext); if(f.exists()&&f.canExecute()) rtmpPath=f.getAbsolutePath(); @@ -543,7 +543,7 @@ private void configPath(String key,String val) { if(!ChannelUtil.empty(val)) PMS.getConfiguration().setCustomProperty(key,val); } - + public void commit() { top.setSave(saPath); top.setPath(chPath); @@ -576,52 +576,52 @@ public void commit() { // PMS.getConfiguration().setCustomProperty("channels.mpeg2_force",String.valueOf(mp2force)); PMS.getConfiguration().setCustomProperty("channels.pmsencoder", String.valueOf(pmsenc)); PMS.getConfiguration().setCustomProperty("channels.stream_var", String.valueOf(streamVar)); - if(!ChannelUtil.empty(navixUploadList)) + if(!ChannelUtil.empty(navixUploadList)) PMS.getConfiguration().setCustomProperty("channels.navix_upload", ChannelUtil.append(navixUploadList,",",navixUploadList2)); PMS.getConfiguration().save(); } catch (Exception e) { } } - + public void ensureCreated(String p) { File f=new File(p); if(!(f.exists()&&f.isDirectory())) f.mkdir(); } - + private void validatePMSEncoder() throws IOException { if(pmsenc) setEngines(); - if(ChannelUtil.empty(scriptPath)) { + if(ChannelUtil.empty(scriptPath)) { ensureCreated("scripts"); scriptPath=new File("scripts").getCanonicalPath().toString(); } else ensureCreated(scriptPath); } - + private void setEngines() { List eng=PMS.getConfiguration().getEnginesAsList(PMS.get().getRegistry()); for(int i=0;i) eng); + PMS.getConfiguration().setEnginesAsList((ArrayList) eng); } - + //////////////////////////////////////////// // Fetch files /////////////////////////////////////////// - + private static final String chList="https://github.com/SharkHunter/Channel/tree/master/channels"; private static final String scList="https://github.com/SharkHunter/Channel/tree/master/scripts"; private static final String chReg="\\s*.*?]+>([^<]+)"; private static final String rawChBase="https://github.com/SharkHunter/Channel/raw/master/channels/"; private static final String rawScBase="https://github.com/SharkHunter/Channel/raw/master/scripts/"; - private static final String pywin="http://sharkhunter-shb.googlecode.com/files/pywin.zip"; - + private static final String pywin="http://sharkhunter-shb.googlecode.com/files/pywin.zip"; + private void fetchFromGit(String list,String raw,String path) throws Exception { URL u=new URL(list); Pattern re=Pattern.compile(chReg); @@ -649,8 +649,8 @@ private void fetchFromGit(String list,String raw,String path) throws Exception { dest.close(); in.close(); } - } - + } + private void fetchPyWinOverlay() throws ConfigurationException { String tmp = (String) PMS.getConfiguration().getCustomProperty("python.pywin_extra"); if(ChannelUtil.empty(tmp)||!tmp.equalsIgnoreCase("true")) { @@ -666,7 +666,7 @@ private void fetchPyWinOverlay() throws ConfigurationException { } public void fetchChannels() { - try { + try { validatePMSEncoder(); // fetch channels fetchFromGit(chList,rawChBase,chPath); @@ -677,13 +677,13 @@ public void fetchChannels() { } catch(Exception e) { Channels.debug("error fetching channels "+e); - } + } } - + /////////////////////////////////////////////////// // Channel Var functions /////////////////////////////////////////////////// - + public void putChVars(String ch,String inst,String var,String val) { String vData=ChannelUtil.append(ch, "@", inst); String putData=vData+"@"+var+"@"+val; @@ -702,7 +702,7 @@ public void putChVars(String ch,String inst,String var,String val) { } if(!found) // new variable pData=putData+","+pData; - putData=pData; + putData=pData; } try { PMS.getConfiguration().setCustomProperty("channels.ch_vars", putData); @@ -710,7 +710,7 @@ public void putChVars(String ch,String inst,String var,String val) { } catch (ConfigurationException e) { } } - + public void chVars(String chName,Channel ch) { if(stdAlone) return; diff --git a/src/com/sharkhunter/channel/ChannelCrawl.java b/src/com/sharkhunter/channel/ChannelCrawl.java index 8afb3c8..0e1dd98 100644 --- a/src/com/sharkhunter/channel/ChannelCrawl.java +++ b/src/com/sharkhunter/channel/ChannelCrawl.java @@ -5,31 +5,30 @@ import java.util.Comparator; import net.pms.dlna.DLNAResource; -import net.pms.dlna.virtual.VirtualVideoAction; public class ChannelCrawl implements Comparator { - + public final static int CRAWL_FLA = 0; public final static int CRAWL_HML = 1; - + public final static int CRAWL_HIGH = 0; public final static int CRAWL_MED = 1; public final static int CRAWL_LOW = 2; public final static int CRAWL_FIRST = 3; public final static int CRAWL_LAST = 4; public final static int CRAWL_ALL = 5; - + public final static int CRAWL_UNKNOWN = -1; - + private final static int MAX_LOOP = 20; - + private boolean allMode; private String name; - + /////////////////////////////////////////////////// // Static parse functions ////////////////////////////////////////////////// - + private static int parseFLA(String str) { if(str.equalsIgnoreCase("first")) return ChannelCrawl.CRAWL_FIRST; @@ -39,7 +38,7 @@ private static int parseFLA(String str) { return ChannelCrawl.CRAWL_LAST; return ChannelCrawl.CRAWL_FIRST; } - + private static int parseHML(String str) { if(str.equalsIgnoreCase("high")) return ChannelCrawl.CRAWL_HIGH; @@ -49,7 +48,7 @@ private static int parseHML(String str) { return ChannelCrawl.CRAWL_LOW; return CRAWL_HIGH; } - + public static int parseCrawlMode(int mainMode,String str) { if(mainMode==CRAWL_FLA) return parseFLA(str); @@ -57,30 +56,30 @@ public static int parseCrawlMode(int mainMode,String str) { return parseHML(str); return CRAWL_UNKNOWN; } - + //////////////////////////////////////////////////////////////// // Rest of class //////////////////////////////////////////////////////////////// - + public ChannelCrawl() { allMode=false; name=null; } - + public boolean allSeen() { return allMode; } - + public String goodName() { return name; } - + public static DLNAResource crawlOneLevel(ArrayList start,int crawlMode) { int pos=-1; int size=start.size(); if(size==0) return null; - + switch(crawlMode) { case CRAWL_LOW: case CRAWL_FIRST: @@ -96,7 +95,7 @@ public static DLNAResource crawlOneLevel(ArrayList start,int crawl default: break; } - + while(pos > -1) { DLNAResource tmp=start.get(pos); if(ChannelUtil.filterInternals(tmp)){ @@ -111,7 +110,7 @@ public static DLNAResource crawlOneLevel(ArrayList start,int crawl } return null; } - + public DLNAResource crawlOne(ArrayList start,int crawlMode) { switch(crawlMode) { case CRAWL_ALL: @@ -122,7 +121,7 @@ public DLNAResource crawlOne(ArrayList start,int crawlMode) { } return crawlOneLevel(start,crawlMode); } - + private ArrayList sortedList(ArrayList list) { ArrayList res=new ArrayList(); for(DLNAResource r : list) { @@ -134,13 +133,13 @@ private ArrayList sortedList(ArrayList list) { Collections.sort(res, this); return res; } - + public DLNAResource crawl(ArrayList start,int[] modes) { ArrayList res=start; DLNAResource res1=null; for(int i=0;i start,int[] modes) { res=(ArrayList) res1.getChildren(); } if(res1 instanceof ChannelPMSSaveFolder) { - // Compensate for the save folder, We know the last one + // Compensate for the save folder, We know the last one // in the save folder is the PLAY option so we use that one res1=crawlOneLevel((ArrayList) res1.getChildren(),CRAWL_LAST); } return res1; } - + public DLNAResource crawl(DLNAResource start,int[] modes) { return crawl((ArrayList) start.getChildren(),modes); } - + private int[] mkModes(String modeStr) { String[] tmp=modeStr.split("\\+"); int[] modes=new int[tmp.length]; @@ -179,7 +178,7 @@ else if(tmp[i].equalsIgnoreCase("hml")) } return modes; } - + private String findMode(DLNAResource r) { if(r instanceof ChannelPMSFolder) { ChannelPMSFolder pmf=(ChannelPMSFolder)r; @@ -190,7 +189,7 @@ private String findMode(DLNAResource r) { } return "FLA"; } - + public DLNAResource startCrawl(ArrayList start,String modeStr) { Channels.debug("do crawl for "+start+ " mode "+modeStr); DLNAResource r=crawl(start, mkModes(modeStr)); @@ -200,7 +199,7 @@ public DLNAResource startCrawl(ArrayList start,String modeStr) { for(int i=0;i start,String modeStr) { // if we get here return what we got return r; } - + public DLNAResource startCrawl(DLNAResource start,String modeStr) { if(ChannelUtil.empty(modeStr)) { modeStr=findMode(start); @@ -234,50 +233,50 @@ public int compare(Object o1, Object o2) { if (s2 == null || s1 == null) { return 0; } - + int lengthFirstStr = s1.length(); int lengthSecondStr = s2.length(); - + int index1 = 0; int index2 = 0; - + while (index1 < lengthFirstStr && index2 < lengthSecondStr) { char ch1 = s1.charAt(index1); char ch2 = s2.charAt(index2); - + char[] space1 = new char[lengthFirstStr]; char[] space2 = new char[lengthSecondStr]; - + int loc1 = 0; int loc2 = 0; - + do { space1[loc1++] = ch1; index1++; - + if (index1 < lengthFirstStr) { ch1 = s1.charAt(index1); } else { break; } } while (Character.isDigit(ch1) == Character.isDigit(space1[0])); - + do { space2[loc2++] = ch2; index2++; - + if (index2 < lengthSecondStr) { ch2 = s2.charAt(index2); } else { break; } } while (Character.isDigit(ch2) == Character.isDigit(space2[0])); - + String str1 = new String(space1); String str2 = new String(space2); - + int result; - + if (Character.isDigit(space1[0]) && Character.isDigit(space2[0])) { Integer firstNumberToCompare = new Integer(Integer .parseInt(str1.trim())); @@ -287,7 +286,7 @@ public int compare(Object o1, Object o2) { } else { result = str1.compareTo(str2); } - + if (result != 0) { return result; } diff --git a/src/com/sharkhunter/channel/ChannelDbg.java b/src/com/sharkhunter/channel/ChannelDbg.java index 355447e..1612320 100644 --- a/src/com/sharkhunter/channel/ChannelDbg.java +++ b/src/com/sharkhunter/channel/ChannelDbg.java @@ -7,25 +7,25 @@ import java.sql.Date; import java.text.SimpleDateFormat; import java.util.Locale; - import org.apache.commons.configuration.ConfigurationException; - +import org.slf4j.LoggerFactory; import net.pms.PMS; import net.pms.configuration.PmsConfiguration; public class ChannelDbg { + private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ChannelDbg.class); private BufferedWriter os; private File f; private SimpleDateFormat sdfHour; private SimpleDateFormat sdfDate; - + public ChannelDbg(File f) { this.f=f; os=null; sdfHour = new SimpleDateFormat("HH:mm:ss.SSS", Locale.US); //$NON-NLS-1$ sdfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US); //$NON-NLS-1$ } - + private void ensureDbgPack() throws ConfigurationException { PmsConfiguration conf=PMS.getConfiguration(); if(conf==null) @@ -42,7 +42,7 @@ private void ensureDbgPack() throws ConfigurationException { conf.setCustomProperty("dbgpack", str); conf.save(); } - + public void start() { if(os!=null) return; @@ -57,7 +57,7 @@ public void start() { os=null; } } - + public void stop() { if(os!=null) { try { @@ -65,19 +65,19 @@ public void stop() { os.close(); debug("Stopped"); } - catch (IOException e) {} + catch (IOException e) {} os=null; } } - + public boolean status() { return (os!=null); } - + public File logFile() { return f; } - + public void debug(String str) { if(os==null) return; @@ -86,7 +86,7 @@ public void debug(String str) { os.write("\n\r"+s+"\n\r"); os.flush(); } catch (IOException e) { - PMS.debug("[Channel]: "+str); + LOGGER.debug("{Channel} {}", str); } } } diff --git a/src/com/sharkhunter/channel/ChannelFolder.java b/src/com/sharkhunter/channel/ChannelFolder.java index 85100ff..0eb179b 100644 --- a/src/com/sharkhunter/channel/ChannelFolder.java +++ b/src/com/sharkhunter/channel/ChannelFolder.java @@ -1,11 +1,8 @@ package com.sharkhunter.channel; -import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; -import java.io.FileInputStream; import java.io.IOException; -import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.Proxy; import java.net.URL; @@ -14,16 +11,13 @@ import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; - import org.apache.commons.lang.StringEscapeUtils; - -import net.pms.PMS; +import org.slf4j.LoggerFactory; import net.pms.dlna.DLNAResource; -import net.pms.dlna.virtual.VirtualFolder; import net.pms.dlna.virtual.VirtualVideoAction; -import net.pms.movieinfo.MovieInfoVirtualFolder; public class ChannelFolder implements ChannelProps, SearchObj{ + private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ChannelFolder.class); public static final int TYPE_NORMAL=0; public static final int TYPE_ATZ=1; public static final int TYPE_EMPTY=2; @@ -33,58 +27,58 @@ public class ChannelFolder implements ChannelProps, SearchObj{ public static final int TYPE_RECURSE=6; public static final int TYPE_SEARCH=7; public static final int TYPE_NAVIX_SEARCH=8; - public static final int TYPE_ACTION=9; + public static final int TYPE_ACTION=9; public static final int TYPE_REMATCH=10; public static final int TYPE_EXEC=11; - + public boolean Ok; - + private String name; private String url; private int format; private int type; private String[] prop; - + private ChannelMatcher matcher; - + private ArrayList subfolders; private Channel parent; private ChannelFolder parentFolder; private ArrayList items; - private ArrayList medias; + private ArrayList medias; private ArrayList switches; - + private int continues; private boolean contAll; - + private String[] sub; - + private String searchId; private String pre_script; private String post_script; private String thumb_script; - + private String hook; private String tag; - + private String proxy; - + private HashMap hdrs; - + private String group; private String imdbId; private String staticThumb; - + private boolean ignoreFav; - + private String actionName; private String[] action_prop; private String videoFormat; - + public ChannelFolder(ArrayList data,Channel parent) { this(data,parent,null); } - + public ChannelFolder(ChannelFolder cf) { Ok=true; type=ChannelFolder.TYPE_NORMAL; @@ -112,7 +106,7 @@ public ChannelFolder(ChannelFolder cf) { action_prop=cf.action_prop; videoFormat=cf.videoFormat; } - + public ChannelFolder(ArrayList data,Channel parent,ChannelFolder pf) { Ok=false; type=ChannelFolder.TYPE_NORMAL; @@ -154,14 +148,14 @@ public ChannelFolder(ArrayList data,Channel parent,ChannelFolder pf) { } Ok=true; } - + private void setSearchId() { searchId=ChannelUtil.getPropertyValue(prop, "search_id"); if(ChannelUtil.empty(searchId)) searchId=parent.nxtSearchId(); parent.addSearcher(searchId, this); } - + public void parse(ArrayList data) { for(int i=0;i data) { if(m!=null) parse(m.getMacro()); else - PMS.debug("unknown macro "+keyval[1]); - } + LOGGER.debug("{Channel} Unknown macro {}", keyval[1]); + } if(keyval[0].equalsIgnoreCase("name")) name=keyval[1]; - if(keyval[0].equalsIgnoreCase("type")) + if(keyval[0].equalsIgnoreCase("type")) type=parseType(keyval[1]); if(keyval[0].equalsIgnoreCase("url")) url=keyval[1]; if(keyval[0].equalsIgnoreCase("format")) { format=ChannelUtil.getFormat(keyval[1],format); - } - if(keyval[0].equalsIgnoreCase("prop")) + } + if(keyval[0].equalsIgnoreCase("prop")) prop=keyval[1].trim().split(","); if(keyval[0].equalsIgnoreCase("matcher")) { if(matcher==null) @@ -268,7 +262,7 @@ public void parse(ArrayList data) { imdbId=keyval[1]; if(keyval[0].equalsIgnoreCase("action_name")) actionName=keyval[1]; - if(keyval[0].equalsIgnoreCase("action_prop")) + if(keyval[0].equalsIgnoreCase("action_prop")) action_prop=keyval[1].trim().split(","); if(keyval[0].equalsIgnoreCase("fallback_video")) videoFormat=ChannelUtil.ensureDot(keyval[1].trim()); @@ -276,80 +270,80 @@ public void parse(ArrayList data) { if(matcher!=null) matcher.processProps(prop); } - + public void setType(int t) { type=t; } - + public int getType() { return type; } - + public String getName() { return name; } - + public String getURL() { return url; } - + public boolean isATZ() { return ((type==ChannelFolder.TYPE_ATZ)||(type==ChannelFolder.TYPE_ATZ_LINK)); } - + public boolean isNaviX() { return (type==ChannelFolder.TYPE_NAVIX)||(type==ChannelFolder.TYPE_NAVIX_SEARCH); } - + public boolean isSearch() { return (type==ChannelFolder.TYPE_SEARCH); } - + public boolean isActionOnly() { return (type==ChannelFolder.TYPE_ACTION); } - + public boolean isFavorized(String name) { return (isFavItem()||parent.isFavorized(name)); } - + public String getProp(String p) { return ChannelUtil.getPropertyValue(prop, p); } - + public boolean getProperty(String p) { return ChannelUtil.getProperty(prop, p); } - + public String[] getPropList() { return prop; } - + public String[] getSubs() { return sub; } - + public String actionName() { return actionName; } - + public void addSubFolder(ChannelFolder f) { subfolders.add(f); f.parentFolder = this; } - + public void setIgnoreFav() { ignoreFav=true; } - + public boolean ignoreFav() { return ignoreFav||parent.noFavorite(); } - + public int getFormat() { return format; } - + private int parseType(String t) { if(t.compareToIgnoreCase("atz")==0) return ChannelFolder.TYPE_ATZ; @@ -373,7 +367,7 @@ private int parseType(String t) { return ChannelFolder.TYPE_EXEC; return ChannelFolder.TYPE_NORMAL; } - + private boolean doContinue(String name,String realUrl) { String cn=ChannelUtil.getPropertyValue(prop, "continue_name"); String cu=ChannelUtil.getPropertyValue(prop, "continue_url"); @@ -396,23 +390,23 @@ private boolean doContinue(String name,String realUrl) { } return false; } - + private class PeekRes { boolean res; String thumbUrl; } - + private PeekRes mkPeekRes(boolean b) { return mkPeekRes(b,""); } - + private PeekRes mkPeekRes(boolean b,String url) { PeekRes r=new PeekRes(); r.res=b; r.thumbUrl=url; return r; } - + private PeekRes peek(String urlEnd,String[] props) { if((type!=ChannelFolder.TYPE_NORMAL)&& (type!=ChannelFolder.TYPE_EMPTY)) // non normal folders are not peekable @@ -448,7 +442,7 @@ private PeekRes peek(String urlEnd,String[] props) { ChannelItem item=items.get(i); ChannelMatcher m=item.getMatcher(); m.startMatch(page); - if(m.match()) + if(m.match()) { // match found String thumb=m.getMatch("thumb",false); return mkPeekRes(true,thumb); @@ -457,9 +451,9 @@ private PeekRes peek(String urlEnd,String[] props) { for(int i=0;i> groups=new HashMap>(); @@ -850,7 +844,7 @@ else if(oldCache) } else { thumb=ChannelUtil.getThumb(thumb, pThumb, parent); - + } parent.debug("matching "+someName+" url "+fUrl+" thumb "+thumb+" group "+group+" imdb "+imdbId); if(ignoreMatch) @@ -878,7 +872,7 @@ else if(oldCache) if (discardDuplicates && !ignoreMatch) { if (uniqueNames.containsKey(someName)) { String uniqueURL = uniqueNames.get(someName); - if (uniqueURL.equalsIgnoreCase(fUrl)) + if (uniqueURL.equalsIgnoreCase(fUrl)) continue; } uniqueNames.put(someName, fUrl); @@ -893,7 +887,7 @@ else if(oldCache) if(!ChannelUtil.empty(cf.group)&&Channels.useGroupFolder()) { ChannelPMSFolder cpf=new ChannelPMSFolder(cf,someName,null,fUrl,thumb); ArrayList groupData=groups.get(cf.group); - if(groupData==null) + if(groupData==null) groupData=new ArrayList(); groupData.add(cpf); groups.put(group, groupData); @@ -955,8 +949,8 @@ public boolean enable() { } if(!groups.isEmpty()) { // we got groups Object[] keySet=groups.keySet().toArray(); - Arrays.sort(keySet); - for(int j=0;j groupData=groups.get(key); ChannelPMSFolder pfold=groupData.get(0); @@ -966,14 +960,14 @@ public boolean enable() { cf1.group=null; // clear group res.addChild(pfold); } - else + else res.addChild(new ChannelGroupFolder(nName+" #"+key,groupData,thumb)); } } } format=form; } - + public String getThumb() { // relic method just return parents thumb if(!ChannelUtil.empty(staticThumb)) return staticThumb; @@ -981,15 +975,15 @@ public String getThumb() { // relic method just return parents thumb return parent.getThumb(); return null; } - + public String separator(String base) { return ChannelUtil.getPropertyValue(prop, base+"_separator"); } - + public boolean onlyFirst() { return ChannelUtil.getProperty(prop, "only_first"); } - + public String append(String base) { return ChannelUtil.getPropertyValue(prop,"append_"+base); } @@ -1009,17 +1003,17 @@ public void search(String searchString, DLNAResource searcher) { } catch (MalformedURLException e) { } } - - - + + + public String thumbScript() { return thumb_script; } - + public Channel getChannel() { return parent; } - + public boolean otherChar(char c) { String p=getProp("locals"); if(!ChannelUtil.empty(p)) { @@ -1029,7 +1023,7 @@ public boolean otherChar(char c) { } return !((c >= 'A' && c <= 'Z')||(c >= 'a' && c <= 'z')); } - + public void addMovieInfo(DLNAResource res,String imdb,String thumb) { if(Channels.useMovieInfo()&& !ChannelUtil.empty(imdb)&& @@ -1037,7 +1031,7 @@ public void addMovieInfo(DLNAResource res,String imdb,String thumb) { res.addChild(new ChannelMovieInfoFolder(imdb,thumb)); } } - + public String rawEntry() { StringBuilder sb=new StringBuilder(); sb.append("folder {\n"); @@ -1054,7 +1048,7 @@ public String rawEntry() { sb.append("type="); sb.append(ChannelUtil.type2str(type)); sb.append("\n"); - + if(matcher!=null) { sb.append("matcher="); sb.append(matcher.regString()); @@ -1099,7 +1093,7 @@ public String rawEntry() { } return sb.toString(); } - + private String mkFavEntry(String urlEnd,String name,String thumb,String imdb) { StringBuilder sb=new StringBuilder(); String realUrl=ChannelUtil.concatURL(url,urlEnd); @@ -1161,9 +1155,9 @@ private String mkFavEntry(String urlEnd,String name,String thumb,String imdb) { } sb.append("\n}\n"); sb.append("\n}\r\n"); - return sb.toString(); + return sb.toString(); } - + public String mkFav(String urlEnd,String name,String thumb,String imdb) { ChannelFolder copy=new ChannelFolder(this); copy.matcher=null; @@ -1174,7 +1168,7 @@ public String mkFav(String urlEnd,String name,String thumb,String imdb) { parent.addFavorite(copy); return mkFavEntry(urlEnd,name,thumb,imdb); } - + public Boolean isFavItem() { return parentFolder != null && parentFolder == parent.favorite(); } @@ -1187,7 +1181,7 @@ public void remove() { if(parentFolder != null) parentFolder.subfolders().remove(this); } - + public void action(DLNAResource res,ChannelFilter filter,String urlEnd, String pThumb,String nName,String imdb,int f) throws MalformedURLException { String[] old_prop=prop; @@ -1201,11 +1195,11 @@ public void action(DLNAResource res,ChannelFilter filter,String urlEnd, prop=old_prop; format=old_format; } - + public String fallBackVideoFormat() { return videoFormat; } - + @Override public boolean escape(String base) { return ChannelUtil.getProperty(prop, base+"_escape"); @@ -1216,26 +1210,26 @@ public boolean escape(String base) { public boolean unescape(String base) { return ChannelUtil.getProperty(prop, base+"_unescape"); } - + public String mangle(String base) { return ChannelUtil.getPropertyValue(prop, base+"_mangle"); } - + //////////////////////////////////////////////////////////////// // Cahceing folders //////////////////////////////////////////////////////////////// - + private File cacheFile() { String n=name; if(url!=null) n=""+url.hashCode(); return new File(Channels.dataPath()+File.separator+parent.name()+"_"+n); } - + public void addCacheClear(DLNAResource res) { addCacheClear(res,cacheFile()); } - + private void addCacheClear(DLNAResource res,final File f) { res.addChild(new VirtualVideoAction("Force update", true) { public boolean enable() { @@ -1244,14 +1238,14 @@ public boolean enable() { } }); } - + private boolean oldCache(String time,File f) { if(time.equals("0")) // never age this entry return false; int t; try { t=Integer.parseInt(time); - + } catch (Exception e) { t=7; } @@ -1261,17 +1255,17 @@ private boolean oldCache(String time,File f) { d.add(Calendar.DATE, t); return c.after(d); } - + private ChannelPMSAllPlay findAllPlay(DLNAResource res,String name) { for(DLNAResource tmp : res.getChildren()) { if(tmp instanceof ChannelPMSAllPlay) { if(tmp.getName().startsWith(name)) return (ChannelPMSAllPlay) tmp; - } + } } return null; } - + private int numberOfMedia(DLNAResource res) { int cnt=0; for(DLNAResource tmp : res.getChildren()) { diff --git a/src/com/sharkhunter/channel/ChannelGUI.java b/src/com/sharkhunter/channel/ChannelGUI.java index 35741ea..31a76fc 100644 --- a/src/com/sharkhunter/channel/ChannelGUI.java +++ b/src/com/sharkhunter/channel/ChannelGUI.java @@ -9,8 +9,6 @@ import java.awt.event.ItemListener; import java.io.File; import java.io.IOException; -import java.util.ArrayList; - import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; @@ -18,18 +16,13 @@ import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; -import javax.swing.JScrollPane; import javax.swing.JSeparator; -import javax.swing.JSplitPane; -import javax.swing.JTable; import javax.swing.JTextField; -import javax.swing.Popup; -import javax.swing.table.DefaultTableModel; - -import net.pms.PMS; +import org.slf4j.LoggerFactory; public class ChannelGUI implements ActionListener, ItemListener{ - + + private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ChannelGUI.class); private ChannelCfg cfg; private Channels root; private JTextField chPath; @@ -48,12 +41,12 @@ public class ChannelGUI implements ActionListener, ItemListener{ private JCheckBox subs; private JCheckBox favorite; private JComponent topComp; - + public ChannelGUI(ChannelCfg cfg,Channels root) { this.cfg=cfg; this.root=root; } - + public JComponent draw() { JPanel top=new JPanel(new BorderLayout(10,10)); JPanel top1=new JPanel(new BorderLayout(10,10)); @@ -132,7 +125,7 @@ public JComponent draw() { favorite.addItemListener(this); commit.setActionCommand("other_commit"); commit.addActionListener(this); - + GridBagConstraints c = new GridBagConstraints(); // 1st the channels path c.fill = GridBagConstraints.BOTH; @@ -158,7 +151,7 @@ public JComponent draw() { c.gridx++; c.weightx=1.0; pathPanel.add(sBrowse,c); - + // 3rd the cred path c.gridx = 0; c.gridy = 2; @@ -170,7 +163,7 @@ public JComponent draw() { c.gridx++; c.weightx=1.0; pathPanel.add(credBrowse,c); - + // NaviXList c.gridx = 0; c.gridy = 3; @@ -179,7 +172,7 @@ public JComponent draw() { c.gridx++; c.weightx=2.0; pathPanel.add(naviText,c); - + // Debug c.gridx = 0; c.gridy = 4; @@ -195,7 +188,7 @@ public JComponent draw() { c.gridy = 6; c.weightx=1.0; pathPanel.add(favorite,c); - + // Sopcast c.gridx = 0; c.gridy = 1; @@ -207,7 +200,7 @@ public JComponent draw() { c.gridx++; c.weightx=1.0; pmsenc.add(sopBrowse,c); - + // PPLive c.gridx = 0; c.gridy = 2; @@ -219,7 +212,7 @@ public JComponent draw() { c.gridx++; c.weightx=1.0; pmsenc.add(ppBrowse,c); - + // Add installation buttons // Channels c.fill = GridBagConstraints.BOTH; @@ -236,7 +229,7 @@ public JComponent draw() { topComp=top; return top; } - + private JFrame cw; @Override @@ -275,7 +268,7 @@ else if(text.equals("credpath")) else if(text.equals("navix")) { String t=naviText.getText(); if(!ChannelUtil.empty(t)&&!t.equals(cfg.getNaviXUpload())) - cfg.setNaviXUpload(t); + cfg.setNaviXUpload(t); } update(); cfg.commit(); @@ -286,7 +279,7 @@ else if(text.equals("navix")) { } else { if(text.equals("other_commit")||text.equals("other_channels")) { - PMS.debug("update channels files"); + LOGGER.debug("{Channel} Update channels files"); pushPaths(); cfg.commit(); if(text.equals("other_channels")) { @@ -302,7 +295,7 @@ else if(text.equals("navix")) { public void itemStateChanged(ItemEvent e) { boolean val=true; Object source = e.getItemSelectable(); - if (e.getStateChange() == ItemEvent.DESELECTED) + if (e.getStateChange() == ItemEvent.DESELECTED) val=false; if(source==dbg) Channels.debug(val); @@ -312,7 +305,7 @@ public void itemStateChanged(ItemEvent e) { cfg.setFavorite(val); cfg.commit(); } - + private void update() { chPath.setText(cfg.getPath()); saPath.setText(cfg.getSavePath()); @@ -326,7 +319,7 @@ private void update() { yt.setText(cfg.getYouTubePath()); credText.setText(cfg.getCredPath()); } - + private void pushPaths() { cfg.setPath(chPath.getText()); cfg.setRtmpPath(rtmp.getText()); @@ -345,5 +338,5 @@ private void pushPaths() { Channels.initNaviX(); } } - + } \ No newline at end of file diff --git a/src/com/sharkhunter/channel/ChannelISO.java b/src/com/sharkhunter/channel/ChannelISO.java index bdba5fe..05f50ed 100644 --- a/src/com/sharkhunter/channel/ChannelISO.java +++ b/src/com/sharkhunter/channel/ChannelISO.java @@ -2,7 +2,6 @@ import java.util.HashMap; import java.util.Locale; -import java.util.Set; public class ChannelISO { private static HashMap special=new HashMap(); @@ -36,16 +35,16 @@ public class ChannelISO { special.put(iso3, iso2); } } - + public static String iso(String someIso,int wantedIso) { - if(someIso.length()==wantedIso) + if(someIso.length()==wantedIso) return someIso; return special.get(someIso); } - + public static boolean equal(String a,String b) { return a.equals(iso(b,a.length())); } - - + + } diff --git a/src/com/sharkhunter/channel/ChannelImageStream.java b/src/com/sharkhunter/channel/ChannelImageStream.java index cd2abf5..a21a083 100644 --- a/src/com/sharkhunter/channel/ChannelImageStream.java +++ b/src/com/sharkhunter/channel/ChannelImageStream.java @@ -1,15 +1,8 @@ package com.sharkhunter.channel; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; -import java.net.URLEncoder; - -import net.pms.PMS; import net.pms.dlna.DLNAMediaInfo; import net.pms.dlna.DLNAResource; import net.pms.formats.Format; @@ -19,7 +12,7 @@ public class ChannelImageStream extends DLNAResource{ private String url; private String thumb; private String auth; - + public ChannelImageStream(String name,String url,String thumb,String auth) { super(Format.IMAGE); this.name=name; @@ -27,39 +20,39 @@ public ChannelImageStream(String name,String url,String thumb,String auth) { this.thumb=thumb; this.auth=auth; } - + public String getName() { return name; } - + public String getSystemName() { return url; } - + public boolean isUnderlyingSeekSupported() { return true; } - + @Override public void resolve() { } - + @Override public boolean isValid() { - checktype(); + resolveFormat(); return true; - + } - + @Override public long length() { return DLNAMediaInfo.TRANS_SIZE; } - + public boolean isFolder() { return false; } - + public InputStream getInputStream() { try { URL urlobj = new URL(url); @@ -67,7 +60,7 @@ public InputStream getInputStream() { //ByteArrayOutputStream bytes = new ByteArrayOutputStream(); URLConnection conn = urlobj.openConnection(); conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.1; sv-SE; rv:1.9.2.3) Gecko/20100409 Firefox/3.6.3"); - if(!ChannelUtil.empty(auth)) + if(!ChannelUtil.empty(auth)) conn.setRequestProperty("Authorization", auth); InputStream in = conn.getInputStream(); return in; diff --git a/src/com/sharkhunter/channel/ChannelItem.java b/src/com/sharkhunter/channel/ChannelItem.java index 4f26de1..e555fce 100644 --- a/src/com/sharkhunter/channel/ChannelItem.java +++ b/src/com/sharkhunter/channel/ChannelItem.java @@ -4,27 +4,27 @@ import java.net.Proxy; import java.net.URL; import java.util.ArrayList; - -import net.pms.PMS; +import org.slf4j.LoggerFactory; import net.pms.dlna.DLNAResource; public class ChannelItem implements ChannelProps{ - + + private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ChannelItem.class); public boolean Ok; - + private Channel parent; private ChannelFolder parentFolder; - + private ChannelMatcher matcher; - + private String url; private String name; private String[] prop; - + private String thumbURL; - + private ArrayList mediaURL; - + public ChannelItem(ArrayList data,Channel parent,ChannelFolder pf) { Ok=false; this.parent=parent; @@ -35,7 +35,7 @@ public ChannelItem(ArrayList data,Channel parent,ChannelFolder pf) { parse(data); Ok=true; } - + public void parse(ArrayList data) { for(int i=0;i data) { if(m!=null) parse(m.getMacro()); else - PMS.debug("unknown macro "+keyval[1]); - } + LOGGER.debug("{Channel} Unknown macro {}", keyval[1]); + } if(keyval[0].equalsIgnoreCase("name")) name=keyval[1]; - if(keyval[0].equalsIgnoreCase("url")) + if(keyval[0].equalsIgnoreCase("url")) url=keyval[1]; - if(keyval[0].equalsIgnoreCase("prop")) + if(keyval[0].equalsIgnoreCase("prop")) prop=keyval[1].trim().split(","); if(keyval[0].equalsIgnoreCase("matcher")) { if(matcher==null) @@ -81,19 +81,19 @@ public void parse(ArrayList data) { if(matcher!=null) matcher.processProps(prop); } - + public boolean autoMedia() { return ChannelUtil.getProperty(prop, "auto_media"); } - + public ChannelMatcher getMatcher() { return matcher; } - + public void match(DLNAResource res) throws MalformedURLException { match(res,"","","",null); } - + public void match(DLNAResource res,String filter,String urlEnd,String backupName, String pThumb) throws MalformedURLException { String u=ChannelUtil.concatURL(url,urlEnd); @@ -142,22 +142,22 @@ public void match(DLNAResource res,String filter,String urlEnd,String backupName } } } - + public String separator(String base) { return ChannelUtil.getPropertyValue(prop, base+"_separator"); } - + public boolean onlyFirst() { return ChannelUtil.getProperty(prop, "only_first"); } - + public String append(String base) { return ChannelUtil.getPropertyValue(prop,"append_"+base); } public String prepend(String base) { return ChannelUtil.getPropertyValue(prop,"prepend_"+base); } - + public String rawEntry() { StringBuilder sb=new StringBuilder(); sb.append("item {"); @@ -192,11 +192,11 @@ public String rawEntry() { sb.append("\n}\n"); return sb.toString(); } - + public String getProp(String p) { return ChannelUtil.getPropertyValue(prop, p); } - + @Override public boolean escape(String base) { return ChannelUtil.getProperty(prop, base+"_escape"); @@ -207,7 +207,7 @@ public boolean escape(String base) { public boolean unescape(String base) { return ChannelUtil.getProperty(prop, base+"_unescape"); } - + public String mangle(String base) { return ChannelUtil.getPropertyValue(prop, base+"_mangle"); } diff --git a/src/com/sharkhunter/channel/ChannelLogin.java b/src/com/sharkhunter/channel/ChannelLogin.java index 7c786b2..e0dc20c 100644 --- a/src/com/sharkhunter/channel/ChannelLogin.java +++ b/src/com/sharkhunter/channel/ChannelLogin.java @@ -8,19 +8,15 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; -import java.util.Date; import java.util.TimeZone; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLSession; -import com.sun.net.ssl.HostnameVerifier; import com.sun.syndication.io.impl.Base64; -import net.pms.PMS; - public class ChannelLogin { - + public static final int STD=0; public static final int COOKIE=1; public static final int APIKEY=2; @@ -44,7 +40,7 @@ public class ChannelLogin { private ChannelSimple pre_fetch; private boolean preFetched; private String activeParams; - + public ChannelLogin(ArrayList data,Channel parent) { this.parent=parent; this.loggedOn=false; @@ -58,7 +54,7 @@ public ChannelLogin(ArrayList data,Channel parent) { activeParams=""; parse(data); } - + public void parse(ArrayList data) { for(int i=0;i data) { } } } - + private String mkQueryString(String usr,String pass) { String usr_pwd=user+"="+ChannelUtil.escape(usr)+ "&"+pwd+"="+ChannelUtil.escape(pass); return ChannelUtil.append(activeParams, "&", usr_pwd); } - + private ChannelAuth mkResult(ChannelAuth a) { if(a==null) a=new ChannelAuth(); @@ -126,7 +122,7 @@ private ChannelAuth mkResult(ChannelAuth a) { a.ttd=ttd; return a; } - + private ChannelAuth stdLogin(String usr,String pass,ChannelAuth a) throws Exception { String query=mkQueryString(usr,pass); //Channels.debug("url "+url+" query "+query); @@ -136,14 +132,14 @@ private ChannelAuth stdLogin(String usr,String pass,ChannelAuth a) throws Except connection = (HttpsURLConnection) u.openConnection(); HttpsURLConnection.setFollowRedirects(true); HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier()); - ((HttpURLConnection) connection).setInstanceFollowRedirects(true); + ((HttpURLConnection) connection).setInstanceFollowRedirects(true); ((HttpURLConnection) connection).setRequestMethod("POST"); } else { connection = (HttpURLConnection) u.openConnection(); HttpURLConnection.setFollowRedirects(true); - ((HttpURLConnection) connection).setInstanceFollowRedirects(true); - ((HttpURLConnection) connection).setRequestMethod("POST"); + ((HttpURLConnection) connection).setInstanceFollowRedirects(true); + ((HttpURLConnection) connection).setRequestMethod("POST"); } String page=ChannelUtil.postPage(connection, query); //PMS.debug("got page after post "+page); @@ -159,7 +155,7 @@ private ChannelAuth stdLogin(String usr,String pass,ChannelAuth a) throws Except } return null; } - + private ChannelAuth updateCookieDb(String cookie,ChannelAuth a) { String u=ChannelUtil.trimURL(url); Channels.debug("update cookie db "+u); @@ -175,7 +171,7 @@ private ChannelAuth updateCookieDb(String cookie,ChannelAuth a) { Channels.mkCookieFile(); return a; } - + private long parseTTD(String expStr,SimpleDateFormat sdfDate) throws ParseException { java.util.Date d; String[] tmp=expStr.trim().split(" "); @@ -194,9 +190,9 @@ private long parseTTD(String expStr,SimpleDateFormat sdfDate) throws ParseExcept c.setTime(d); c.setTimeZone(TimeZone.getDefault()); c.get(Calendar.DATE); - return c.getTimeInMillis(); + return c.getTimeInMillis(); } - + private long parseTTD(String expStr) { SimpleDateFormat sdfDate = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss"); SimpleDateFormat sdfDate1 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss z"); @@ -211,14 +207,14 @@ private long parseTTD(String expStr) { } return ttd; } - - + + private ChannelAuth getCookie(URLConnection connection,ChannelAuth a) throws Exception { String hName=""; for (int j=1; (hName = connection.getHeaderFieldKey(j))!=null; j++) { String cStr=connection.getHeaderField(j); Channels.debug("hdr "+hName); - if (!hName.equalsIgnoreCase("Set-Cookie")) + if (!hName.equalsIgnoreCase("Set-Cookie")) continue; String[] fields = cStr.split(";\\s*"); String cookie=fields[0]; @@ -250,7 +246,7 @@ private ChannelAuth getCookie(URLConnection connection,ChannelAuth a) throws Exc return mkResult(a); return null; } - + private ChannelAuth cookieLogin(String usr,String pass,ChannelAuth a) throws Exception { ChannelAuth a1=Channels.getCookie(ChannelUtil.trimURL(url)); if(a1!=null) { // found some in hash @@ -281,7 +277,7 @@ private ChannelAuth cookieLogin(String usr,String pass,ChannelAuth a) throws Exc HttpsURLConnection connection = (HttpsURLConnection) u.openConnection(p); HttpsURLConnection.setFollowRedirects(true); HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier()); - ((HttpsURLConnection) connection).setInstanceFollowRedirects(true); + ((HttpsURLConnection) connection).setInstanceFollowRedirects(true); ((HttpsURLConnection) connection).setRequestMethod(method); String page=ChannelUtil.postPage(connection, query); //Channels.debug("login res page "+page); @@ -291,8 +287,8 @@ private ChannelAuth cookieLogin(String usr,String pass,ChannelAuth a) throws Exc } else { HttpURLConnection connection = (HttpURLConnection) u.openConnection(); - HttpURLConnection.setFollowRedirects(true); - connection.setInstanceFollowRedirects(true); + HttpURLConnection.setFollowRedirects(true); + connection.setInstanceFollowRedirects(true); connection.setRequestMethod(method); String page=ChannelUtil.postPage(connection, query); //Channels.debug("login page "+page); @@ -301,7 +297,7 @@ private ChannelAuth cookieLogin(String usr,String pass,ChannelAuth a) throws Exc return getCookie(connection,a); } } - + private ChannelAuth basicLogin(String usr,String pass,ChannelAuth a) { String tmp=usr+":"+pass; tokenStr=Base64.encode(tmp); @@ -309,11 +305,11 @@ private ChannelAuth basicLogin(String usr,String pass,ChannelAuth a) { type=ChannelLogin.STD; return mkResult(a); } - + public ChannelAuth getAuthStr(String usr,String pass,ChannelAuth a) { return getAuthStr(usr,pass,false,a); } - + public ChannelAuth getAuthStr(String usr,String pass,boolean media,ChannelAuth a) { Channels.debug("login on channel "+parent.getName()+" type "+type+" on "+loggedOn); /*Date d=new Date(ttd); @@ -368,13 +364,13 @@ else if(type==ChannelLogin.BASIC) return a; } } - + public void reset() { tokenStr=""; loggedOn=false; ttd=0; } - + private static class NullHostnameVerifier implements javax.net.ssl.HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; diff --git a/src/com/sharkhunter/channel/ChannelMedia.java b/src/com/sharkhunter/channel/ChannelMedia.java index b8db3dd..bdf933e 100644 --- a/src/com/sharkhunter/channel/ChannelMedia.java +++ b/src/com/sharkhunter/channel/ChannelMedia.java @@ -2,29 +2,24 @@ import java.util.ArrayList; import java.util.HashMap; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import org.apache.commons.lang.StringEscapeUtils; -import net.pms.PMS; +import org.slf4j.LoggerFactory; import net.pms.configuration.RendererConfiguration; import net.pms.dlna.DLNAResource; -import net.pms.dlna.virtual.VirtualVideoAction; -import net.pms.formats.Format; public class ChannelMedia implements ChannelProps,ChannelScraper { + private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ChannelMedia.class); public static final int TYPE_NORMAL=0; public static final int TYPE_ASX=1; - + public static final int SAVE_OPT_NONE=0; public static final int SAVE_OPT_SAVE=1; public static final int SAVE_OPT_PLAY=2; - + public static final int SCRIPT_LOCAL=0; public static final int SCRIPT_NET=1; public static final int SCRIPT_EXT=2; - + public boolean Ok; private ChannelMatcher matcher; private String name; @@ -42,7 +37,7 @@ public class ChannelMedia implements ChannelProps,ChannelScraper { private HashMap hdrs; private String videoFormat; private ChannelMatcher formatMatcher; - + public ChannelMedia(ArrayList data,Channel parent) { Ok=false; matcher=null; @@ -54,14 +49,14 @@ public ChannelMedia(ArrayList data,Channel parent) { params=new HashMap(); format=-1; proxy=null; - hdrs=new HashMap(); + hdrs=new HashMap(); hdrs.putAll(parent.getHdrs()); videoFormat=null; formatMatcher=null; parse(data); Ok=true; } - + public void parse(ArrayList data) { for(int i=0;i data) { if(m!=null) parse(m.getMacro()); else - PMS.debug("unknown macro "+keyval[1]); - } + LOGGER.debug("{Channel} Unknown macro {}", keyval[1]); + } if(keyval[0].equalsIgnoreCase("matcher")) { if(matcher==null) matcher=new ChannelMatcher(keyval[1],null,this); @@ -117,7 +112,7 @@ public void parse(ArrayList data) { } if(keyval[0].equalsIgnoreCase("name")) name=keyval[1]; - if(keyval[0].equalsIgnoreCase("prop")) + if(keyval[0].equalsIgnoreCase("prop")) prop=keyval[1].trim().split(","); if(keyval[0].equalsIgnoreCase("img")) thumbURL=keyval[1]; @@ -154,23 +149,23 @@ public void parse(ArrayList data) { if(matcher!=null) matcher.processProps(prop); } - + public void setFallBackFormat(String s) { videoFormat=s; } - + public ChannelMatcher getMatcher() { return matcher; } - + public ChannelMatcher getFormatMatcher() { return formatMatcher; } - + public boolean onlyFirst() { return ChannelUtil.getProperty(prop, "only_first"); } - + public void stash(String key,String val) { if(ChannelUtil.empty(val)) return; @@ -183,16 +178,16 @@ public void add(DLNAResource res,String nName,String url,String thumb,boolean au public void add(DLNAResource res,String nName,String url,String thumb,boolean autoASX,int sOpt) { add(res,nName,url,thumb,autoASX,null,-1,sOpt,null, null); } - + public void add(DLNAResource res,String nName,String url,String thumb,boolean autoASX,String imdb) { add(res,nName,url,thumb,autoASX,imdb,-1,ChannelMedia.SAVE_OPT_NONE,null, null); } - + public void add(DLNAResource res,String nName,String url,String thumb, boolean autoASX,String imdb,int f,String subs) { add(res,nName,url,thumb,autoASX,imdb,f,ChannelMedia.SAVE_OPT_NONE,subs, null); } - + public void add(final DLNAResource res,String nName,String url,String thumb, boolean autoASX,String imdb,int f,int sOpt,String subs, HashMap rtmpStash) { if(!ChannelUtil.empty(thumbURL)) { @@ -271,11 +266,11 @@ else if(sOpt==ChannelMedia.SAVE_OPT_SAVE) res.addChild(cms); } } - + public String separator(String base) { return ChannelUtil.separatorToken(ChannelUtil.getPropertyValue(prop, base+"_separator")); } - + @Override public String scrape(Channel ch, String url, String scriptName,int format,DLNAResource start ,boolean noSub,String imdb,Object embedSubs, @@ -303,18 +298,18 @@ public String scrape(Channel ch, String url, String scriptName,int format,DLNARe vars.put("subtitle", subFile); } Channels.debug("subFile "+subFile); - } + } Channels.debug("scrape script name "+scriptName); if(ChannelUtil.empty(scriptName)) { // no script just return what we got vars.put("url", ChannelUtil.parseASX(url,asx)); if(extraMap!=null) vars.putAll(extraMap); if(live) - vars.put("live", "true"); + vars.put("live", "true"); return ChannelUtil.createMediaUrl(vars,format,ch,render); } ch.debug("media scrape type "+scriptType+" name "+scriptName); - if(scriptType==ChannelMedia.SCRIPT_NET) + if(scriptType==ChannelMedia.SCRIPT_NET) return ChannelNaviXProc.parse(url,scriptName,format,subFile,parent); if(scriptType==ChannelMedia.SCRIPT_EXT) { /*String f=ChannelUtil.format2str(format); @@ -335,7 +330,7 @@ public String scrape(Channel ch, String url, String scriptName,int format,DLNARe } vars.put("url", ChannelUtil.parseASX(rUrl,asx)); return ChannelUtil.createMediaUrl(vars, format,ch,render); - } + } ArrayList sData=Channels.getScript(scriptName); if(sData==null) { // weird no script found, log and bail out ch.debug("no script "+scriptName+" defined"); @@ -353,18 +348,18 @@ public String scrape(Channel ch, String url, String scriptName,int format,DLNARe res.put("__type__", "normal"); return ChannelUtil.createMediaUrl(res,format,ch,render); } - + public boolean scriptOnly() { return !ChannelUtil.empty(script)&&(matcher==null); } - + public String append(String base) { return ChannelUtil.getPropertyValue(prop,"append_"+base); } public String prepend(String base) { return ChannelUtil.getPropertyValue(prop,"prepend_"+base); } - + public String rawEntry() { StringBuilder sb=new StringBuilder(); sb.append("media {"); @@ -415,7 +410,7 @@ else if(scriptType==ChannelMedia.SCRIPT_NET) sb.append("\n}\n"); return sb.toString(); } - + public long delay() { String x=ChannelUtil.getPropertyValue(prop, "delay"); if(ChannelUtil.empty(x)) @@ -429,7 +424,7 @@ public long delay() { return 0; } } - + public String backtrackedName(DLNAResource start) { return ChannelSubUtil.backtrackedName(start, prop); } @@ -444,17 +439,17 @@ public boolean escape(String base) { public boolean unescape(String base) { return ChannelUtil.getProperty(prop, base+"_unescape"); } - + public String mangle(String base) { return ChannelUtil.getPropertyValue(prop, base+"_mangle"); } - + public String subScrape(DLNAResource start,String imdb) { return subScrape(start,imdb,false); } - + public String subScrape(DLNAResource start,String imdb,boolean select) { - if(subtitle==null) + if(subtitle==null) return null; String subFile=null; for(int i=0;i subSites() { return ChannelSubUtil.subSites(subtitle); } - + public HashMap subSelect(DLNAResource start,String imdb) { return ChannelSubUtil.subSelect(start, imdb, subtitle, parent, backtrackedName(start)); } - + public HashMap subSelect(DLNAResource start,String imdb,String subSite) { return ChannelSubUtil.subSelect(start, imdb, subSite, subtitle, parent, backtrackedName(start)); } - + public String relativeURL() { return ChannelUtil.getPropertyValue(prop, "relative_url"); } diff --git a/src/com/sharkhunter/channel/ChannelMediaStream.java b/src/com/sharkhunter/channel/ChannelMediaStream.java index 77e8013..64473f9 100644 --- a/src/com/sharkhunter/channel/ChannelMediaStream.java +++ b/src/com/sharkhunter/channel/ChannelMediaStream.java @@ -13,12 +13,9 @@ import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; import java.util.HashMap; import java.util.List; - +import org.slf4j.LoggerFactory; import net.pms.PMS; import net.pms.configuration.FormatConfiguration; import net.pms.configuration.RendererConfiguration; @@ -32,13 +29,11 @@ import net.pms.formats.Format; import net.pms.formats.FormatFactory; import net.pms.formats.v2.SubtitleType; -import net.pms.formats.WEB; -import net.pms.io.BufferedOutputFile; import net.pms.io.OutputParams; -import net.pms.io.WindowsNamedPipe; public class ChannelMediaStream extends DLNAResource { + private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ChannelMediaStream.class); private String url; private String thumb; private String name; @@ -48,7 +43,7 @@ public class ChannelMediaStream extends DLNAResource { private String realUrl; private int ASX; private ChannelScraper scraper; - private String saveName; + private String saveName; private String dispName; private Thread saver; private boolean scraped; @@ -67,17 +62,17 @@ public class ChannelMediaStream extends DLNAResource { private Thread bgThread; private int bgCnt; private String hdr; - + public ChannelMediaStream(Channel ch,String name,String nextUrl, String thumb,String proc,int type,int asx, - ChannelScraper scraper) { + ChannelScraper scraper) { this(ch,name,nextUrl,thumb,proc,type,asx,scraper,name,null); } public ChannelMediaStream(Channel ch,String name,String nextUrl, String thumb,String proc,int type,int asx, ChannelScraper scraper,String dispName) { this(ch,name,nextUrl,thumb,proc,type,asx,scraper,dispName,null); - + } public ChannelMediaStream(Channel ch,String name,String nextUrl, String thumb,String proc,int type,int asx, @@ -114,11 +109,11 @@ public ChannelMediaStream(Channel ch,String name,String nextUrl, getMedia().setAudioTracksList(new ArrayList()); getMedia().setMediaparsed(true); } - + public ChannelMediaStream(ChannelMediaStream cms) { this(cms,null); } - + public ChannelMediaStream(ChannelMediaStream cms,String name) { super(cms.getType()); url=cms.url; @@ -153,7 +148,7 @@ public ChannelMediaStream(ChannelMediaStream cms,String name) { getMedia().setAudioTracksList(new ArrayList()); getMedia().setMediaparsed(true); } - + public ChannelMediaStream(String name,String realUrl,Channel parent,int format, String thumb) { super(format); @@ -188,51 +183,51 @@ public ChannelMediaStream(String name,String realUrl,Channel parent,int format, getMedia().setAudioTracksList(new ArrayList()); getMedia().setMediaparsed(true); } - + public String saveName() { return saveName; } - + public void noSubs() { noSubs=true; } - + public void subs() { noSubs=false; } - + public void setRender(RendererConfiguration r) { render=r; } - + public void setSaveMode(boolean raw) { rawSave=raw; } - + public void setFallbackFormat(String s) { videoFormat=s; } - + public void setEmbedSub(Object str) { embedSub=str; } - + public ChannelScraper scraper() { return scraper; } - + public String imdb() { return imdb; } - + public void setName(String n) { name=n; } - + public void setStash(HashMap map) { stash=map; } - + public InputStream getThumbnailInputStream() throws IOException { if (thumb != null) { try { @@ -245,17 +240,17 @@ public InputStream getThumbnailInputStream() throws IOException { } return super.getThumbnailInputStream(); } - - + + private void updateStreamDetails(boolean loop) { - Format old_ext=getExt(); + Format old_ext = getFormat(); // update format, use checktype to be future proof - setExt(null); - checktype(); - if(getExt()==null) { // no ext found restore what we got and bail out - setExt(old_ext); + setFormat(null); + resolveFormat(); + if(getFormat() == null) { // no ext found restore what we got and bail out + setFormat(old_ext); return; - } + } // need to update player as well @@ -285,13 +280,13 @@ private void updateStreamDetails(boolean loop) { // if(pl!=null) if(Channels.cfg().usePMSEncoder()) { boolean forceTranscode = false; - if (getExt() != null) { - forceTranscode = getExt().skip(PMS.getConfiguration().getForceTranscodeForExtensions(), getDefaultRenderer() != null ? getDefaultRenderer().getTranscodedExtensions() : null); + if (getFormat() != null) { + forceTranscode = getFormat().skip(PMS.getConfiguration().getForceTranscodeForExtensions(), getDefaultRenderer() != null ? getDefaultRenderer().getTranscodedExtensions() : null); } boolean isIncompatible = false; - if (!getExt().isCompatible(getMedia(),getDefaultRenderer())) { + if (!getFormat().isCompatible(getMedia(),getDefaultRenderer())) { isIncompatible = true; } boolean mp2=false; @@ -315,14 +310,14 @@ private void updateStreamDetails(boolean loop) { setPlayer(pl); } } - + public DLNAMediaSubtitle getSubs() { DLNAMediaSubtitle sub=this.getMediaSubtitle(); - if(sub!=null&&sub.id!=-1) + if(sub != null && sub.getId() != -1) return null; return sub; } - + public void scrape(RendererConfiguration render) { if(!scraped) { if(scraper!=null) @@ -334,7 +329,7 @@ public void scrape(RendererConfiguration render) { } scraped=true; } - + private void scrape_i(RendererConfiguration render) { Channels.debug("scrape "+name+" nosubs "+noSubs); fool=Channels.cfg().netDiscStyle(); @@ -357,7 +352,7 @@ else if(realUrl.startsWith("navix://")) { else { if(realUrl.startsWith("subs://")) fixStuff(realUrl.substring(7),true); - else if(realUrl.startsWith("navix://")) + else if(realUrl.startsWith("navix://")) fixStuff(realUrl.substring(8+8),false); else if(realUrl.startsWith("rtmpdump://")) { rtmpUrl(realUrl.substring(11+8)); @@ -367,19 +362,19 @@ else if(realUrl.startsWith("rtmp://")) { } } if(noSubs) { // make sure subs are off here - media_subtitle=new DLNAMediaSubtitle(); - media_subtitle.setId(-1); + setMediaSubtitle(new DLNAMediaSubtitle()); + getMediaSubtitle().setId(-1); } Channels.debug("call update "+realUrl); updateStreamDetails(true); fool=false; ch.prepareCom(); } - - + + public InputStream getInputStream(long low, long high, double timeseek, RendererConfiguration mediarenderer) throws IOException { - if(parent instanceof ChannelPMSSaveFolder) - if(((ChannelPMSSaveFolder)parent).preventAutoPlay()) + if(getParent() instanceof ChannelPMSSaveFolder) + if(((ChannelPMSSaveFolder)getParent()).preventAutoPlay()) return null; scrape_i(mediarenderer); if(delayed()) @@ -391,12 +386,12 @@ public InputStream getInputStream(long low, long high, double timeseek, Renderer else return is; } - + //public InputStream getInputStream(long low, long high, double timeseek, RendererConfiguration mediarenderer) throws IOException { public InputStream getInputStream(Range range, RendererConfiguration mediarenderer) throws IOException { - PMS.debug("cms getinp/2 scrape "+scraper+" url "+realUrl); - if(parent instanceof ChannelPMSSaveFolder) - if(((ChannelPMSSaveFolder)parent).preventAutoPlay()) + LOGGER.debug("{Channel} Cms getinp/2 scrape {} url {}", scraper, realUrl); + if(getParent() instanceof ChannelPMSSaveFolder) + if(((ChannelPMSSaveFolder)getParent()).preventAutoPlay()) return null; Channels.debug("cms getinp/2... scrape "+scraper+" url "+realUrl+" "+scraped); scrape_i(mediarenderer); @@ -416,7 +411,7 @@ public InputStream getInputStream(Range range, RendererConfiguration mediarender else return is; } - + private InputStream getStream() { if(realUrl.startsWith("resource://")) { return getResourceInputStream(realUrl.substring("resource://".length())); @@ -431,7 +426,7 @@ private InputStream getStream() { if(auth!=null) { if(auth.method==ChannelLogin.STD) conn.setRequestProperty("Authorization", auth.authStr); - else if(ChannelUtil.cookieMethod(auth.method)) + else if(ChannelUtil.cookieMethod(auth.method)) cookie=ChannelUtil.append(cookie,"; ",auth.authStr); } if(!ChannelUtil.empty(cookie)) @@ -462,7 +457,7 @@ public InputStream getInputStream() { return null; return getStream(); } - + private InputStream startSave(InputStream is) throws IOException { String sName=saveName; boolean cache=ChannelUtil.empty(saveName); @@ -482,14 +477,20 @@ public void run() { new Thread(r).start(); return is; } + OutputStream[] oss = null; + PipedInputStream pis = null; BufferedOutputStream fos=new BufferedOutputStream(new FileOutputStream(fName)); + try { PipedOutputStream pos=(new PipedOutputStream()); - PipedInputStream pis=new PipedInputStream(pos); - OutputStream[] oss=new OutputStream[2]; + pis=new PipedInputStream(pos); + oss=new OutputStream[2]; oss[0]=fos; oss[1]=pos; + } finally { + fos.close(); + } saver=new Thread(new ChannelSaver(is,oss)); - saver.start(); + saver.start(); return new BufferedInputStream(pis); } @@ -514,7 +515,7 @@ public boolean isFolder() { public long lastModified() { return 0; } - + public boolean directStream() { if(format==Format.AUDIO) return true; @@ -524,7 +525,7 @@ public boolean directStream() { else { u= realUrl; } - return u.startsWith("http")&&(media_subtitle!=null); + return u.startsWith("http") && (getMediaSubtitle() != null); } public String getSystemName() { @@ -540,20 +541,20 @@ public String getSystemName() { return ensureExt(u.substring(u.lastIndexOf("/")+1)); return (u); // need this to } - + private boolean legalExt(String ext) { if(ChannelUtil.empty(ext)) return false; ArrayList formats= (ArrayList) FormatFactory.getSupportedFormats(); for(Format f : formats) { - String[] supported=f.getId(); + String[] supported = f.getSupportedExtensions(); for(int i=0;i ancestors=new ArrayList(); while(tmp!=null) { @@ -606,7 +607,7 @@ public void donePlaying() { break; if(Channels.monitoredPlay(tmp)) { if(ancestors.size()==0) { // odd case1 - tmp.getChildren().remove(this); + tmp.getChildren().remove(this); break; } DLNAResource oldest=ancestors.get(ancestors.size()-1); @@ -628,7 +629,7 @@ public void donePlaying() { ancestors.add(tmp); tmp=tmp.getParent(); } - if(bgThread!=null) + if(bgThread!=null) if(--bgCnt!=0) // more people using this thread don't kill the dl return; // killThread can handle bgThread==null, so it's safe to call it @@ -636,28 +637,28 @@ public void donePlaying() { ChannelUtil.killThread(bgThread); bgThread=null; } - + public void nowPlaying() { startTime=System.currentTimeMillis(); } - + public void setImdb(String i) { imdb=i; } - - public void bgThread(Thread t) { + + public void bgThread(Thread t) { bgThread=t; bgCnt=1; } - + public void moreBg() { bgCnt++; } - + public boolean isBgDownload() { return (bgThread!=null); } - + private void fixStuff(String str,boolean subs) { String[] splits=str.split("&"); for(int i=0;iSystem.currentTimeMillis()); } - + //////////////////////////////////////// // Playlist //////////////////////////////////////// - + public String playlistName() { if(scraper!=null) return scraper.backtrackedName(this); else return name; } - + public String playlistURI() { if(scraper==null) ChannelUtil.parseASX(url, ASX); @@ -777,7 +778,7 @@ public String playlistURI() { embedSub,stash,null); return url; } - + public String playlistExtra() { String res=ch.getName(); if(scraper==null) @@ -786,11 +787,11 @@ public String playlistExtra() { return res; return res+","+processor+","+ChannelUtil.format2str(format); } - + public String playlistThumb() { return thumb; } - + public List addStreamvars(List cmdList,OutputParams params) { Channels.debug("streamvars adding "+getName()+" "+streamVars); if(streamVars==null) @@ -800,15 +801,15 @@ public List addStreamvars(List cmdList,OutputParams params) { cmdList1=cmdList; return cmdList1; } - + public void setStreamVars(ChannelStreamVars vars) { streamVars=vars; } - + public String toString() { return super.toString()+" url "+url+" proc "+processor+" "+" real "+realUrl; } - + public String write() { //ch,url,processor,format,this,noSubs,imdb, //embedSub,stash @@ -825,17 +826,17 @@ public String write() { res=res.replaceAll("[\n\r]", ""); return res; } - + public byte[] getHeaders() { return hdr.trim().getBytes(); } - + public boolean isURLResolved() { if(scraper==null) return false; return !scraper.getBoolProp("do_resolve"); } - + private boolean live() { if(ChannelUtil.empty(realUrl)) { if(scraper==null) @@ -846,7 +847,7 @@ private boolean live() { realUrl.contains("live=")|| realUrl.contains("-v"); } - + public boolean isResumeable() { boolean b=true; if (getFormat() != null) { @@ -858,7 +859,7 @@ public boolean isResumeable() { } return b; } - + public String urlResolve() { if(Channels.cfg().usePMSEncoder()) { if(fool) { @@ -872,7 +873,7 @@ else if(realUrl.startsWith("navix://")) { else { if(realUrl.startsWith("subs://")) fixStuff(realUrl.substring(7),true); - else if(realUrl.startsWith("navix://")) + else if(realUrl.startsWith("navix://")) fixStuff(realUrl.substring(8+8),false); else if(realUrl.startsWith("rtmpdump://")) { rtmpUrl(realUrl.substring(11+8)); diff --git a/src/com/sharkhunter/channel/ChannelMonitor.java b/src/com/sharkhunter/channel/ChannelMonitor.java index 0fd0ca4..a9f5cbd 100644 --- a/src/com/sharkhunter/channel/ChannelMonitor.java +++ b/src/com/sharkhunter/channel/ChannelMonitor.java @@ -6,10 +6,9 @@ import net.pms.dlna.DLNAResource; import net.pms.dlna.virtual.VirtualFolder; -import net.pms.dlna.virtual.VirtualVideoAction; public class ChannelMonitor { - + private ChannelFolder cf; private ArrayList oldEntries; private String name; @@ -27,17 +26,17 @@ public class ChannelMonitor { scanning=false; try_search = false; } - + public void setTemplate(String t) { templ=t; } - + public void setSearch(String s) { search=s; } public void setTrySearch(boolean b) { try_search = b; } - + public void scan() { if(scanning) return; @@ -62,7 +61,7 @@ public void scan() { for(DLNAResource r : dummy.getChildren()) { if(ChannelUtil.empty(templ)) { // standard simple matching - if(oldEntries.contains(r.getName().trim())) + if(oldEntries.contains(r.getName().trim())) continue; } else { @@ -76,7 +75,7 @@ public void scan() { doCrawl(crawl,getName().trim()); scanning=false; } - + private void doCrawl(ArrayList res,String folder) { if(res.isEmpty()) return; @@ -99,7 +98,7 @@ private void doCrawl(ArrayList res,String folder) { rescan(folder); cms.donePlaying(); } - + private void rescan(String folder) { Channels.clearNewMediaFolder(folder); Runnable r=new Runnable() { @@ -110,11 +109,11 @@ public void run() { }; new Thread(r).start(); } - + public String getName() { return name; } - + public boolean addEntry(String newEntry) { Channels.debug("add entry "+newEntry+" old "+oldEntries.contains(newEntry)); if(!oldEntries.contains(newEntry)) { @@ -123,7 +122,7 @@ public boolean addEntry(String newEntry) { } return false; } - + private boolean templateMatch(String entry) { HashMap vars=new HashMap(); vars.put("entry", entry); @@ -137,5 +136,5 @@ private boolean templateMatch(String entry) { } return res; } - + } diff --git a/src/com/sharkhunter/channel/ChannelMonitorMgr.java b/src/com/sharkhunter/channel/ChannelMonitorMgr.java index 8d2a716..e643876 100644 --- a/src/com/sharkhunter/channel/ChannelMonitorMgr.java +++ b/src/com/sharkhunter/channel/ChannelMonitorMgr.java @@ -7,15 +7,13 @@ import java.util.Timer; import java.util.TimerTask; -import net.pms.dlna.DLNAResource; - public class ChannelMonitorMgr { - + private ArrayList monitors; - + private static final int PERIOD = 24*60*60*1000; private static final int DEFAULT_DELAY_SCAN = 10*1000; - + public ChannelMonitorMgr() { monitors=new ArrayList(); Timer timer=new Timer(); @@ -31,16 +29,16 @@ public void run() { scanAll(); }}, launchTime.getTime(),PERIOD); } - + public void add(ChannelMonitor m) { monitors.add(m); } - + public void scanAll() { for(ChannelMonitor m : monitors) m.scan(); } - + public boolean monitored(String name) { for(ChannelMonitor m :monitors) { if(m.getName().equals(name)) @@ -48,7 +46,7 @@ public boolean monitored(String name) { } return false; } - + public ChannelMonitor getMonitor(String name) { for(ChannelMonitor m :monitors) { if(name.equals(m.getName())) @@ -56,18 +54,18 @@ public ChannelMonitor getMonitor(String name) { } return null; } - + public boolean update(String name,String newEntry) { ChannelMonitor m=getMonitor(name); if(m!=null) return m.addEntry(newEntry); return false; } - + public void delayedScan() { delayedScan(DEFAULT_DELAY_SCAN); } - + public void delayedScan(final int delay) { if(monitors.isEmpty()) // no idea to scan return; diff --git a/src/com/sharkhunter/channel/ChannelMovieInfo.java b/src/com/sharkhunter/channel/ChannelMovieInfo.java index 30da00d..f9ab4d0 100644 --- a/src/com/sharkhunter/channel/ChannelMovieInfo.java +++ b/src/com/sharkhunter/channel/ChannelMovieInfo.java @@ -4,23 +4,23 @@ import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; - -import net.pms.PMS; +import org.slf4j.LoggerFactory; import net.pms.dlna.DLNAResource; import net.pms.movieinfo.FileMovieInfoVirtualFolder; public class ChannelMovieInfo { + private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ChannelMovieInfo.class); private String plugins; private int numberOfActors; private int lineLength; - + public ChannelMovieInfo() { numberOfActors=0; lineLength=0; parse(); } - + public void addFolders(DLNAResource res,String imdbId,String thumb) { if (plugins != null) { String[] plgn = plugins.split(","); @@ -34,19 +34,19 @@ public void addFolders(DLNAResource res,String imdbId,String thumb) { } } } - - private void parse() + + private void parse() { - File miConf = new File("MOVIEINFO.conf"); + File miConf = new File("MOVIEINFO.conf"); if (!miConf.exists()) - miConf = new File("plugins/MOVIEINFO.conf"); + miConf = new File("plugins/MOVIEINFO.conf"); if (miConf.exists()) { try { - BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(miConf), "UTF-8")); + BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(miConf), "UTF-8")); String line = null; while ((line=br.readLine()) != null) { line = line.trim(); - if (line.length() > 0 && !line.startsWith("#") && line.indexOf("=") > -1) { + if (line.length() > 0 && !line.startsWith("#") && line.indexOf("=") > -1) { if(line.startsWith("Plugins="))plugins = line.substring(line.indexOf("=")+1,line.length()).toUpperCase(); if(line.startsWith("NumberOfActors="))numberOfActors = Integer.parseInt(line.substring(line.indexOf("=")+1,line.length())); if(line.startsWith("Linelength="))lineLength = Integer.parseInt(line.substring(line.indexOf("=")+1,line.length())); @@ -54,9 +54,9 @@ private void parse() } br.close(); } catch (Exception e) { - e.printStackTrace(); + LOGGER.debug("{Channel} Exception in parse(): {}", e); } } else - PMS.minimal("MOVIEINFO.conf file not found!"); + LOGGER.info("{Channel} MOVIEINFO.conf file not found!"); } } diff --git a/src/com/sharkhunter/channel/ChannelNaviX.java b/src/com/sharkhunter/channel/ChannelNaviX.java index 7bb30a3..d157f66 100644 --- a/src/com/sharkhunter/channel/ChannelNaviX.java +++ b/src/com/sharkhunter/channel/ChannelNaviX.java @@ -5,11 +5,9 @@ import java.net.URL; import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -import net.pms.PMS; import net.pms.configuration.RendererConfiguration; import net.pms.dlna.DLNAResource; import net.pms.dlna.Feed; @@ -27,7 +25,7 @@ public class ChannelNaviX extends VirtualFolder implements ChannelScraper { private String imdbId; private boolean ignoreFav; private boolean ignoreSave; - + public ChannelNaviX(Channel ch,String name,String thumb,String url, String[] props,String[] sub) { super(name,ChannelUtil.getThumb(thumb,null,ch)); @@ -42,24 +40,24 @@ public ChannelNaviX(Channel ch,String name,String thumb,String url, ignoreFav=false; ignoreSave=false; } - + private boolean favFolder() { return !(ignoreFav||parent.noFavorite()); } - + public void setIgnoreFav() { ignoreFav=true; } - + public void setIgnoreSave() { ignoreSave=true; } - + private String washName(String name) { name=name.replaceAll("\\[[^]]*\\]",""); return name; } - + private void doAdd(DLNAResource upper,DLNAResource res,String name,String url) { if(Channels.isCode(name, ChannelIllegal.TYPE_NAME)|| Channels.isCode(url, ChannelIllegal.TYPE_URL)) { @@ -70,7 +68,7 @@ private void doAdd(DLNAResource upper,DLNAResource res,String name,String url) { else upper.addChild(res); } - + private void addMedia(String name,String nextUrl,String thumb,String proc,String type,String pp, DLNAResource res,String imdb,Channel ch) { if(type!=null) { @@ -122,7 +120,7 @@ else if(type.equalsIgnoreCase("rss")) { else { int f=ChannelUtil.getFormat(type); Channels.debug("add media "+f+" name "+name+" url "+nextUrl); - if(f==-1) + if(f==-1) return; int asx; if(ChannelUtil.getProperty(props,"auto_asx")) @@ -141,7 +139,7 @@ else if(type.equalsIgnoreCase("rss")) { ChannelMediaStream cms=new ChannelMediaStream(ch,name,nextUrl,thumb,proc, f,asx,this); cms.setImdb(imdb); - cms.setRender(this.defaultRenderer); + cms.setRender(this.getDefaultRenderer()); if(Channels.cfg().useStreamVar()) { ChannelStreamVars streamVars=new ChannelStreamVars(Channels.defStreamVar()); streamVars.add(this, parent); @@ -151,8 +149,8 @@ else if(type.equalsIgnoreCase("rss")) { } } } - } - + } + public void readPlx(String str,DLNAResource res) { // The URL found in the cf points to a NaviX playlist // (or similar) fetch and parse @@ -203,7 +201,7 @@ else if(line.startsWith("thumb=")) else if(line.startsWith("processor=")) proc=line.substring(10); else if(line.startsWith("type=")) - type=line.substring(5); + type=line.substring(5); else if(line.startsWith("playpath=")) playpath=line.substring(9); else if(line.startsWith("channel=")) { @@ -224,7 +222,7 @@ else if(line.startsWith("description=")) { // add last item addMedia(name,nextUrl,thumb,proc,type,playpath,res,imdb,ch); } - + public void discoverChildren() { if(favFolder()) { // Add bookmark action @@ -240,7 +238,7 @@ public boolean enable() { } readPlx(url,this); } - + public String subCb(String realName) { String imdb=imdbId; imdbId=null; // clear this always @@ -263,7 +261,7 @@ public String subCb(String realName) { Channels.debug("subs "+subFile); if(ChannelUtil.empty(subFile)) continue; - + return subFile; } return null; @@ -279,15 +277,15 @@ public String scrape(Channel ch, String url, String processorUrl,int format,DLNA return ChannelUtil.badResource(); return res; } - + public Channel getChannel() { return parent; } - + public boolean isTranscodeFolderAvailable() { return false; } - + public InputStream getThumbnailInputStream() { try { return downloadAndSend(thumbnailIcon,true); @@ -296,7 +294,7 @@ public InputStream getThumbnailInputStream() { return super.getThumbnailInputStream(); } } - + public String rawEntry() { StringBuilder sb=new StringBuilder(); sb.append("folder {\n"); @@ -326,7 +324,7 @@ public String rawEntry() { sb.append("\n}\n"); return sb.toString(); } - + public void bookmark(String name,String url,String thumb) { if(!favFolder()||parent==null) // weird but better safe than sorry return; @@ -359,15 +357,15 @@ public long delay() { public String backtrackedName(DLNAResource start) { return ChannelSubUtil.backtrackedName(start, props); } - + public ArrayList subSites() { return ChannelSubUtil.subSites(subtitle); } - + public HashMap subSelect(DLNAResource start,String imdb) { return ChannelSubUtil.subSelect(start, imdb, subtitle, parent); } - + public HashMap subSelect(DLNAResource start,String imdb,String subSite) { return ChannelSubUtil.subSelect(start, imdb, subSite, subtitle, parent); } @@ -384,5 +382,5 @@ public String lastPlayResolveURL(DLNAResource start) { // TODO Auto-generated method stub return null; } - + } diff --git a/src/com/sharkhunter/channel/ChannelNaviXNookie.java b/src/com/sharkhunter/channel/ChannelNaviXNookie.java index 608b17b..3d8a35b 100644 --- a/src/com/sharkhunter/channel/ChannelNaviXNookie.java +++ b/src/com/sharkhunter/channel/ChannelNaviXNookie.java @@ -3,10 +3,8 @@ import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; -import java.io.IOException; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -14,38 +12,42 @@ public class ChannelNaviXNookie { private static HashMap stash=new HashMap(); private static File nFile; - + public static void init(File f) throws Exception { stash.clear(); nFile=f; if(!f.exists()) // no file, nothing to do return; BufferedReader in = new BufferedReader(new FileReader(f)); - String str; - while ((str = in.readLine()) != null) { - str=str.trim(); - if(ChannelUtil.ignoreLine(str)) - continue; - String[] vals=str.split(","); - if(vals.length<3) // weird line,ignore - continue; - long now=(long)(System.currentTimeMillis()/1000); - String key=vals[0]; - long ttd=convTime(vals[1]); - if(ttd!=0) { - if(now>ttd) // nookie timed out + try { + String str; + while ((str = in.readLine()) != null) { + str=str.trim(); + if(ChannelUtil.ignoreLine(str)) + continue; + String[] vals=str.split(","); + if(vals.length<3) // weird line,ignore continue; + long now=(long)(System.currentTimeMillis()/1000); + String key=vals[0]; + long ttd=convTime(vals[1]); + if(ttd!=0) { + if(now>ttd) // nookie timed out + continue; + } + Long l=stash.get(key); + if(l!=null&&l.longValue() vars=new HashMap(); private static HashMap rvars=new HashMap(); public static HashMap nookies=new HashMap(); private static long lastExpire=0; - + private static void debug(String msg) { if(ChannelUtil.empty(vars.get("nodebug"))) Channels.debug(msg); } - + private static String escapeChars(String str) { StringBuilder sb=new StringBuilder(); // str=str.replaceAll("\\(", "\\\\\\("); @@ -65,7 +62,7 @@ private static String fixVar(String val,String storedVal) { return storedVal; } } - + private static boolean eqOp(String op) { if(op.equals("<=")) // lte return true; @@ -75,7 +72,7 @@ private static boolean eqOp(String op) { return true; return false; } - + private static boolean boolOp(String var,String op,String comp) { if(var==null) var=""; @@ -95,7 +92,7 @@ private static boolean boolOp(String var,String op,String comp) { return (var.compareTo(comp)>=0); return false; } - + private static String getVar(String key) { if(key.startsWith("pms_stash.")) { // special PMS stash @@ -112,7 +109,7 @@ private static String getVar(String key) { } return vars.get(key); } - + private static void putVar(String key,String val) { if(key.startsWith("pms_stash.")) { // special PMS stash @@ -129,18 +126,18 @@ private static void putVar(String key,String val) { } vars.put(key, val); } - + private static void clearVs(int maxV) { for(int j=1;j<=maxV;j++) { vars.remove("v"+String.valueOf(j)); rvars.remove("v"+String.valueOf(j)); } } - + private static boolean parseV2(String[] lines,int start,String url) throws Exception { return parseV2(lines,start,url,null); } - + private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a) throws Exception { Pattern ifparse=Pattern.compile("^([^<>=!]+)\\s*([!<>=]+)\\s*(.*)"); boolean if_skip=false; @@ -166,7 +163,7 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a if(if_skip&&!line.startsWith("else")&&!line.startsWith("elseif")&&!line.startsWith("endif")) continue; if_skip=false; - + if(line.startsWith("print")) { String var=line.substring(6).trim(); String msg; @@ -174,17 +171,17 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a msg = var.substring(1); else msg = var + "=" + getVar(var); - PMS.debug(msg); + LOGGER.debug(msg); Channels.debug(msg); continue; } - + if(line.equalsIgnoreCase("scrape")) { // scrape, fetch page... String sUrl=vars.get((String)"s_url"); URLConnection u=null; String action=vars.get("s_action"); Proxy p=ChannelUtil.proxy(a); - if(action!=null&&action.equalsIgnoreCase("geturl")) { + if(action!=null&&action.equalsIgnoreCase("geturl")) { // YUCK!! this sucks, we need to get the location out of the redirect... debug("geturl called "+sUrl); HttpURLConnection h=(HttpURLConnection)new URL(sUrl).openConnection(p); @@ -217,7 +214,7 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a hdr.put("Referer", vars.get("s_referer")); } if(method!=null&&method.equalsIgnoreCase("post")) { - String q=vars.get("s_postdata"); + String q=vars.get("s_postdata"); sPage=ChannelUtil.postPage(u,(q==null?"":q),vars.get("s_cookie"),hdr); } else { @@ -233,7 +230,7 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a // get headers and cookies String hName=""; for (int j=1; (hName = u.getHeaderFieldKey(j))!=null; j++) { - if (hName.equals("Set-Cookie")) { + if (hName.equals("Set-Cookie")) { String[] fields = u.getHeaderField(j).split(";\\s*"); String cookie=fields[0]; String[] cf=cookie.split("=",2); @@ -253,7 +250,7 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a Matcher m=re.matcher(sPage); clearVs(maxV); maxV=0; - if(m.find()) { + if(m.find()) { for(int j=1;j<=m.groupCount();j++) { vars.put("v"+String.valueOf(j), m.group(j)); rvars.put("v"+String.valueOf(j), m.group(j)); @@ -266,17 +263,17 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a if_true=false; continue; } - + if(line.startsWith("if ")) { // if block String cond=line.substring(3); - debug("if "+cond+" pattern "+ifparse.pattern()); + debug("if "+cond+" pattern "+ifparse.pattern()); Matcher im=ifparse.matcher(cond); String var; String op=null; String comp=null; if(!im.find()) { var=getVar(cond); - } + } else { var=getVar(im.group(1)); debug("gc "+im.groupCount()+" "+var); @@ -303,7 +300,7 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a if_skip=true; continue; } - + if(line.startsWith("elseif ")) { String cond=line.substring(7); Matcher im=ifparse.matcher(cond); @@ -312,7 +309,7 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a String comp=null; if(!im.find()) { var=getVar(cond); - } + } else { var=getVar(im.group(1)); Channels.debug("gc "+im.groupCount()+" "+var); @@ -342,13 +339,13 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a if_true=true; continue; } - + if(line.startsWith("error ")) { Channels.debug("Error "+line.substring(6)); throw new Exception("NIPL error"); } - - + + if(line.startsWith("concat ")) { String[] ops=line.substring(7).split(" ",2); String res=ChannelUtil.append(getVar(ops[0].trim()),"", @@ -357,7 +354,7 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a debug("concat "+ops[0]+" res "+res); continue; } - + if(line.startsWith("match ")) { String var=line.substring(6).trim(); Pattern re=Pattern.compile(escapeChars(vars.get("regex"))); @@ -379,7 +376,7 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a } continue; } - + if(line.startsWith("replace ")) { String[] ops=line.substring(8).split(" ",2); Pattern re=Pattern.compile(vars.get("regex")); @@ -388,21 +385,21 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a putVar(ops[0], res); continue; } - + if(line.startsWith("unescape ")) { String var=line.substring(9).trim(); String res=ChannelUtil.unescape(getVar(var)); putVar(var, res); continue; } - + if(line.startsWith("escape ")) { String var=line.substring(7).trim(); String res=ChannelUtil.escape(getVar(var)); putVar(var, res); continue; } - + String[] vLine=line.split("=",2); if(vLine.length==2) { // variable String key=vLine[0].trim(); @@ -414,7 +411,7 @@ private static boolean parseV2(String[] lines,int start,String url,ChannelAuth a } else { String realVal=fixVar(val,vars.get(val)); - if(key.startsWith("nookies.")) { + if(key.startsWith("nookies.")) { nookies.put(key.substring(8), realVal); ChannelNaviXNookie.store(key.substring(8),realVal,vars.get("nookie_expires")); } @@ -436,11 +433,11 @@ else if(key.startsWith("pms_stash.")) { } continue; } - + ////////////////////////////////////// // These ones are channel specific ////////////////////////////////////// - + if(line.startsWith("prepend ")) { String[] ops=line.substring(8).split(" ",2); String res=ChannelUtil.append(fixVar(ops[1],getVar(ops[1])),"", @@ -449,7 +446,7 @@ else if(key.startsWith("pms_stash.")) { debug("prepend "+ops[0]+" res "+res); continue; } - + if(line.startsWith("call ")) { String nScript=line.substring(5).trim(); nScript=fixVar(nScript,getVar(nScript)); @@ -472,10 +469,10 @@ else if(key.startsWith("pms_stash.")) { putVar("v1",ChannelUtil.unescape(tmp)); break; } - } + } continue; } - + if(line.startsWith("stripExt ")) { String[] ops=line.substring(9).split(" "); String var=ops[0].trim(); @@ -495,32 +492,32 @@ else if(key.startsWith("pms_stash.")) { putVar(var, res); continue; } - + if(line.startsWith("sleep ")) { String time=line.substring(6).trim(); time=fixVar(time,getVar(time)); ChannelUtil.sleep(time); continue; } - + ////////////////////// // Exit form here ////////////////////// - + if(line.startsWith("report")) { Channels.debug("report found take another spin"); return true; } - + if(line.trim().equals("play")) return false; - + } // This is weird no play statement?? throw error Channels.debug("no play found"); throw new Exception("NIPL error no play"); } - + private static boolean parseV1(String[] lines,int start,String url) throws Exception { String nextUrl=lines[start]; int modLen=lines.length-start; @@ -541,7 +538,7 @@ private static boolean parseV1(String[] lines,int start,String url) throws Excep cookie=lines[start+3]; URLConnection u=new URL(nextUrl).openConnection(); String sPage=ChannelUtil.fetchPage(u, null, cookie,null); - if(ChannelUtil.empty(sPage)) + if(ChannelUtil.empty(sPage)) throw new Exception("Empty scrap page"); Channels.debug("v1 scrap page "+sPage); Pattern re=Pattern.compile(escapeChars(filt)); @@ -563,16 +560,16 @@ private static boolean parseV1(String[] lines,int start,String url) throws Excep if(l[0].contains("error")) throw new Exception("Empty scrap page"); vars.put("url", l[0]); - if(l.length>1) + if(l.length>1) vars.put("swfplayer", l[1]); if(l.length>2) vars.put("playpath",l[2]); if(l.length>3) - vars.put("pageurl", l[3]); + vars.put("pageurl", l[3]); } return false; } - + private static void addSpecials(Channel ch) { if(ch!=null) { vars.put("user", ch.user()); @@ -584,15 +581,15 @@ private static void addSpecials(Channel ch) { } } } - + public static String parse(String url,String pUrl,int format) { return parse(url,pUrl,format,null,null,null,null,null); } - + public static String parse(String url,String pUrl,int format,String subFile,Channel ch) { return parse(url,pUrl,format,null,null,subFile,ch,null); } - + public static String parse(String url,String pUrl,int format,ChannelNaviX caller, DLNAResource start,RendererConfiguration render) { return parse(url,pUrl,format,caller,start,null,null,render); @@ -620,7 +617,7 @@ public static String parse(String url,String pUrl,int format,ChannelNaviX caller } catch (MalformedURLException e) { Channels.debug("error fetching page "+e); return null; - } + } int phase=0; boolean loop=true; String lastPage=""; @@ -632,7 +629,7 @@ public static String parse(String url,String pUrl,int format,ChannelNaviX caller } vars.put("nookies."+key, nookies.get(key)); } - + while(loop) { if(phase>0) { String res="phase="+String.valueOf(phase); @@ -663,7 +660,7 @@ public static String parse(String url,String pUrl,int format,ChannelNaviX caller procPage=""; } Channels.debug("processor page "+procPage); - if(ChannelUtil.empty(procPage)) + if(ChannelUtil.empty(procPage)) return null; if(phase>0&&lastPage.equals(procPage)) { Channels.debug("processor loop"); @@ -672,7 +669,7 @@ public static String parse(String url,String pUrl,int format,ChannelNaviX caller lastPage=procPage; String[] lines=procPage.split("\n"); int i=0; - while(ChannelUtil.ignoreLine(lines[i])) + while(ChannelUtil.ignoreLine(lines[i])) i++; try { if(lines[i].equalsIgnoreCase("v2")) @@ -711,57 +708,57 @@ else if(lines[i].equalsIgnoreCase("v1")) Channels.debug("navix return media url "+rUrl); return rUrl; } - + ////////////////////////////////////// - // lite versions + // lite versions ////////////////////////////////////// - + // lite with ArrayList as line arg - + public static HashMap lite(String url,ArrayList lines,int asx, HashMap initStash,Channel ch) { String[] arr=lines.toArray(new String[lines.size()]); return lite(url,arr,asx,initStash,ch); } - + public static HashMap lite(String url,ArrayList lines,int asx) { return lite(url,lines,asx,null); } - + public static HashMap lite(String url,ArrayList lines,int asx,Channel ch) { return lite(url,lines,asx,null,ch); } - + public static HashMap lite(String url,ArrayList lines) { return lite(url,lines,ChannelUtil.ASXTYPE_AUTO); } - + public static HashMap lite(String url,ArrayList lines, HashMap initStash) { return lite(url,lines,ChannelUtil.ASXTYPE_AUTO,initStash,null); } - + public static HashMap lite(String url,ArrayList lines, HashMap initStash,Channel ch) { return lite(url,lines,ChannelUtil.ASXTYPE_AUTO,initStash,ch); } - + // Lite with array as line arg public static HashMap lite(String url,String[] lines) { return lite(url,lines,ChannelUtil.ASXTYPE_AUTO,null); } - + public static HashMap lite(String url,String[] lines,int asx,Channel ch) { return lite(url,lines,asx,null,ch); } - + public static HashMap lite(String url,String[] lines, HashMap initStash) { return lite(url,lines,ChannelUtil.ASXTYPE_AUTO,initStash,null); } - + // The actual work of lite is done here - + public static HashMap lite(String url,String[] lines,int asx, HashMap initStash,Channel ch) { try { @@ -770,7 +767,7 @@ public static HashMap lite(String url,String[] lines,int asx, if(initStash!=null) vars.putAll(initStash); ChannelAuth a=null; - if(ch!=null) { + if(ch!=null) { a=ch.prepareCom(); debug("a "+a+" cookie "+a.authStr); if(a!=null&&a.method==ChannelLogin.COOKIE) @@ -789,25 +786,25 @@ public static HashMap lite(String url,String[] lines,int asx, return null; } } - + ////////////////////////////////// - // simple versions + // simple versions ////////////////////////////////// - + public static String simple(String str,ArrayList script) { return simple(str,script,null,null); } - + public static String simple(String str,String script,HashMap initStash) { ArrayList sData=Channels.getScript(script); return simple(str,sData,initStash,null); } - + public static String simple(String str,String script) { ArrayList sData=Channels.getScript(script); return simple(str,sData); } - + public static String simple(String str,ArrayList script,HashMap initStash,Channel ch) { if(script==null) return str; diff --git a/src/com/sharkhunter/channel/ChannelNaviXUpdate.java b/src/com/sharkhunter/channel/ChannelNaviXUpdate.java index 071cf47..e2de7e4 100644 --- a/src/com/sharkhunter/channel/ChannelNaviXUpdate.java +++ b/src/com/sharkhunter/channel/ChannelNaviXUpdate.java @@ -1,14 +1,12 @@ package com.sharkhunter.channel; -import java.io.IOException; -import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ChannelNaviXUpdate { - + private static String baseUrl="http://www.navixtreme.com/"; private static String myUrl=baseUrl+"playlist/mine.plx"; private static String loginUrl=baseUrl+"members"; @@ -16,7 +14,7 @@ public class ChannelNaviXUpdate { private static String listId=null; private static String naviCookie=null; private static boolean local; - + private static boolean setId(String url,String name,String name1,String type) { Pattern re=Pattern.compile("/(\\d+)/"); if(ChannelUtil.empty(url)) { @@ -49,7 +47,7 @@ private static boolean setId(String url,String name,String name1,String type) { } return false; } - + private static void fetchCookie(ChannelCred cr) throws Exception{ if(cr==null) return; @@ -57,7 +55,7 @@ private static void fetchCookie(ChannelCred cr) throws Exception{ String query="action=takelogin&ajax=1&username="+cr.user+"&password="+cr.pwd; URLConnection c=u.openConnection(); String page=ChannelUtil.postPage(c, query); - if(ChannelUtil.empty(page)) + if(ChannelUtil.empty(page)) throw new Exception("Empty NaviX login page"); String[] lines=page.split("\n"); if(!lines[0].contains("ok")) @@ -66,7 +64,7 @@ private static void fetchCookie(ChannelCred cr) throws Exception{ ChannelCookie.parseCookie(c, a, baseUrl); naviCookie="l_access="+lines[1].trim(); } - + private static void fetchListId(String name) throws Exception { Channels.debug("using "+name+" as NaviX upload list"); if(name.equals("local")) { @@ -101,13 +99,13 @@ else if(line.startsWith("type=")) } setId(url,name,name1,type); } - + public static void init(String listName,ChannelCred cred) throws Exception { local=false; fetchCookie(cred); - fetchListId(listName); + fetchListId(listName); } - + private static void upload(String query) throws Exception { if(ChannelUtil.empty(listId)||ChannelUtil.empty(naviCookie)) throw new Exception("NaviXupdater missing listId or cookie"); @@ -116,13 +114,13 @@ private static void upload(String query) throws Exception { String s=ChannelUtil.postPage(u.openConnection(), query,naviCookie,null); Channels.debug("navixup res "+s); } - + public static void updatePlx(String name,String url) throws Exception { String query="action=item_save&id=0&list_id="+listId+"&text_local=0&"+ "list_pos=top&type=plx&name="+ChannelUtil.escape(name)+"&URL="+ChannelUtil.escape(url); upload(query); } - + public static void sync(String name,String url,String proc,int format, String thumb,String imdb) throws Exception { if(ChannelUtil.empty(proc)) // just to make sure @@ -166,7 +164,7 @@ public static void sync(String name,String url,String proc,int format, "&description="+ChannelUtil.escape(imdb); upload(query); } - + public static void updateMedia(Channel ch,String name,String url,String proc,int format, String thumb,String imdb) throws Exception { if(local) { @@ -175,11 +173,11 @@ public static void updateMedia(Channel ch,String name,String url,String proc,int if(netActive()) sync(name,url,proc,format,thumb,imdb); } - + public static boolean netActive() { return (!ChannelUtil.empty(listId))&&(!ChannelUtil.empty(naviCookie)); } - + public static boolean active() { return local||netActive(); } diff --git a/src/com/sharkhunter/channel/ChannelNullPlayer.java b/src/com/sharkhunter/channel/ChannelNullPlayer.java index 1d2dfcc..80bae06 100644 --- a/src/com/sharkhunter/channel/ChannelNullPlayer.java +++ b/src/com/sharkhunter/channel/ChannelNullPlayer.java @@ -7,37 +7,31 @@ import net.pms.PMS; import net.pms.configuration.PmsConfiguration; import net.pms.dlna.DLNAMediaInfo; -import net.pms.dlna.DLNAMediaSubtitle; import net.pms.dlna.DLNAResource; import net.pms.encoders.FFMpegVideo; -import net.pms.encoders.MEncoderWebVideo; -import net.pms.formats.v2.SubtitleUtils; import net.pms.io.OutputParams; import net.pms.io.PipeProcess; import net.pms.io.ProcessWrapper; import net.pms.io.ProcessWrapperImpl; import net.pms.util.CodecUtil; -import net.pms.util.FileUtil; - -import static org.apache.commons.lang3.StringUtils.isNotBlank; public class ChannelNullPlayer extends FFMpegVideo { private boolean transcode; private PmsConfiguration configuration; - private boolean wmv; - + private boolean wmv; + public ChannelNullPlayer(boolean transcode) { super(); configuration=PMS.getConfiguration(); this.transcode=transcode||Channels.cfg().mp2Force(); wmv=false; } - + public String name() { return "Channel Null Player"; } - + private void addMencoder(ArrayList args,String in,File subFile) { int nThreads = configuration.getMencoderMaxThreads(); String acodec = (configuration.isMencoderAc3Fixed() ? "ac3_fixed" : "ac3")+":abitrate=128" ; @@ -49,7 +43,7 @@ private void addMencoder(ArrayList args,String in,File subFile) { args.add("-prefer-ipv4"); args.add("-cookies-file"); args.add(Channels.cfg().getCookiePath()); - + args.add("-oac"); if(!transcode) args.add("pcm"); @@ -104,7 +98,7 @@ private void addMencoder(ArrayList args,String in,File subFile) { } } - + public ProcessWrapper launchTranscode( DLNAResource dlna, DLNAMediaInfo media, @@ -120,15 +114,15 @@ public ProcessWrapper launchTranscode( wmv=true; transcode=true; } - + PipeProcess pipe = new PipeProcess("channels" + System.currentTimeMillis()); params.input_pipes[0] = pipe; - + ArrayList args=new ArrayList(); ChannelMediaStream cms=(ChannelMediaStream)dlna; String format=ChannelUtil.extension(cms.realFormat(),true); - String effFile=fileName; - + //String effFile=fileName; + if (Channels.cfg().fileBuffer()) { String fName=Channels.fileName(dlna.getName(),true); if(cms.saveName()!=null) @@ -156,22 +150,22 @@ public void run() { // delay until file is large enough while(m.length() urls2fetch; private ArrayList threads; private long startedAt; - + // Values of when to fetch etc. private int maxParralell; private int duration; private GregorianCalendar nextTime; private File file; private boolean cache; - + // Constants public static final int DEFAULT_MAX_THREAD=2; public static final int DEFAULT_MAX_DURATION=60; - + public ChannelOffHour(int max,int dur,String start,File f,boolean cache) { maxParralell=max; duration=dur; @@ -53,7 +45,7 @@ public ChannelOffHour(int max,int dur,String start,File f,boolean cache) { setStartTime(start); schedule(true); } - + public void schedule(boolean first) { final ChannelOffHour inst=this; TimerTask task = new TimerTask() { @@ -74,7 +66,7 @@ public void run() { Timer time=new Timer(); time.schedule(task, nextTime.getTime()); } - + private void setStartTime(String start) { SimpleDateFormat sdfHour = new SimpleDateFormat("HH:mm"); try { @@ -95,12 +87,12 @@ private void setStartTime(String start) { if(now.after(nextTime.getTime())) // already missed first trigger, schedule tomorrow nextTime.add(Calendar.DATE, 1); } - + private Date getNextTime() { nextTime.add(Calendar.DATE, 1); return nextTime.getTime(); } - + public void update(String url,String name,boolean add) { if(add) urls2fetch.put(name,url); @@ -109,15 +101,15 @@ public void update(String url,String name,boolean add) { Channels.debug((add?"Added":"Removed")+" "+name+"("+url+") to off hour schedule"); storeDb(); } - + public boolean scheduled(String name) { return urls2fetch.containsKey(name); } - + public void init() { if(!file.exists()) // no file, bail out early return; - try { + try { BufferedReader in=new BufferedReader(new FileReader(file)); String str; while ((str = in.readLine()) != null) { @@ -134,7 +126,7 @@ public void init() { Channels.debug("Error reading offhour file "+e); } } - + public void monitorThread() { if(threads.size()==0) // no threads, no idea to monitor return; @@ -145,8 +137,8 @@ public void run() { long now=System.currentTimeMillis(); // time to quit, leave all threads running // until they're done - if(now>stop) - return; + if(now>stop) + return; ArrayList tmp=new ArrayList(threads); for(int i=0;i pls=PlayerFactory.getPlayers(); for(int i=0;i stash; - + private static final String P="PLAY"; private static final String SP="PLAY&SAVE"; private static final String NS=" - No Subs"; @@ -34,9 +34,9 @@ public class ChannelPMSSaveFolder extends VirtualFolder { private static final String SNS=SP+NS; private static final String PES=P+ES; private static final String SES=SP+ES; - + private static final long AUTO_PLAY_FACTOR=(1000*15); - + public ChannelPMSSaveFolder(Channel ch,String name,String url,String thumb, String proc,int asx,int type, ChannelScraper scraper) { @@ -56,7 +56,7 @@ public ChannelPMSSaveFolder(Channel ch,String name,String url,String thumb, videoFormat=null; embedSub=null; } - + public static String washName(String str) { String[] strs={SNS,PNS,SP,P,PES,SES}; for(String s : strs) { @@ -65,34 +65,34 @@ public static String washName(String str) { } return str; } - + public void setImdb(String i) { imdb=i; } - + public void setDoSubs(boolean b) { subs=b; } - + public void setSaveMode(boolean raw) { rawSave=raw; } - + public void setEmbedSub(String str) { embedSub=str; } - + public void setStash(HashMap map) { stash=map; } - + private String displayName(String n) { if(Channels.cfg().longSaveName()) return ChannelUtil.append(n, " ", name); else return n; } - + public void discoverChildren() { final ChannelPMSSaveFolder me=this; final ChannelOffHour oh=Channels.getOffHour(); @@ -170,7 +170,7 @@ public boolean enable() { thumb,proc,f,asx,scraper,name,name); cms.setEmbedSub(embedSub); cms.setImdb(imdb); - cms.setRender(this.defaultRenderer); + cms.setRender(getDefaultRenderer()); cms.setSaveMode(rawSave); cms.setFallbackFormat(videoFormat); cms.setStreamVars(streamVars); @@ -181,7 +181,7 @@ public boolean enable() { proc,f,asx,scraper,name,null); cms.setEmbedSub(embedSub); cms.setImdb(imdb); - cms.setRender(this.defaultRenderer); + cms.setRender(getDefaultRenderer()); cms.setSaveMode(rawSave); cms.setFallbackFormat(videoFormat); cms.setStreamVars(streamVars); @@ -203,14 +203,14 @@ public boolean enable() { subSel.setStreamVars(streamVars); addChild(subSel); } - } + } } // add the no subs variants if(save) { cms=new ChannelMediaStream(ch,displayName(SNS),url, thumb,proc,f,asx,scraper,name,name); cms.setImdb(imdb); - cms.setRender(this.defaultRenderer); + cms.setRender(getDefaultRenderer()); cms.setSaveMode(rawSave); cms.setFallbackFormat(videoFormat); cms.setStreamVars(streamVars); @@ -221,7 +221,7 @@ public boolean enable() { cms=new ChannelMediaStream(ch,displayName(PNS),url,thumb, proc,f,asx,scraper,name,null); cms.setImdb(imdb); - cms.setRender(this.defaultRenderer); + cms.setRender(getDefaultRenderer()); cms.setSaveMode(rawSave); cms.setFallbackFormat(videoFormat); cms.setStreamVars(streamVars); @@ -230,7 +230,7 @@ public boolean enable() { addChild(cms); } - + public InputStream getThumbnailInputStream() { try { return downloadAndSend(thumbnailIcon,true); @@ -239,30 +239,30 @@ public InputStream getThumbnailInputStream() { return super.getThumbnailInputStream(); } } - + public void childDone() { //childDone=System.currentTimeMillis(); } - + public boolean preventAutoPlay() { // Normally childDone is 0 and 0+15000 is never larger // then now. return (childDone+AUTO_PLAY_FACTOR)>System.currentTimeMillis(); } - + public void setFallbackFormat(String s) { videoFormat=s; } - + public boolean isRefreshNeeded() { return true; } - + public boolean refreshChildren() { refreshChildren(null); return true; } - + public boolean refreshChildren(String str) { if(str==null) return false; @@ -270,11 +270,11 @@ public boolean refreshChildren(String str) { //discoverChildren(str); return true; } - + public void resolve() { setDiscovered(false); } - + public void addChild(DLNAResource child) { if(Channels.cfg().stdAlone()) { // be brutal diff --git a/src/com/sharkhunter/channel/ChannelPMSSubSelector.java b/src/com/sharkhunter/channel/ChannelPMSSubSelector.java index 822eb48..fe91005 100644 --- a/src/com/sharkhunter/channel/ChannelPMSSubSelector.java +++ b/src/com/sharkhunter/channel/ChannelPMSSubSelector.java @@ -5,14 +5,13 @@ import java.util.TreeMap; import java.util.TreeSet; -import net.pms.dlna.DLNAMediaSubtitle; import org.apache.commons.lang.StringUtils; import net.pms.dlna.DLNAResource; import net.pms.dlna.virtual.VirtualFolder; public class ChannelPMSSubSelector extends VirtualFolder { - + private Channel ch; private String name; private String url; @@ -28,18 +27,18 @@ public class ChannelPMSSubSelector extends VirtualFolder { private String matchName; private String site; - + private ChannelStreamVars streamVars; - + private static final String PNS="PLAY (no subs match)"; - + public ChannelPMSSubSelector(Channel ch,String name,String nextUrl, String thumb,String proc,int type,int asx, ChannelScraper scraper,String dispName, String saveName,String imdb) { this(ch,name,nextUrl,thumb,proc,type,asx,scraper,dispName,saveName,imdb,null); } - + public ChannelPMSSubSelector(Channel ch,String name,String nextUrl, String thumb,String proc,int type,int asx, ChannelScraper scraper,String dispName, @@ -61,14 +60,14 @@ public ChannelPMSSubSelector(Channel ch,String name,String nextUrl, site=null; streamVars=null; } - + public void setSite(String s) { site=s; ChannelSubs subs=Channels.getSubs(site); if(!ChannelUtil.empty(subs.getImg())) thumbnailIcon=subs.getImg(); } - + public void setStreamVars(ChannelStreamVars vars) { streamVars=vars; } @@ -120,7 +119,7 @@ public void discoverChildren() { cms.setStreamVars(streamVars); addChild(cms); } - + public InputStream getThumbnailInputStream() { try { return downloadAndSend(thumbnailIcon,true); @@ -128,8 +127,8 @@ public InputStream getThumbnailInputStream() { catch (Exception e) { return super.getThumbnailInputStream(); } - } - + } + private TreeMap> sortMap(HashMap map) { if(ChannelUtil.empty(matchName)) // make matchName ain't null matchName=""; diff --git a/src/com/sharkhunter/channel/ChannelProxy.java b/src/com/sharkhunter/channel/ChannelProxy.java index a51ca6e..0e5e773 100644 --- a/src/com/sharkhunter/channel/ChannelProxy.java +++ b/src/com/sharkhunter/channel/ChannelProxy.java @@ -1,7 +1,6 @@ package com.sharkhunter.channel; import java.io.File; -import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Proxy; @@ -10,12 +9,12 @@ import java.util.ArrayList; public class ChannelProxy { - + public static final int PROXY_NULL=-1; public static final int PROXY_HTTP=0; - + public static ChannelProxy NULL_PROXY=new ChannelProxy(); - + private Proxy p; private boolean state; private long lastCheck; @@ -23,16 +22,16 @@ public class ChannelProxy { private int type; private String extra; private String url; - + private static final long VerifyInterval=(60*1000*5); - + public ChannelProxy() { p=Proxy.NO_PROXY; state=true; ia=null; type=PROXY_NULL; } - + public ChannelProxy(String name,ArrayList data,File dPath) throws UnknownHostException { String addr=null,port=null; p=null; @@ -61,7 +60,7 @@ public ChannelProxy(String name,ArrayList data,File dPath) throws Unknow InetAddress ia=InetAddress.getByName(addr); p=new Proxy(Proxy.Type.HTTP,(SocketAddress)new InetSocketAddress(ia,j.intValue())); } - + public boolean isUp() { if(type==PROXY_NULL) return true; @@ -73,19 +72,19 @@ public boolean isUp() { } catch (IOException e) { state=false; }*/ - state=true; + state=true; lastCheck=System.currentTimeMillis(); return state; } - + public int type() { return type; } - + public Proxy getProxy() { return p; } - + public void invalidate() { if(type==PROXY_NULL) // impossible to invalidate return; diff --git a/src/com/sharkhunter/channel/ChannelScraper.java b/src/com/sharkhunter/channel/ChannelScraper.java index d79fac9..abb5d17 100644 --- a/src/com/sharkhunter/channel/ChannelScraper.java +++ b/src/com/sharkhunter/channel/ChannelScraper.java @@ -2,13 +2,11 @@ import java.util.ArrayList; import java.util.HashMap; -import java.util.List; - import net.pms.configuration.RendererConfiguration; import net.pms.dlna.DLNAResource; -public interface ChannelScraper { - public String scrape(Channel ch,String url,String processorUrl,int format,DLNAResource start, +public interface ChannelScraper { + public String scrape(Channel ch,String url,String processorUrl,int format,DLNAResource start, boolean noSub,String imdb,Object embedSubs, HashMap extraMap,RendererConfiguration render); public long delay(); diff --git a/src/com/sharkhunter/channel/ChannelSearch.java b/src/com/sharkhunter/channel/ChannelSearch.java index 99de9ae..b5e60e5 100644 --- a/src/com/sharkhunter/channel/ChannelSearch.java +++ b/src/com/sharkhunter/channel/ChannelSearch.java @@ -1,10 +1,7 @@ package com.sharkhunter.channel; -import java.io.BufferedReader; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileOutputStream; -import java.io.FileReader; import java.util.ArrayList; import net.pms.dlna.virtual.VirtualFolder; @@ -16,7 +13,7 @@ public class ChannelSearch extends VirtualFolder { private File file; private boolean all; ChannelSearchItem last; - + public ChannelSearch(File f) { super("Recent Searches",null); searchList=new ArrayList(); @@ -24,7 +21,7 @@ public ChannelSearch(File f) { all=true; last=null; } - + public void dump() { if(all) { try { @@ -55,7 +52,7 @@ else if(last!=null) { all=false; last=null; } - + private ChannelSearchItem findItem(Channel ch,String id,String str) { ChannelSearchItem old=null; for(int i=0;i data,Channel parent) { this.parent=parent; parse(data); } - + public ChannelSimple(Channel parent) { this.parent=parent; } - + public void setProp(String p) { prop=p.trim().split(","); } - - public void parse(ArrayList data) { + + public void parse(ArrayList data) { for(int i=0;i data) { if(m!=null) parse(m.getMacro()); else - PMS.debug("unknown macro "+keyval[1]); - } + LOGGER.debug("{Channel} Unknown macro {}", keyval[1]); + } if(keyval[0].equalsIgnoreCase("name")) name=keyval[1]; if(keyval[0].equalsIgnoreCase("url")) - url=keyval[1]; - if(keyval[0].equalsIgnoreCase("prop")) + url=keyval[1]; + if(keyval[0].equalsIgnoreCase("prop")) prop=keyval[1].trim().split(","); if(keyval[0].equalsIgnoreCase("matcher")) { if(matcher==null) @@ -70,11 +68,11 @@ public void parse(ArrayList data) { if(matcher!=null) matcher.processProps(prop); } - + public ChannelMatcher getMatcher() { return matcher; } - + public String fetch() { try { URL urlobj=new URL(url.replaceAll(" ", "%20")); @@ -89,18 +87,18 @@ public String fetch() { public String separator(String base) { return ChannelUtil.getPropertyValue(prop, base+"_separator"); } - + public boolean onlyFirst() { return ChannelUtil.getProperty(prop, "only_first"); } - + public String append(String base) { return ChannelUtil.getPropertyValue(prop,"append_"+base); } public String prepend(String base) { return ChannelUtil.getPropertyValue(prop,"prepend_"+base); } - + @Override public boolean escape(String base) { return ChannelUtil.getProperty(prop, base+"_escape"); diff --git a/src/com/sharkhunter/channel/ChannelStreamVars.java b/src/com/sharkhunter/channel/ChannelStreamVars.java index 20256e2..71b6a60 100644 --- a/src/com/sharkhunter/channel/ChannelStreamVars.java +++ b/src/com/sharkhunter/channel/ChannelStreamVars.java @@ -2,48 +2,50 @@ import java.io.BufferedReader; import java.io.File; -import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; -import java.util.Formatter; import java.util.HashMap; import java.util.List; - -import net.pms.PMS; +import org.slf4j.LoggerFactory; import net.pms.dlna.DLNAResource; import net.pms.io.OutputParams; public class ChannelStreamVars { + private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(ChannelStreamVars.class); private HashMap vars; private String instance; - + public ChannelStreamVars() { vars=new HashMap(); } - + public ChannelStreamVars(ChannelStreamVars def) { vars=new HashMap(def.vars); instance=def.instance; } - + public void parse(File f) throws Exception { - BufferedReader in=new BufferedReader(new FileReader(f)); String str,ver="unknown"; StringBuilder sb=new StringBuilder(); - while ((str = in.readLine()) != null) { - str=str.trim(); - if(ChannelUtil.ignoreLine(str)) - continue; - if(str.startsWith("version")) { - String[] v=str.split("\\s*=\\s*"); - if(v.length<2) - continue; - ver=v[1]; - continue; // don't append these - } - sb.append(str); - sb.append("\n"); - } + BufferedReader in=new BufferedReader(new FileReader(f)); + try { + while ((str = in.readLine()) != null) { + str=str.trim(); + if(ChannelUtil.ignoreLine(str)) + continue; + if(str.startsWith("version")) { + String[] v=str.split("\\s*=\\s*"); + if(v.length<2) + continue; + ver=v[1]; + continue; // don't append these + } + sb.append(str); + sb.append("\n"); + } + } finally { + in.close(); + } String[] lines=sb.toString().split("\n"); for(int i=0;i list,OutputParams params) { for(String var: vars.keySet()) { ChannelVar v=vars.get(var); v.action(player,list,params); } } - + public void setInstance(int i) { setInstance(String.format("%x", i)); } - + public void setInstance(String inst) { instance=inst; } - + public String instance() { return instance; } diff --git a/src/com/sharkhunter/channel/ChannelSubUtil.java b/src/com/sharkhunter/channel/ChannelSubUtil.java index 57eb85c..2136467 100644 --- a/src/com/sharkhunter/channel/ChannelSubUtil.java +++ b/src/com/sharkhunter/channel/ChannelSubUtil.java @@ -2,15 +2,13 @@ import java.io.IOException; import java.io.OutputStreamWriter; -import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Date; import java.util.HashMap; import net.pms.dlna.DLNAResource; public class ChannelSubUtil { - + private final static String ARROW =" --> "; public static String backtrackedName(DLNAResource start,String[] prop) { @@ -24,7 +22,7 @@ public static String backtrackedName(DLNAResource start,String[] prop) { public static HashMap subSelect(DLNAResource start,String imdb, String[] subtitle,Channel ch,String realName) { - if(subtitle==null) + if(subtitle==null) return null; for(int i=0;i subSelect(DLNAResource start,String imdb,C } public static ArrayList subSites(String[] subtitle) { - if(subtitle==null) + if(subtitle==null) return null; ArrayList res=new ArrayList(); for(int i=0;i subSites(String[] subtitle) { res.add(Channels.openSubs().getName()); return res; } - + private static String fixTimeNormal(String str) { int pos=str.lastIndexOf(':'); if(pos==-1) @@ -107,7 +105,7 @@ private static String fixTimeNormal(String str) { sb.setCharAt(pos, ','); return sb.toString(); } - + private static String fixTimeMs(String str) { long millis=Long.parseLong(str); long sec,min,hour; @@ -119,18 +117,18 @@ private static String fixTimeMs(String str) { millis = millis % 1000; return String.format("%02d:%02d:%02d,%03d", hour,min,sec,millis); } - + private static String fixTime(String str,boolean ms) { if(ms) return fixTimeMs(str); else return fixTimeNormal(str); } - + public static void writeSRT(OutputStreamWriter out,int id,String start,String stop,String text) throws IOException { writeSRT(out,id,start,stop,text,false); } - + public static void writeSRT(OutputStreamWriter out,int id,String start,String stop,String text,boolean ms) throws IOException { text=text.trim().replaceAll("\\\\n", "\n"); out.write(String.valueOf(id)); diff --git a/src/com/sharkhunter/channel/ChannelSubs.java b/src/com/sharkhunter/channel/ChannelSubs.java index 5b305e5..d2f8577 100644 --- a/src/com/sharkhunter/channel/ChannelSubs.java +++ b/src/com/sharkhunter/channel/ChannelSubs.java @@ -1,37 +1,25 @@ package com.sharkhunter.channel; -import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; -import java.io.InputStream; import java.io.OutputStream; import java.net.URL; -import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; -import java.util.Locale; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import net.pms.PMS; -import net.pms.dlna.DLNAResource; -import net.pms.formats.Format; -import net.pms.formats.v2.SubtitleType; public class ChannelSubs implements ChannelProps { - + private String name; private String url; private ChannelMatcher matcher; private int best; - private int pathCnt; private String[] prop; private File dPath; private String script; @@ -39,7 +27,7 @@ public class ChannelSubs implements ChannelProps { private String[] lang; private ChannelMatcher select; protected String img; - + public ChannelSubs() { prop=null; dPath=new File(Channels.dataPath()); @@ -93,14 +81,14 @@ public ChannelSubs(String name,ArrayList data,File dPath) { if(best<1) best=1; } - if(keyval[0].equalsIgnoreCase("prop")) - prop=keyval[1].trim().split(","); + if(keyval[0].equalsIgnoreCase("prop")) + prop=keyval[1].trim().split(","); if(keyval[0].equalsIgnoreCase("name_script")) { nameScript=keyval[1].split(","); } if(keyval[0].equalsIgnoreCase("script")) { script=keyval[1]; - } + } if(keyval[0].equalsIgnoreCase("lang")) { lang=keyval[1].trim().split(","); } @@ -113,19 +101,19 @@ public ChannelSubs(String name,ArrayList data,File dPath) { if(matcher!=null) matcher.processProps(prop); } - + public String getName() { return name; } - + public void setName(String name) { this.name=name; } - + public String getImg() { return img; } - + private String rarFile(File f) { boolean concat=ChannelUtil.getProperty(prop, "rar_concat"); boolean keep=ChannelUtil.getProperty(prop, "rar_keep"); @@ -150,7 +138,7 @@ private String rarFile(File f) { if(concat) { if(first) { fName=(f.getAbsolutePath()+".srt").replace(".rar", ""); - fos = new FileOutputStream(fName); + fos = new FileOutputStream(fName); } } else { @@ -179,7 +167,7 @@ private String rarFile(File f) { return null; return cacheFile(new File(firstName)); } - + private String zipFile(File f) { boolean concat=ChannelUtil.getProperty(prop, "zip_concat"); boolean keep=ChannelUtil.getProperty(prop, "zip_keep"); @@ -208,12 +196,12 @@ private String zipFile(File f) { continue; if(rename) { String i=first?"":"_"+String.valueOf(id++); - fName=dPath+File.separator+i+entry.getName(); + fName=dPath+File.separator+i+entry.getName(); } if(concat) { if(first) { fName=(f.getAbsolutePath()+".srt").replace(".zip", ""); - FileOutputStream fos1 = new FileOutputStream(fName); + FileOutputStream fos1 = new FileOutputStream(fName); dest = new BufferedOutputStream(fos1, BUFFER); } } @@ -231,7 +219,7 @@ private String zipFile(File f) { if(!concat) { dest.flush(); dest.close(); - } + } } if(concat) { dest.flush(); @@ -241,24 +229,24 @@ private String zipFile(File f) { if(!keep) f.delete(); return cacheFile(new File(firstName)); // return the first name no matter what - } + } catch (Exception e) { Channels.debug("error "+e+" reading zipped subtile"); return null; } } - + private String cacheFile(File f) { ChannelUtil.cacheFile(f,"sub"); return f.getAbsolutePath(); } - + public String getSubs(String mediaName) { HashMap map=new HashMap(); map.put("url", mediaName); return getSubs(map); } - + public String getSubs(HashMap map) { String mediaName=map.get("url"); Channels.debug("get subs "+mediaName); @@ -290,7 +278,7 @@ public String getSubs(HashMap map) { boolean rar=ChannelUtil.getProperty(prop, "rar_force"); return downloadSubs(subUrl,path,zip,rar); } - + public static String downloadSubs(String subUrl) { int pos=subUrl.lastIndexOf('/'); String name="sub_"+System.currentTimeMillis(); @@ -298,16 +286,16 @@ public static String downloadSubs(String subUrl) { name=subUrl.substring(pos+1); return downloadSubs(subUrl,name); } - + public static String downloadSubs(String subUrl,String name) { name=name.replaceAll("[\\?&=;,]", "").replace('/', '_').replace('\\', '_'); String path=Channels.dataPath()+File.separator+name+".srt"; ChannelSubs nullSub=new ChannelSubs(); return nullSub.downloadSubs(subUrl,path,false,false); - + } - - + + private String downloadSubs(String subUrl,String path, boolean zip,boolean rar) { File f=new File(path); if(f.exists()) @@ -327,7 +315,7 @@ private String downloadSubs(String subUrl,String path, boolean zip,boolean rar) return rarFile(f); return cacheFile(f); } - + private String getMediaName(String mediaName,HashMap map) { if(nameScript!=null) { String nScript=nameScript[0]; @@ -343,12 +331,12 @@ private String getMediaName(String mediaName,HashMap map) { } else mediaName=ChannelUtil.escape(mediaName); - } + } else mediaName=ChannelUtil.escape(mediaName); return mediaName; } - + public String fetchSubsUrl(HashMap map) { String mediaName=map.get("url").trim(); mediaName=getMediaName(mediaName,map); @@ -362,7 +350,7 @@ public String fetchSubsUrl(HashMap map) { Channels.debug("subs page "+page); if(ChannelUtil.empty(page)) return null; - if(!ChannelUtil.empty(script)) { // we got a script, we'll use it + if(!ChannelUtil.empty(script)) { // we got a script, we'll use it ArrayList s=Channels.getScript(script); if(s!=null) { HashMap res=ChannelNaviXProc.lite(page, s,map); @@ -386,7 +374,7 @@ public String fetchSubsUrl(HashMap map) { } return null; } - + public HashMap select(HashMap map) { if(select==null) return null; @@ -434,15 +422,15 @@ public static String icon(Object obj,String icon) { if(obj instanceof String) return icon; ChannelSubSelected css=(ChannelSubSelected)obj; - if(ChannelUtil.empty(css.lang)) + if(ChannelUtil.empty(css.lang)) return icon; return "/resource/images/codes/"+ChannelISO.iso(css.lang, 3)+".png"; } - + public String resolve(ChannelSubSelected css) { return ""; } - + public static String resolve(Object obj) { if(obj instanceof String) return downloadSubs((String)obj); @@ -459,7 +447,7 @@ public static String resolve(Object obj) { else return downloadSubs(css.url,css.name); ArrayList s=Channels.getScript(css.script); - if(s==null) + if(s==null) return null; HashMap map=new HashMap(); map.put("select", "true"); @@ -474,25 +462,25 @@ public static String resolve(Object obj) { else return downloadSubs(subUrl,css.name); } - + public boolean langSupported() { return !ChannelUtil.empty(langPrefered()); } - + public String langPrefered() { if(lang==null) return null; String[] langCode=PMS.getConfiguration().getSubtitlesLanguages().split(","); if(lang[0].equals("all")) return langCode[0]; - for(int j=0;j hdr) { + HashMap hdr) { URL url=connection.getURL(); - connection.setDoOutput(true); - connection.setDoInput(true); - connection.setUseCaches(false); - connection.setDefaultUseCaches(false); - //connection.setAllowUserInteraction(true); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.setUseCaches(false); + connection.setDefaultUseCaches(false); + //connection.setAllowUserInteraction(true); connection.setRequestProperty ("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("User-Agent",defAgentString); if(query==null) query=""; - connection.setRequestProperty("Content-Length", "" + query.length()); - + connection.setRequestProperty("Content-Length", "" + query.length()); + try { String c1=ChannelCookie.getCookie(url.toString()); if(!empty(c1)) { @@ -78,7 +68,7 @@ public static String postPage(URLConnection connection,String query,String cooki if(!empty(cookie)) connection.setRequestProperty("Cookie",cookie); if(hdr!=null&&hdr.size()!=0) { - for(String key : hdr.keySet()) + for(String key : hdr.keySet()) connection.setRequestProperty(key,hdr.get(key)); } connection.setConnectTimeout(10000); @@ -87,8 +77,8 @@ public static String postPage(URLConnection connection,String query,String cooki // open up the output stream of the connection if(!empty(query)) { DataOutputStream output = new DataOutputStream(connection.getOutputStream()); - output.writeBytes(query); - output.flush (); + output.writeBytes(query); + output.flush (); output.close(); } @@ -110,15 +100,15 @@ public static String postPage(URLConnection connection,String query,String cooki return ""; } } - + public static String fetchPage(URLConnection connection) { return fetchPage(connection,null,"",null); } - + public static String fetchPage(URLConnection connection,ChannelAuth auth,String cookie) { return fetchPage(connection,auth,cookie,null); } - + public static String fetchPage(URLConnection connection,ChannelAuth auth,String cookie,HashMap hdr) { try { // URLConnection connection=url.openConnection(); @@ -129,7 +119,7 @@ public static String fetchPage(URLConnection connection,ChannelAuth auth,String Channels.debug("auth "+auth.method+" authstr "+auth.authStr); if(auth.method==ChannelLogin.STD) connection.setRequestProperty("Authorization", auth.authStr); - else if(auth.method==ChannelLogin.COOKIE) + else if(auth.method==ChannelLogin.COOKIE) cookie=append(cookie,"; ",auth.authStr); else if(auth.method==ChannelLogin.APIKEY) { url=new URL(url.toString()+auth.authStr); @@ -147,10 +137,10 @@ else if(auth.method==ChannelLogin.APIKEY) { if(!empty(cookie)) connection.setRequestProperty("Cookie",cookie); if(hdr!=null&&hdr.size()!=0) { - for(String key : hdr.keySet()) + for(String key : hdr.keySet()) connection.setRequestProperty(key,hdr.get(key)); } - // connection.setRequestProperty("Content-Length", "0"); + // connection.setRequestProperty("Content-Length", "0"); connection.setDoInput(true); connection.setDoOutput(true); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); @@ -171,7 +161,7 @@ else if(auth.method==ChannelLogin.APIKEY) { return ""; } } - + public static boolean cookieContains(String cookie1,String cookie0) { if(empty(cookie0)) return false; @@ -187,7 +177,7 @@ public static boolean cookieContains(String cookie1,String cookie0) { } return false; } - + public static boolean downloadText(InputStream in,File f) throws Exception { String subcp=getCodePage(); OutputStreamWriter out=new OutputStreamWriter(new FileOutputStream(f),subcp); @@ -205,11 +195,11 @@ public static boolean downloadText(InputStream in,File f) throws Exception { in.close(); return true; } - + public static boolean downloadBin(String url,File f) { return downloadBin(url,f,false); } - + public static boolean downloadBin(String url,File f,boolean text) { try { URL u=new URL(url); @@ -242,11 +232,11 @@ public static boolean downloadBin(String url,File f,boolean text) { } return false; } - + public static boolean empty(String s) { return (s==null)||(s.length()==0); } - + private static String findProperty(String[] props,String prop) { if(props==null) return null; @@ -256,7 +246,7 @@ private static String findProperty(String[] props,String prop) { } return null; } - + public static String getPropertyValue(String[] props,String prop) { String s=findProperty(props,prop); if(s==null) @@ -266,11 +256,11 @@ public static String getPropertyValue(String[] props,String prop) { return null; return ss[1]; } - + public static boolean getProperty(String[] props,String prop) { return (findProperty(props,prop)!=null); } - + public static ArrayList gatherBlock(String[] lines,int start) { ArrayList res=new ArrayList(); int curls=1; @@ -289,7 +279,7 @@ public static ArrayList gatherBlock(String[] lines,int start) { } return res; } - + public static ArrayList gatherBlock(ArrayList data,int start) { ArrayList res=new ArrayList(); int curls=1; @@ -308,7 +298,7 @@ public static ArrayList gatherBlock(ArrayList data,int start) { } return res; } - + public static String append(String res,String sep,String data) { res=ChannelUtil.separatorToken(res); data=ChannelUtil.separatorToken(data); @@ -321,18 +311,18 @@ public static String append(String res,String sep,String data) { return res+data; return res+sep+data; } - + public static ChannelMacro findMacro(ArrayList macros,String macro) { if(macros==null) return null; - for(int i=0;i vars,int format, Channel ch,RendererConfiguration render) { if(!empty(vars.get("bad"))) { @@ -536,18 +526,18 @@ public static String createMediaUrl(HashMap vars,int format, return null; rUrl=rUrl.replace("HTTP://", "http://"); // ffmpeg has problems with ucase HTTP int rtmpMet=Channels.rtmpMethod(); - String type=vars.get("__type__"); + String type=vars.get("__type__"); Channels.debug("create media url entry "+rUrl+" format "+format+" type "+type); if(rUrl.startsWith("http")) { if((format!=Format.VIDEO)|| - (rtmpMet==Channels.RTMP_MAGIC_TOKEN)) + (rtmpMet==Channels.RTMP_MAGIC_TOKEN)) return rUrl; //rUrl="navix://channel?url="+escape(rUrl); rUrl="channel?url="+escape(rUrl); String agent=vars.get("agent"); if(empty(agent)) agent=ChannelUtil.defAgentString; - rUrl=append(rUrl,"&agent=",escape(agent)); + rUrl=append(rUrl,"&agent=",escape(agent)); if(!empty(vars.get("referer"))) rUrl=append(rUrl,"&referer=",escape(vars.get("referer"))); String sub=vars.get("subtitle"); @@ -565,7 +555,7 @@ public static String createMediaUrl(HashMap vars,int format, Channels.debug("return media url "+rUrl); return rUrl; } - + if(!empty(type)&&type.equals("RTMPDUMP")) { Channels.debug("rmtpdump spec "+rUrl); String[] args=rUrl.split("!!!"); @@ -589,7 +579,7 @@ public static String createMediaUrl(HashMap vars,int format, Channels.debug("return media url rtmpdump spec "+rUrl); return rUrl; } - + String[] s=rUrl.split(" "); if(s.length>1) { // This is likely rtmp from navix @@ -602,18 +592,18 @@ public static String createMediaUrl(HashMap vars,int format, vars.put(ss[0].toLowerCase(), ss[1]); } } - + if(!rtmpStream(rUrl)) // type is sopcast etc. return rUrl; if(rUrl.startsWith("rtmpdump://")) return rUrl; - + switch(rtmpMet) { case Channels.RTMP_MAGIC_TOKEN: rUrl=ChannelUtil.append(rUrl, "!!!pms_ch_dash_y!!!", vars.get("playpath")); rUrl=ChannelUtil.append(rUrl, "!!!pms_ch_dash_w!!!", vars.get("swfVfy")); break; - + case Channels.RTMP_DUMP: Channels.debug("rtmpdump method"); rUrl="rtmpdump://channel?-r="+escape(rUrl); @@ -632,7 +622,7 @@ public static String createMediaUrl(HashMap vars,int format, rUrl=addSubs(rUrl,sub,ch,render); } break; - + default: rUrl=vars.get("url"); break; @@ -640,7 +630,7 @@ public static String createMediaUrl(HashMap vars,int format, Channels.debug("return media url "+rUrl); return rUrl; } - + public static String rtmpOp(String op) { if(op.equals("-r")) return ""; @@ -655,19 +645,19 @@ public static String rtmpOp(String op) { if(op.equals("--swfVfy")) return "swfVfy"; return op; - + } - + private static boolean backTrackCompensate(DLNAResource start) { // if we are in a subslector skip that - if(start instanceof ChannelPMSSubSelector) + if(start instanceof ChannelPMSSubSelector) return true; // Sub sites should be skipped to if(start instanceof ChannelPMSSubSiteSelector) return true; return false; } - + public static String backTrack(DLNAResource start,int stop) { if(start==null) return null; @@ -693,7 +683,7 @@ public static String backTrack(DLNAResource start,int stop) { return curr.getName(); return null; } - + public static String backTrack(DLNAResource start,int[] stops,String sep) { if(empty(sep)) sep=" "; @@ -705,13 +695,13 @@ public static String backTrack(DLNAResource start,int[] stops,String sep) { } return res; } - - + + public static String backTrack(DLNAResource start,int[] stops) { return backTrack(start,stops, " "); } - - + + public static int[] getNameIndex(String[] prop) { try { String x=ChannelUtil.getPropertyValue(prop, "name_index"); @@ -731,7 +721,7 @@ public static int[] getNameIndex(String[] prop) { } return null; } - + public static String mangle(String re,String str) { if(empty(re)) return str; @@ -743,7 +733,7 @@ public static String mangle(String re,String str) { res=res+m.group(i); return res; } - + public static String format2str(int format) { switch(format) { case Format.AUDIO: @@ -756,20 +746,20 @@ public static String format2str(int format) { return "Unknown"; } } - + public static String execute(String script,String url,int format) { return execute(script,url,format2str(format)); } - + public static String execute(String script,String url,String format) { ProcessBuilder pb=new ProcessBuilder(script,"\""+url+"\"",format); return execute(pb); } - + public static String execute(ProcessBuilder pb) { return execute(pb,false); } - + public static String execute(ProcessBuilder pb,boolean verbose) { try { Channels.debug("about to execute "+pb.command()); @@ -807,13 +797,13 @@ public static void cacheFile(File f,String type) { catch (Exception e) { } } - + public static Thread backgroundDownload(String name,String url,boolean cache) { String fName=ChannelUtil.guessExt(Channels.fileName(name, cache), url); if(ChannelUtil.rtmpStream(url)) { try { - // URL u=new URL(url); + // URL u=new URL(url); // rtmp stream special fix if(empty(extension(fName))) // no extension. Rtmp is normally mp4 fName=fName+".mp4"; @@ -832,7 +822,7 @@ public void run() { return null; } } - + String subFile=""; if(url.startsWith("http")|| url.startsWith("navix")|| @@ -878,7 +868,7 @@ public void run() { // ignore this Channels.debug("Error moving subtitle file "+sFile); } - } + } // download the actaul movie, subtitles are done downloadBin(rUrl,f); } @@ -887,7 +877,7 @@ public void run() { } return null; } - + private static ProcessBuilder buildPid(String fName,String url) { int rtmpMet=Channels.rtmpMethod(); if(rtmpMet==Channels.RTMP_MAGIC_TOKEN) { @@ -911,11 +901,11 @@ private static ProcessBuilder buildPid(String fName,String url) { args.add("\""+fName+"\""); return new ProcessBuilder(args); } - + public static int getFormat(String type) { return getFormat(type,-1); } - + public static int getFormat(String type,int def) { if(type.equalsIgnoreCase("image")) return Format.IMAGE; @@ -925,7 +915,7 @@ public static int getFormat(String type,int def) { return Format.AUDIO; return def; } - + public static Proxy proxy(ChannelAuth a) { if(a==null) return Proxy.NO_PROXY; @@ -933,7 +923,7 @@ public static Proxy proxy(ChannelAuth a) { return Proxy.NO_PROXY; return a.proxy.getProxy(); } - + public static String separatorToken(String str) { if(str==null) return null; @@ -943,20 +933,20 @@ public static String separatorToken(String str) { return "\r\n"; return str; } - + public static boolean cookieMethod(int method) { return (method==ChannelLogin.COOKIE)||(method==ChannelLogin.SIMPLE_COOKIE); } - + public static void list2file(StringBuilder sb,String[] list) { for(int i=0;i addStreamVars(List args,ChannelStreamVars streamVars, OutputParams params) { ArrayList res=new ArrayList(); @@ -1083,14 +1073,14 @@ public static List addStreamVars(List args,ChannelStreamVars str } return res; } - + public static String ensureImdbtt(String imdb) { /*if(empty(imdb)) return imdb; return (imdb.startsWith("tt")?imdb:"tt"+imdb);*/ return imdb; } - + public static String trimURL(String url) { String u1=url.replace("http://", "").replace("https://", ""); int p=u1.indexOf("/"); @@ -1101,7 +1091,7 @@ public static String trimURL(String url) { u1=u1.substring(p+1); return u1; } - + public static void killThread(Thread t) { if(t!=null) { t.interrupt(); @@ -1111,10 +1101,10 @@ public static void killThread(Thread t) { } } } - + public static final String REL_HOST = "host"; public static final String REL_PATH = "path"; - + public static String relativeURL(String rUrl,String pUrl,String relType) { if(empty(relType)|| empty(rUrl)|| @@ -1140,18 +1130,18 @@ public static String relativeURL(String rUrl,String pUrl,String relType) { } return rUrl; } - + public static void appendVarLine(StringBuffer sb,String var,String val) { sb.append(var); sb.append("="); sb.append(val.trim()); sb.append("\n"); } - + public static Thread newBackgroundDownload(final String name,String url) { if(ChannelUtil.rtmpStream(url)) { try { - // URL u=new URL(url); + // URL u=new URL(url); // rtmp stream special fix final ProcessBuilder pb=buildPid(name,url); if(pb==null) @@ -1210,7 +1200,7 @@ public void run() { // ignore this Channels.debug("Error moving subtitle file "+sFile); } - } + } // download the actaul movie, subtitles are done Channels.debug("rUrl "+rUrl); if(rUrl.contains(".m3u8")) { @@ -1242,11 +1232,11 @@ public void run() { } return null; } - + public static boolean filterInternals(DLNAResource r) { return ((r instanceof VirtualVideoAction)||(r instanceof ChannelPMSAllPlay)); } - + public static String searchInPath(DLNAResource res) { while(res!=null) { if((res instanceof Search)) { @@ -1258,7 +1248,7 @@ public static String searchInPath(DLNAResource res) { } return ""; } - + public static int convInt(String str,int def) { try { Integer i=Integer.valueOf(str); @@ -1275,5 +1265,5 @@ public static String getCodePage() { return "utf-8"; return cp; } - + } diff --git a/src/com/sharkhunter/channel/Channels.java b/src/com/sharkhunter/channel/Channels.java index 1e8ffc7..d409449 100644 --- a/src/com/sharkhunter/channel/Channels.java +++ b/src/com/sharkhunter/channel/Channels.java @@ -2,15 +2,11 @@ import java.io.BufferedReader; import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; @@ -24,14 +20,12 @@ import java.util.HashMap; import java.util.Iterator; import java.util.List; - import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; import org.apache.commons.io.FileUtils; - +import org.slf4j.LoggerFactory; import net.pms.PMS; import net.pms.dlna.DLNAResource; -import net.pms.dlna.PlaylistFolder; import net.pms.dlna.virtual.VirtualFolder; import net.pms.dlna.virtual.VirtualVideoAction; import no.geosoft.cc.io.FileListener; @@ -39,21 +33,23 @@ public class Channels extends VirtualFolder implements FileListener { + private static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(Channels.class); + // Version string public static final String VERSION="2.25"; public static final String ZIP_VER="211"; - + // Constants for RTMP string constructions public static final int RTMP_MAGIC_TOKEN=1; public static final int RTMP_DUMP=2; public int rtmp; - + public static final int DeafultContLim=5; public static final int ContSafetyVal=-100; - + // Define keywords private static final String[] defWords={"macrodef","scriptdef","subdef","proxydef"}; - + private File file; private FileMonitor fileMonitor; private ArrayList chFiles; @@ -85,7 +81,7 @@ public class Channels extends VirtualFolder implements FileListener { private VirtualFolder monitor; private ChannelMonitorMgr monMgr; private PropertiesConfiguration credConf; - + public Channels(String path,String name,String img) { super(name,img); // First the simple fields @@ -115,7 +111,7 @@ public Channels(String path,String name,String img) { searchDb=new ChannelSearch(new File(dataPath()+File.separator+"search.txt")); //rtmp=Channels.RTMP_MAGIC_TOKEN; rtmp=Channels.RTMP_DUMP; - PMS.minimal("Start channel "+VERSION); + LOGGER.info("{Channel} Starting channel {}", VERSION); dbg=new ChannelDbg(new File(path+File.separator+"channel.log")); dbg.start(); stash.put("default", new HashMap()); @@ -131,7 +127,7 @@ public Channels(String path,String name,String img) { addChild(local); } catch (MalformedURLException e) { } - + addChild(cache); addChild(searchDb); addChild(new ChannelPMSCode("Unlock All",null,true)); @@ -139,7 +135,7 @@ public Channels(String path,String name,String img) { allUnlocked=false; setOpenSubs(true); } - + private void addMonitor() { if(!cfg.monitor()) return; @@ -148,7 +144,7 @@ private void addMonitor() { addChild(monitor); clearMonitor(); } - + public void start(long poll) { addMonitor(); // Move any work favorites first @@ -187,7 +183,7 @@ public void start(long poll) { } catch (IOException e) { } } - + private void dumpEmptyCreds() throws IOException { for(Channel ch : getChannels()) { if(!ch.login()) @@ -204,7 +200,7 @@ private void dumpEmptyCreds() throws IOException { debug("error saving creds"); } } - + private void initNaviXUploader() { try { // must do this last we need some credentials first if(ChannelUtil.empty(cfg.getNaviXUpload())) { @@ -228,30 +224,30 @@ private void initNaviXUploader() { debug("error navix up startup "+e); } } - + public static void initNaviX() { inst.initNaviXUploader(); } - + public static void debug(String msg) { inst.dbg.debug("[Channel] "+msg); } - + public static void debug(boolean start) { if(start) inst.dbg.start(); else inst.dbg.stop(); } - + public static boolean debugStatus() { return inst.dbg.status(); } - + public static File dbgFile() { return inst.dbg.logFile(); } - + private Channel find(String name) { for(DLNAResource f:getChildren()) { if((f instanceof Channel)&&(f.getDisplayName().trim().equals(name.trim()))) @@ -259,13 +255,13 @@ private Channel find(String name) { } return null; } - + public static Channel findChannel(String name) { if(inst==null) new CH_plugin(); return inst.find(name); } - + public static ArrayList getChannels() { ArrayList res=new ArrayList(); for(DLNAResource f:inst.getChildren()) @@ -274,7 +270,7 @@ public static ArrayList getChannels() { } return res; } - + private void addFavorites() { if(noFavorite()) return; @@ -291,7 +287,7 @@ private void addFavorites() { } } } - + private void readChannel(String data) throws Exception { String str; String[] lines=data.split("\n"); @@ -317,15 +313,15 @@ private void readChannel(String data) throws Exception { ch.parse(chData,macros); initVar(chName,ch); addChild(ch); - } + } else { - PMS.minimal("channel "+chName+" was not parsed ok"); + LOGGER.warn("{Channel} Channel {} was not parsed ok", chName); } } } } } - + private void parseDefines(String data) { String str; String[] lines=data.split("\n"); @@ -406,13 +402,13 @@ private void parseDefines(String data) { } } } - + public void parseChannels(File f) throws Exception { BufferedReader in=new BufferedReader(new FileReader(f)); String str; boolean defines=false; StringBuilder sb=new StringBuilder(); - String ver="unknown"; + String ver="unknown"; while ((str = in.readLine()) != null) { str=str.trim(); if(ChannelUtil.ignoreLine(str)) @@ -433,18 +429,18 @@ public void parseChannels(File f) throws Exception { continue; ver=v[1]; continue; // don't append these - } - if(str.trim().startsWith("favorite")) + } + if(str.trim().startsWith("favorite")) defines=true; - if(str.trim().startsWith("illegal")) + if(str.trim().startsWith("illegal")) defines=true; - if(str.trim().startsWith("code")) + if(str.trim().startsWith("code")) defines=true; sb.append(str); sb.append("\n"); } in.close(); - PMS.minimal("parsing channel file "+f.toString()+" version "+ver); + LOGGER.info("{Channel} Parsing channel file {} version {}", f.toString(), ver); debug("parsing channel file "+f.toString()+" version "+ver); String s=sb.toString(); if(defines) @@ -453,8 +449,8 @@ public void parseChannels(File f) throws Exception { addCred(); addFavorites(); } - - + + private void addCred() { for(int i=0;i) { } catch (Exception e) { debug("handle cred exe "+e); - } + } } - + private void handleVCR(File f) throws IOException { - BufferedReader in = new BufferedReader(new FileReader(f)); - SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); + BufferedReader in = new BufferedReader(new FileReader(f)); + try { + SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); String str; GregorianCalendar now=new GregorianCalendar(); while ((str = in.readLine()) != null) { @@ -551,8 +548,11 @@ private void handleVCR(File f) throws IOException { name=data[3]; ChannelVCR.start(d,data[1],proc,name); } + } finally { + in.close(); + } } - + private void handleDirChange(File dir) throws Exception { if(!dir.exists()) // file (or dir is gone) ignore return; @@ -568,16 +568,16 @@ private void handleDirChange(File dir) throws Exception { fileMonitor.addFile(f); } catch (Exception e) { debug("Error parsing file "+f.toString()+" ("+e.toString()+")"); - } + } } } else if(f.getAbsolutePath().endsWith(".cred")) handleCred(f); else if(f.getAbsolutePath().endsWith(".vcr")) handleVCR(f); - else if(f.getAbsolutePath().contains("stream.var")) + else if(f.getAbsolutePath().contains("stream.var")) defStreamVar.parse(f); - } + } } @Override @@ -594,17 +594,17 @@ public void fileChanged(File f) { handleCred(f); else if(f.getAbsolutePath().endsWith(".vcr")) handleVCR(f); - else if(f.getAbsolutePath().contains("stream.var")) + else if(f.getAbsolutePath().contains("stream.var")) defStreamVar.parse(f); else if(f.exists()) parseChannels(f); } catch (Exception e) { - PMS.minimal("Error parsing file "+f.toString()+" ("+e.toString()+")"); - } + LOGGER.warn("{Channel} Error parsing file {} ({})", f.toString(), e.getLocalizedMessage()); + } } } - + ////////////////////////////////////// private void startOffHour() { @@ -627,40 +627,40 @@ private void startOffHour() { oh=new ChannelOffHour(max,dur,s[0],new File(ohDb),cache); oh.init(); } - + //////////////////////////////////// // Save handling //////////////////////////////////// - + public void setSave(String sPath) { setSave(sPath,null); - + } - + public void setSave(String sPath,String ts) { savePath=sPath; appendTS=(ChannelUtil.empty(ts)?false:true); cache.savePath(sPath); - if(oh==null) + if(oh==null) startOffHour(); - PMS.debug("[Channel]: using save path "+sPath); + LOGGER.debug("{Channel} Using save path {}", sPath); debug("using save path "+sPath); } - + public static boolean save() { return !ChannelUtil.empty(inst.savePath); } - + public static String fileName(String name,boolean cache) { return fileName(name,cache,null); } - + public static String fileName(String name,boolean cache,String imdb) { name=name.trim(); name=ChannelPMSSaveFolder.washName(name); - String ext=ChannelUtil.extension(name); + String ext=ChannelUtil.extension(name); String fName=name; - if(inst.appendTS) { + if(inst.appendTS) { // if we got an extension we move it to the end of the filename String ts="_"+String.valueOf(System.currentTimeMillis()); fName=ChannelUtil.append(name, null, ts); @@ -682,7 +682,7 @@ public static String fileName(String name,boolean cache,String imdb) { else return getPath()+File.separator+"data"+File.separator+fName; } - + public InputStream getThumbnailInputStream() { try { return downloadAndSend(thumbnailIcon,true); @@ -691,36 +691,36 @@ public InputStream getThumbnailInputStream() { return super.getThumbnailInputStream(); } } - + /////////////////////////////////////////// // Path handling /////////////////////////////////////////// - + public static String getSavePath() { return inst.savePath; } - + public static String getPath() { return inst.file.getAbsolutePath(); } - + public void setPath(String path) { debug("Set chanelpath to "+path); file=new File(path); } - + public static String dataPath() { return getPath()+File.separator+"data"; } - + public static String dataEntry(String str) { return dataPath()+File.separator+str; } - + //////////////////////////////////////////// // Script functions //////////////////////////////////////////// - + public static ArrayList getScript(String name) { if(ChannelUtil.empty(name)) return null; @@ -730,53 +730,53 @@ public static ArrayList getScript(String name) { } return null; } - + public static ChannelSubs getSubs(String name) { if(inst.openSubs!=null&&name.equals(inst.openSubs.getName())) return inst.openSubs; return inst.subtitles.get(name); } - + ///////////////////////////////// // RtmpMethod change ///////////////////////////////// - + public static void rtmpMethod(int newVal) { inst.rtmp=newVal; } - + public static int rtmpMethod() { return inst.rtmp; } - + public static void setSubs(boolean b) { inst.subs=b; } - + public static boolean doSubs() { return inst.subs; } - + public static boolean cache() { return inst.doCache; } - + public static void setCache(boolean b) { inst.doCache=true; } - + public static String cacheFile() { return inst.file.getAbsolutePath()+File.separator+"data"+File.separator+"cache"; } - + public static ChannelOffHour getOffHour() { return inst.oh; } - + public static ChannelCfg cfg() { return inst.cfg; } - + public void setCfg(ChannelCfg c) { cfg=c; if(!ChannelUtil.empty(cfg.getCredPath())&&!cfg.getCredPath().equals(file)) { @@ -796,65 +796,76 @@ public void setCfg(ChannelCfg c) { writeCookieFile(cfg.getCookiePath()); } } - + ////////////////////////////////////////// // Cookie mgmt ////////////////////////////////////////// - + public static boolean readCookieFile(String file) { return readCookieFile(file,inst.cookies); } - + public static boolean readCookieFile(String file,HashMap> map) { boolean skipped=false; + File cookieFile = new File(file); + if (!cookieFile.exists()) { + LOGGER.debug("{Channel} Cookie file \"{}\" not found - skipping", file); + return true; + } try { - BufferedReader in=new BufferedReader(new FileReader(file)); - String str; - while ((str = in.readLine()) != null) { - if(ChannelUtil.ignoreLine(str)) - continue; - str=str.trim(); - String[] line=str.split("\t"); - if(line.length<7) // bad line skip it - continue; - String url=line[0]; - String ttd0=line[4]; - String key=line[5]; - String val=line[6]; - long ttd=0; - try { - ttd=Long.parseLong(ttd0); - } - catch (NumberFormatException e1) { - } - if(ttd old=map.get(url); - if(old==null) { - old=new ArrayList(); - } - old.add(a); - map.put(url, old); - - } + + BufferedReader in=new BufferedReader(new FileReader(cookieFile)); + try { + String str; + while ((str = in.readLine()) != null) { + if(ChannelUtil.ignoreLine(str)) + continue; + str=str.trim(); + String[] line=str.split("\t"); + if(line.length<7) // bad line skip it + continue; + String url=line[0]; + String ttd0=line[4]; + String key=line[5]; + String val=line[6]; + long ttd=0; + try { + ttd=Long.parseLong(ttd0); + } + catch (NumberFormatException e1) { + } + if(ttd old=map.get(url); + if(old==null) { + old=new ArrayList(); + } + old.add(a); + map.put(url, old); + + } + } finally { + in.close(); + } } catch (Exception e) { - } + LOGGER.debug("{Channel} Exception caught in readCookieFile: {}", e); + } return skipped; } - + private static void writeCookieFile(String file) { try { FileOutputStream out=new FileOutputStream(file); // write a dummy line to make sure the file exists Date now=new Date(); - String data="# Cookie file generated "+ now.toString() +"\n"; + String data="# Cookie file generated "+ now.toString() +"\n"; out.write(data.getBytes(), 0, data.length()); for(String key : inst.cookies.keySet()) { ArrayList list= inst.cookies.get(key); @@ -864,15 +875,16 @@ private static void writeCookieFile(String file) { "\n"; out.write(data.getBytes(), 0, data.length()); } - } + } out.flush(); out.close(); } catch (Exception e) { + LOGGER.warn("{Channel} Error writing cookie file \"{}\": {}", file, e); debug("Error writing cookie file "+e); } } - + public static void mkCookieFile() { String file=cfg().getCookiePath(); if(ChannelUtil.empty(file)) @@ -912,7 +924,7 @@ public static void mkCookieFile() { f.delete(); // clear the file and the rewrite it writeCookieFile(file); } - + private static void mergeChannelAuths(ChannelAuth old,ArrayList list) { String cookie=old.authStr.split("=")[0]; ChannelAuth tmp=null; @@ -934,7 +946,7 @@ else if(old.ttd>a.ttd) list.add(tmp); } } - + private static boolean findCookie(ArrayList l,ChannelAuth a) { String cookie=a.authStr.split("=")[0]; for(int i=0;i l,ChannelAuth a) { } return false; } - + public static boolean addCookie(String url,ChannelAuth a) { ArrayList l=inst.cookies.get(url); - if(l==null) + if(l==null) l=new ArrayList(); if(!findCookie(l,a)) l.add(a); inst.cookies.put(url, l); return true; } - + public static ChannelAuth getCookie(String url) { ArrayList l=inst.cookies.get(url); if(l==null) @@ -969,18 +981,18 @@ public static ChannelAuth getCookie(String url) { } return a; } - + //////////////////////////////////////////////// // Handle search db ///////////////////////////////////////////////// - + private void initSearch(File f) throws Exception { if(!f.exists()) return; BufferedReader in=new BufferedReader(new FileReader(f)); String str; while ((str = in.readLine()) != null) { - if(ChannelUtil.ignoreLine(str)) + if(ChannelUtil.ignoreLine(str)) continue; str=str.trim(); String[] line=str.split(","); @@ -997,33 +1009,33 @@ private void initSearch(File f) throws Exception { in.close(); searchDb.dump(); } - + public static void addSearch(Channel ch,String id,String str) { debug("add search entry "+ch.name()+" "+id+" "+str); inst.searchDb.addSearch(ch, id, str); inst.searchDb.dump(); } - + //////////////////////////////////////////////////// // Proxy handling //////////////////////////////////////////////////// - + public static ChannelProxy getProxy(String name) { return inst.proxies.get(name); } - + ////////////////////////////////////////////// // Find stuff in the stash ///////////////////////////////////////////// - + public static HashMap getStash(String key) { return inst.stash.get(key); } - + public static String getStashData(String key,String stashKey) { return getStashData(key,stashKey,null); - } - + } + public static String getStashData(String key,String stashKey,String def) { HashMap s=getStash(key); if(s==null) @@ -1033,11 +1045,11 @@ public static String getStashData(String key,String stashKey,String def) { return def; return res; } - + public static void putStash(String stash,String key,String val) { putStash(stash,key,val,false); } - + public static void putStash(String stash,String key,String val,boolean create) { HashMap s=getStash(stash); if(s!=null) @@ -1046,25 +1058,25 @@ else if(create){ s=new HashMap(); s.put(key, val); inst.stash.put(stash, s); - } + } } - + ///////////////////////////////// // Groupfolder ///////////////////////////////// - + public static void setGroup(boolean b) { inst.groupFolder=b; } - + public static boolean useGroupFolder() { return inst.groupFolder; } - + /////////////////////////////////// // MovieInfo /////////////////////////////////// - + public static void setMovieInfo(boolean b) { if(b) { inst.movieInfo=null; @@ -1092,56 +1104,56 @@ public static void setMovieInfo(boolean b) { else inst.movieInfo=null; } - + public static boolean useMovieInfo() { return (inst.movieInfo!=null); } - + public static ChannelMovieInfo movieInfo() { return inst.movieInfo; } - + ///////////////////////////////////////////////// // Favorite handling methods ///////////////////////////////////////////////// - + public static File workFavFile() { return new File(getPath()+File.separator+"000favorite.work"); } - + public static File favFile() { return new File(getPath()+File.separator+"000favorite.ch"); } - + public static boolean noFavorite() { return !cfg().favorite(); } - + public static boolean noPlay() { return cfg().noPlay(); } - + ////////////////////////////////////////////////////////////// // ChannelVars handling ////////////////////////////////////////////////////////////// - + public void initVar(String channel,Channel ch) { cfg().chVars(channel,ch); } - + public static void setChVar(String ch,String inst,String var,String val) { cfg().putChVars(ch,inst,var,val); } - + //////////////////////////////////////////////////////////////// // ProxyDNS //////////////////////////////////////////////////////////////// - + private static boolean useProxyDNS(boolean channel) { int mode=cfg().proxyDNSMode(); return (mode==ChannelCfg.PROXY_DNS_CHANNEL)&&channel; } - + public static void setProxyDNS(boolean channel) { if(!useProxyDNS(channel)) return; @@ -1150,42 +1162,42 @@ public static void setProxyDNS(boolean channel) { return; setProxyDNS(p); } - + public static void setProxyDNS(String server) { debug("set DNS server to "+server); System.setProperty("sun.net.spi.nameservice.nameservers", server); System.setProperty("sun.net.spi.nameservice.provider.1", "dns,dnsjava"); } - + public static void restoreProxyDNS() { // trick here, if mode!=channel this is always false and we dont swap // the DNS back and forth - if(!useProxyDNS(true)) + if(!useProxyDNS(true)) return; System.clearProperty("sun.net.spi.nameservice.nameservers"); System.clearProperty("sun.net.spi.nameservice.provider.1"); } - + ////////////////////////////////////////////////////////////////////// - + public static ChannelStreamVars defStreamVar() { return inst.defStreamVar; } - + /////////////////////////////////////////////////////////////////////// - + private static boolean isIllegal(ArrayList list,String str,int type) { for(ChannelIllegal ill : list) { - if(ill.isIllegal(str, type)) + if(ill.isIllegal(str, type)) return true; } return false; } - + public static boolean isIllegal(String str,int type) { return isIllegal(inst.illegals,str,type); } - + public static boolean isCode(String str,int type) { if(allUnlocked()) return false; @@ -1193,27 +1205,27 @@ public static boolean isCode(String str,int type) { return false; return isIllegal(inst.codes,str,type); } - + public static String getCode() { if(cfg().stdAlone()) return ""; return (String) PMS.getConfiguration().getCustomProperty("channels.code"); } - + public static void unlockAll() { inst.allUnlocked=true; } - + public static boolean allUnlocked() { return inst.allUnlocked; } - + ////////////////////////////////////////////////////////////////////////// - + public static File localPLX() { return new File(dataPath()+File.separator+"navix_local.plx"); } - + public static void addToPLX(Channel ch,String name,String url,String proc,int format, String thumb,String imdb) throws IOException { FileWriter out=new FileWriter(localPLX(),true); @@ -1245,13 +1257,13 @@ public static void addToPLX(Channel ch,String name,String url,String proc,int fo out.write(sb.toString()); out.close(); } - + ////////////////////////////////////////////////////// - + public static ChannelSubs openSubs() { return inst.openSubs; } - + public static void setOpenSubs(boolean b) { if(b) { try { @@ -1265,28 +1277,28 @@ public static void setOpenSubs(boolean b) { else inst.openSubs=null; } - + //////////////////////////////////////////////////////////////// // Monitor stuff //////////////////////////////////////////////////////////////// - + private class ChannelPlainFolder extends VirtualFolder { public ChannelPlainFolder(String name) { super(name,null); } } - + private static File monitorFile() { return new File(dataPath()+File.separator+"monitor"); } - + private void parseMonitorFile() { File f=monitorFile(); if(!cfg.monitor()||!f.exists()) return; try { BufferedReader in=new BufferedReader(new FileReader(f)); - String str; + String str; ArrayList entries=null; String name=""; Channel owner=null; @@ -1375,9 +1387,9 @@ private void parseMonitorFile() { in.close(); } catch (Exception e) { debug("mon file parse error "+e); - } + } } - + private static String templWash(String name,String templ) { if(ChannelUtil.empty(templ)) return name; @@ -1385,8 +1397,8 @@ private static String templWash(String name,String templ) { vars.put("__wash__", "1"); return ChannelNaviXProc.simple(name, templ, vars); } - - + + private static String monNameWash(String name,String templ,String searched, String nameProp) { if(!ChannelUtil.empty(nameProp)&& @@ -1396,18 +1408,18 @@ private static String monNameWash(String name,String templ,String searched, } return templWash(name,templ); } - - + + public static void monitor(DLNAResource res,ChannelFolder cf, String data) throws IOException { monitor(res,cf,data,null); } - + public static void monitor(DLNAResource res,ChannelFolder cf, String data,String templ) throws IOException { if(!inst.cfg.monitor()) return; - if(inst.monMgr.monitored(res.getName())) + if(inst.monMgr.monitored(res.getName())) return; File f=monitorFile(); boolean newFile=!f.exists(); @@ -1470,7 +1482,7 @@ public static void monitor(DLNAResource res,ChannelFolder cf, } } } - + public static void updateMonitor(String monName,String newEntry) { try { if(!inst.monMgr.update(monName, newEntry)) // weird? @@ -1492,7 +1504,7 @@ public static void updateMonitor(String monName,String newEntry) { debug("update mon file error "+e); } } - + private void allPlayed(DLNAResource res,String name) { for(DLNAResource r : res.getChildren()) { if(r instanceof VirtualVideoAction) @@ -1500,7 +1512,7 @@ private void allPlayed(DLNAResource res,String name) { updateMonitor(name,r.getName()); } } - + private static DLNAResource findMonitorFolder(DLNAResource start,String name) { for(DLNAResource r : start.getChildren()) { if(name.equals(r.getName())) @@ -1508,7 +1520,7 @@ private static DLNAResource findMonitorFolder(DLNAResource start,String name) { } return null; } - + private void addNewMonitoredMedia_i(final DLNAResource r,final String folder) { DLNAResource f=findMonitorFolder(monitor,folder); if(f==null) { @@ -1523,23 +1535,23 @@ public boolean enable() { } }); } - f.addChild(r); + f.addChild(r); } public static void addNewMonitoredMedia(DLNAResource r,String folder) { inst.addNewMonitoredMedia_i(r, folder); } - + public static void clearNewMediaFolder(String folder) { DLNAResource f=findMonitorFolder(inst.monitor,folder); if(f!=null) inst.monitor.getChildren().remove(f); } - + public static boolean monitoredPlay(DLNAResource res) { return (inst.monitor==res); - } - + } + public static void clearMonitor() { inst.monitor.getChildren().clear(); inst.monitor.addChild(new VirtualVideoAction("Rescan",true) { @@ -1551,11 +1563,11 @@ public boolean enable() { } }); } - + /////////////////////////////////////////////////////// // URL Resolving /////////////////////////////////////////////////////// - + public String urlResolve(String url,boolean dummyOnly) { for(Channel ch : getChannels()) { String u = ch.urlResolve(url,dummyOnly); diff --git a/src/com/sharkhunter/channel/Search.java b/src/com/sharkhunter/channel/Search.java index 98bd2da..e90e9fb 100644 --- a/src/com/sharkhunter/channel/Search.java +++ b/src/com/sharkhunter/channel/Search.java @@ -4,44 +4,43 @@ public class Search extends VirtualFolder { private SearchObj sobj; - private String name; private StringBuilder sb; - private boolean searched; - - + private boolean searched; + + public Search(SearchObj obj) { this(obj,""); } - + public Search(SearchObj obj,String str) { super(str,null); this.sobj=obj; this.sb=new StringBuilder(str); searched=false; } - + public String result() { return sb.toString(); } - + public SearchObj getSearchObj() { return sobj; } - + public String getName() { return sb.toString(); } - + public String getSystemName() { return getName(); } - + public void resolve() { - discovered=false; + setDiscovered(false); } - + public synchronized void append(char ch) { - if(ch=='\0') + if(ch=='\0') sb=new StringBuilder(); else if(ch=='\b') { if(sb.length()!=0) @@ -50,12 +49,12 @@ else if(ch=='\b') { else this.sb.append(ch); } - + public void discoverChildren() { if(searched) { getChildren().clear(); } this.sobj.search(sb.toString(),this); searched=true; - } + } } diff --git a/src/com/sharkhunter/channel/SearchAction.java b/src/com/sharkhunter/channel/SearchAction.java index 27564fc..676887b 100644 --- a/src/com/sharkhunter/channel/SearchAction.java +++ b/src/com/sharkhunter/channel/SearchAction.java @@ -14,25 +14,25 @@ public class SearchAction extends VirtualFolder { public SearchAction(Search sobj,char ch) { this(sobj,ch,String.valueOf(ch)); } - + public SearchAction(Search sobj,char ch,String name) { super(name,"images/Play1Hot_120.jpg"); this.sobj=sobj; this.ch=ch; this.name=name; } - + public InputStream getThumbnailInputStream() { return getResourceInputStream("images/Play1Hot_120.jpg"); } - + public void resolve() { - discovered=false; // we can't clear this enough + setDiscovered(false); // we can't clear this enough } - + public void discoverChildren() { sobj.append(ch); - discovered=false; + setDiscovered(false); } @Override @@ -54,7 +54,7 @@ public long length() { public long lastModified() { return 0; } - + public String getThumbnailContentType() { return HTTPResource.JPEG_TYPEMIME; } diff --git a/src/com/sharkhunter/channel/SearchFolder.java b/src/com/sharkhunter/channel/SearchFolder.java index 0b123d0..c17a164 100644 --- a/src/com/sharkhunter/channel/SearchFolder.java +++ b/src/com/sharkhunter/channel/SearchFolder.java @@ -1,22 +1,19 @@ package com.sharkhunter.channel; -import java.io.*; - import net.pms.dlna.virtual.VirtualFolder; -import net.pms.PMS; public class SearchFolder extends VirtualFolder { private String name; private SearchObj sobj; private String result; - + public SearchFolder (String name,SearchObj sobj){ super(name,null); this.name=name; this.sobj=sobj; } - - + + private void createSearcher(SearchObj obj,String initStr) { char i; Search s=new Search(obj,initStr); @@ -24,15 +21,15 @@ private void createSearcher(SearchObj obj,String initStr) { addChild(new SearchAction(s,'\0',"Clear")); addChild(new SearchAction(s,' ',"Space")); addChild(new SearchAction(s,'\b',"Delete")); - for(i='A';i<='Z';i++) + for(i='A';i<='Z';i++) addChild(new SearchAction(s,i)); for(i='0';i<='9';i++) addChild(new SearchAction(s,i)); } - + public void resolve() { } - + public void discoverChildren(String str) { Channels.debug("search "+str); result=null; @@ -43,29 +40,29 @@ public void discoverChildren(String str) { sobj.search(str, this); } } - + public String result() { return result; } - + public boolean isSearched() { return true; } - + //@Override public void discoverChildren() { createSearcher(sobj,""); } - + public boolean isRefreshNeeded() { return true; } - + public boolean refreshChildren() { refreshChildren(null); return true; } - + public boolean refreshChildren(String str) { if(str==null) return false;