示例#1
0
        public long GetStatistic(RecognitionInfo selected) //get http add isGetting???
        {
            long res = 999999;

            Task.Run(() =>
            {
                try
                {
                    var httpResponse = client.GetAsync(url).Result;
                    var stats        = JsonConvert.DeserializeObject <long>(httpResponse.Content.ReadAsStringAsync().Result);
                    if (stats != 999999)
                    {
                        disp.BeginInvoke(new Action(() =>
                        {
                            res = stats;
                        }));
                    }
                }
                catch (AggregateException)
                {
                    disp.BeginInvoke(new Action(() =>
                    {
                        MessageBox.Show("NO CONNECTION", "Info");
                    }));
                }
            });
            Statistic = res;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Statistic"));
            return(res);
        }
示例#2
0
        public List <RecognitionContract> Post([FromBody] Dictionary <string, string> imgs)
        {
            List <RecognitionContract> predictionResults = new List <RecognitionContract>();

            imgs.Values.ToArray();
            model.MakePrediction(imgs);

            lock (model.recognitionLibraryContext)
            {
                foreach (var i in imgs)
                {
                    RecognitionInfo temp = new RecognitionInfo(i.Key, "", 0);
                    temp.Image = Convert.FromBase64String(i.Value);
                    var res = model.recognitionLibraryContext.FindOne(temp);
                    if (res == null)
                    {
                        Trace.WriteLine("Post null");
                    }
                    else
                    {
                        byte[] tmp1      = res.ImageDetails.Image;
                        var    converted = Convert.ToBase64String(tmp1);
                        predictionResults.Add(new RecognitionContract(i.Key, res.Label.ToString(), res.Confidence, converted));
                    }
                    Trace.WriteLine("Post " + i.Key + " " + res.Label + res.Confidence);
                }
            }

            return(predictionResults);
        }
示例#3
0
        public bool Said(string text, float confidence)
        {
            if (confidence < 0.0 || confidence > 1.0)
            {
                throw new ArgumentException("Confidence has to be between 0.0 and 1.0");
            }

            var init = EnsureRecognizer();

            if (!recognizerResults.ContainsKey(text))
            {
                var builder = new GrammarBuilder(text);
                recognitionEngine.LoadGrammarAsync(new Grammar(builder));
                recognizerResults[text] = new RecognitionInfo(confidence);
            }

            if (init)
            {
                recognitionEngine.SetInputToDefaultAudioDevice();
                recognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
            }
            var info   = recognizerResults[text];
            var result = info.Result;

            info.Result = false;

            return(result);
        }
示例#4
0
        public string GetImage([FromBody] List <string> img)
        {
            RecognitionInfo tmp = new RecognitionInfo(img[0], "", 0);

            tmp.Image = Convert.FromBase64String(img[1]);
            var res = model.recognitionLibraryContext.FindOne(tmp);

            return(res.Statistic.ToString());
        }
示例#5
0
文件: Recognizer.cs 项目: caoxk/coapp
 internal void CopyDetailsFrom(RecognitionInfo fileInfo)
 {
     FullPath          = fileInfo.FullPath;
     IsInvalid         = fileInfo.IsInvalid;
     IsPackageFile     = fileInfo.IsPackageFile;
     IsPackageFeed     = fileInfo.IsPackageFeed;
     IsCoAppMSI        = fileInfo.IsCoAppMSI;
     IsLegacyMSI       = fileInfo.IsLegacyMSI;
     IsLegacyEXE       = fileInfo.IsLegacyEXE;
     IsNugetPackage    = fileInfo.IsNugetPackage;
     IsOpenwrapPackage = fileInfo.IsOpenwrapPackage;
     IsArchive         = fileInfo.IsArchive;
     IsAtom            = fileInfo.IsAtom;
 }
        public List <RecognitionInfo> Post([FromBody] string dir)
        {
            List <RecognitionInfo> predictionResults = new List <RecognitionInfo>();

            model.MakePrediction(dir);
            lock (model.recognitionLibraryContext)
            {
                foreach (var path in Directory.GetFiles(dir).Where(s => s.EndsWith(".png") || s.EndsWith(".jpg") || s.EndsWith(".bmp") || s.EndsWith(".gif")))
                {
                    RecognitionInfo temp = new RecognitionInfo(path, "", 0);
                    var             res  = model.recognitionLibraryContext.FindOne(temp);
                    predictionResults.Add(new RecognitionInfo(path, res.Label.ToString(), res.Confidence));
                }
            }

            return(predictionResults);
        }
示例#7
0
        public bool Said(string text, float confidence)
        {
            if(confidence < 0.0 || confidence > 1.0) throw new ArgumentException("Confidence has to be between 0.0 and 1.0");

            var init = EnsureRecognizer();

            if (!recognizerResults.ContainsKey(text))
            {
                var builder = new GrammarBuilder(text);
                recognitionEngine.LoadGrammarAsync(new Grammar(builder));
                recognizerResults[text] = new RecognitionInfo(confidence);
            }

            if (init)
            {
                recognitionEngine.SetInputToDefaultAudioDevice();
                recognitionEngine.RecognizeAsync(RecognizeMode.Multiple);
            }
            var info = recognizerResults[text];
            var result = info.Result;
            info.Result = false;

            return result;
        }
示例#8
0
        internal static Task<RecognitionInfo> Recognize(string item, bool forceRescan = false)
        {
            var cachedResult = SessionCache<RecognitionInfo>.Value[item];
            if (cachedResult != null) {
                if (forceRescan) {
                    SessionCache<RecognitionInfo>.Value[item] = null;
                } else {
                    return cachedResult.AsResultTask();
                }
            }

            try {
                var location = new Uri(item);
                if (!location.IsFile) {
                    // some sort of remote item.
                    // since we can't do anything with a remote item directly,
                    // we have to issue a request to the client to get it for us

                    // before we go down this, check to see if we asked for it in this session
                    // in the last five minutes or so. We don't need to pound away at a URL for
                    // no reason.
                    var peek = SessionCache<RecognitionInfo>.Value[location.AbsoluteUri];
                    if( peek != null ) {
                        if( DateTime.Now.Subtract(peek.LastAccessed) < new TimeSpan(0,5,0) ) {
                            return peek.AsResultTask();
                        }
                    }

                    // since we're expecting that the canonicalname will be used as a filename
                    // in the .cache directory, we need to generate a safe filename based on the
                    // data in the URL
                    var safeCanonicalName = location.GetLeftPart(UriPartial.Path).MakeSafeFileName();

                    // BEFORE
                    // Check to see if there is a request for this file already in progress.
                    // attach a continuation to that if it is, instead of adding a new task
                    Task<RecognitionInfo> completion;
                    lock (SessionCache<Task<RecognitionInfo>>.Value) {
                        completion = SessionCache<Task<RecognitionInfo>>.Value[safeCanonicalName];
                        if (completion != null) {
                            return completion.ContinueAlways(antecedent => antecedent.Result);
                        }

                        // otherwise, let's create a delegate to run when the file gets resolved.
                        completion = new Task<RecognitionInfo>(rrfState => {
                            var state = rrfState as RequestRemoteFileState;
                            if (state == null || string.IsNullOrEmpty(state.LocalLocation)) {
                                // didn't fill in the local location? -- this happens when the client can't download.
                                // PackageManagerMessages.Invoke.FileNotRecognized() ?
                                var rslt = new RecognitionInfo {
                                    FullPath = location.AbsoluteUri,
                                    FullUrl = location,
                                    IsURL = true,
                                    IsInvalid = true,
                                };
                                // session cache it
                                SessionCache<RecognitionInfo>.Value[location.AbsoluteUri] = rslt;
                                return rslt;
                            }
                            var newLocation = new Uri(state.LocalLocation);
                            if (newLocation.IsFile) {
                                var continuedResult = Recognize(state.LocalLocation).Result;

                                // create the result object
                                var result = new RecognitionInfo {
                                    FullUrl = location,
                                };

                                // if( continuedResult.IsPackageFeed && forceRescan ) {
                                // this ensures that feed files aren't kept around needlessly.
                                //state.LocalLocation.MarkFileTemporary();
                                //}

                                result.CopyDetailsFrom(continuedResult);
                                result.IsURL = true;

                                return Cache(item, result);
                            }
                            // so, the callback comes, but it's not a file.
                            //
                            var r = new RecognitionInfo {
                                FullPath = location.AbsoluteUri,
                                IsInvalid = true,
                            };

                            // session cache it
                            SessionCache<RecognitionInfo>.Value[location.AbsoluteUri] = r;
                            return r;
                        }, new RequestRemoteFileState {
                            OriginalUrl = location.AbsoluteUri
                        }, TaskCreationOptions.AttachedToParent);

                        // store the task until the client tells us that it has the file.
                        SessionCache<Task<RecognitionInfo>>.Value[safeCanonicalName] = completion;
                    }

                    // GS01: Should we make a deeper path in the cache directory?
                    // perhaps that would let us use a cached version of the file we're looking for.
                    Event<GetResponseInterface>.RaiseFirst().RequireRemoteFile(safeCanonicalName, location.SingleItemAsEnumerable(),PackageManagerSettings.CoAppPackageCache, forceRescan);

                    // return the completion task, as whatever is waiting for this
                    // needs to continue on that.
                    return completion;
                }

                //----------------------------------------------------------------
                // we've managed to find a file system path.
                // let's figure out what it is.
                var localPath = location.LocalPath;

                if (localPath.Contains("?") || localPath.Contains("*")) {
                    // looks like a wildcard package feed.
                    // which is a directory feed with a filter.
                    var i = localPath.IndexOfAny(new[] {'*', '?'});

                    var lastSlash = localPath.LastIndexOf('\\', i);
                    var folder = localPath.Substring(0, lastSlash);
                    if (Directory.Exists(folder)) {
                        return CacheAndReturnTask(item, new RecognitionInfo {
                            FullPath = folder,
                            Filter = localPath.Substring(lastSlash + 1),
                            IsFolder = true,
                            IsPackageFeed = true
                        });
                    }
                }

                if (Directory.Exists(localPath)) {
                    // it's a directory.
                    // which means that it's a package feed.
                    return CacheAndReturnTask(item, new RecognitionInfo {
                        FullPath = localPath,
                        Filter = "*",
                        IsFolder = true,
                        IsPackageFeed = true,
                    });
                }

                if (File.Exists(localPath)) {
                    var ext = Path.GetExtension(localPath);
                    var result = new RecognitionInfo {
                        IsFile = true,
                        FullPath = localPath
                    };

                    switch (ext) {
                        case ".msi":
                            result.IsCoAppMSI = CoAppMSI.IsValidPackageFile(localPath);
                            result.IsLegacyMSI = !result.IsCoAppMSI;
                            result.IsPackageFile = true;
                            break;

                        case ".nupkg":
                            result.IsNugetPackage = true;
                            result.IsPackageFile = true;
                            break;

                        case ".exe":
                            result.IsLegacyEXE = true;
                            result.IsPackageFile = true;
                            break;

                        case ".zip":
                        case ".cab":
                        case ".rar":
                        case ".7z":
                            result.IsArchive = true;
                            result.IsPackageFeed = true;
                            break;

                        default:
                            // guess based on file contents
                            try {
                                if (CoAppMSI.IsValidPackageFile(localPath)) {
                                    result.IsCoAppMSI = true;
                                    result.IsPackageFile = true;
                                }
                            } catch {
                                // not a coapp file...
                            }

                            if (localPath.IsXmlFile()) {
                                try {
                                    // this could be an atom feed
                                    var feed = AtomFeed.LoadFile(localPath);
                                    if (feed != null) {
                                        result.IsPackageFeed = true;
                                        result.IsAtom = true;
                                    }
                                } catch {
                                    // can't seem to figure out what this is.
                                    result.IsInvalid = true;
                                }
                            }
                            break;
                    }
                    return CacheAndReturnTask(item, result);
                }
            } catch (UriFormatException) {
            }
            // item wasn't able to match any known URI, UNC or Local Path format.
            // or was file not found
            return new RecognitionInfo {
                FullPath = item,
                IsInvalid = true,
            }.AsResultTask();
        }
示例#9
0
 internal void CopyDetailsFrom(RecognitionInfo fileInfo)
 {
     FullPath = fileInfo.FullPath;
     IsInvalid = fileInfo.IsInvalid;
     IsPackageFile = fileInfo.IsPackageFile;
     IsPackageFeed = fileInfo.IsPackageFeed;
     IsCoAppMSI = fileInfo.IsCoAppMSI;
     IsLegacyMSI = fileInfo.IsLegacyMSI;
     IsLegacyEXE = fileInfo.IsLegacyEXE;
     IsNugetPackage = fileInfo.IsNugetPackage;
     IsOpenwrapPackage = fileInfo.IsOpenwrapPackage;
     IsArchive = fileInfo.IsArchive;
     IsAtom = fileInfo.IsAtom;
 }
示例#10
0
 private static RecognitionInfo Cache(string itemPath, RecognitionInfo recognitionInfo)
 {
     SessionCache<RecognitionInfo>.Value[itemPath] = recognitionInfo;
     return recognitionInfo;
 }
示例#11
0
 private static Task<RecognitionInfo> CacheAndReturnTask(string itemPath, RecognitionInfo recognitionInfo)
 {
     SessionCache<RecognitionInfo>.Value[itemPath] = recognitionInfo;
     return recognitionInfo.AsResultTask();
 }
示例#12
0
 private static Task<RecognitionInfo> CacheAndReturnTask(string itemPath, RecognitionInfo recognitionInfo)
 {
     lock (typeof(Recognizer)) {
         return (SessionData.Current.RecognitionInfo[itemPath] = recognitionInfo).AsResultTask();
     }
 }
示例#13
0
        internal static Task<RecognitionInfo> Recognize(string item, bool forceRescan = false)
        {
            var cachedResult = SessionData.Current.RecognitionInfo[item];

            if (cachedResult != null) {
                if (forceRescan) {
                    SessionData.Current.RecognitionInfo[item] = null;
                } else {
                    return cachedResult.AsResultTask();
                }
            }

            try {
                var location = new Uri(item);
                if (!location.IsFile) {
                    // some sort of remote item.
                    // since we can't do anything with a remote item directly,
                    // we have to issue a request to the client to get it for us

                    // before we go down this, check to see if we asked for it in this session
                    // in the last five minutes or so. We don't need to pound away at a URL for
                    // no reason.
                    var peek = SessionData.Current.RecognitionInfo[location.AbsoluteUri];
                    if( peek != null ) {
                        if( DateTime.Now.Subtract(peek.LastAccessed) < new TimeSpan(0,5,0) ) {
                            return peek.AsResultTask();
                        }
                    }

                    // since we're expecting that the canonicalname will be used as a filename
                    // in the .cache directory, we need to generate a safe filename based on the
                    // data in the URL
                    var safeCanonicalName = location.GetLeftPart(UriPartial.Path).MakeSafeFileName();

                    return SessionData.Current.RequireRemoteFile(safeCanonicalName, location.SingleItemAsEnumerable(), PackageManagerSettings.CoAppPackageCache, forceRescan, state => {
                        if (state == null || string.IsNullOrEmpty(state.LocalLocation)) {
                            // didn't fill in the local location? -- this happens when the client can't download.
                            return Cache(location.AbsoluteUri, new RecognitionInfo {
                                FullPath = location.AbsoluteUri,
                                FullUrl = location,
                                IsURL = true,
                                IsInvalid = true,
                            });
                        }

                        var newLocation = new Uri(state.LocalLocation);
                        if (newLocation.IsFile) {
                            var continuedResult = Recognize(state.LocalLocation).Result;

                            // create the result object
                            var result = new RecognitionInfo {
                                FullUrl = location,
                            };

                            result.CopyDetailsFrom(continuedResult);
                            result.IsURL = true;

                            return Cache(item, result);
                        }

                        // so, the callback comes, but it's not a file.
                        // session cache it
                        return Cache(location.AbsoluteUri,new RecognitionInfo {
                            FullPath = location.AbsoluteUri,
                            IsInvalid = true,
                        });
                    }) as Task<RecognitionInfo>;
                }

                //----------------------------------------------------------------
                // we've managed to find a file system path.
                // let's figure out what it is.
                var localPath = location.LocalPath;

                if (localPath.Contains("?") || localPath.Contains("*")) {
                    // looks like a wildcard package feed.
                    // which is a directory feed with a filter.
                    var i = localPath.IndexOfAny(new[] {'*', '?'});

                    var lastSlash = localPath.LastIndexOf('\\', i);
                    var folder = localPath.Substring(0, lastSlash);
                    if (Directory.Exists(folder)) {
                        return CacheAndReturnTask(item, new RecognitionInfo {
                            FullPath = folder,
                            Filter = localPath.Substring(lastSlash + 1),
                            IsFolder = true,
                            IsPackageFeed = true
                        });
                    }
                }

                if (Directory.Exists(localPath)) {
                    // it's a directory.
                    // which means that it's a package feed.
                    return CacheAndReturnTask(item, new RecognitionInfo {
                        FullPath = localPath,
                        Filter = "*.msi", // TODO: evenutally, we have to expand this to detect other types.
                        IsFolder = true,
                        IsPackageFeed = true,
                    });
                }

                if (File.Exists(localPath)) {
                    var ext = Path.GetExtension(localPath);
                    var result = new RecognitionInfo {
                        IsFile = true,
                        FullPath = localPath
                    };

                    switch (ext) {
                        case ".msi":
                            result.IsCoAppMSI = CoAppMSI.IsValidPackageFile(localPath);
                            result.IsLegacyMSI = !result.IsCoAppMSI;
                            result.IsPackageFile = true;
                            break;

                        case ".nupkg":
                            result.IsNugetPackage = true;
                            result.IsPackageFile = true;
                            break;

                        case ".exe":
                            result.IsLegacyEXE = true;
                            result.IsPackageFile = true;
                            break;

                        case ".zip":
                        case ".cab":
                        case ".rar":
                        case ".7z":
                            result.IsArchive = true;
                            result.IsPackageFeed = true;
                            break;

                        default:
                            // guess based on file contents
                            try {
                                if (CoAppMSI.IsValidPackageFile(localPath)) {
                                    result.IsCoAppMSI = true;
                                    result.IsPackageFile = true;
                                }
                            } catch {
                                // not a coapp file...
                            }

                            if (localPath.IsXmlFile()) {
                                try {
                                    // this could be an atom feed
                                    var feed = AtomFeed.LoadFile(localPath);
                                    if (feed != null) {
                                        result.IsPackageFeed = true;
                                        result.IsAtom = true;
                                    }
                                } catch {
                                    // can't seem to figure out what this is.
                                    result.IsInvalid = true;
                                }
                            }
                            break;
                    }
                    return CacheAndReturnTask(item, result);
                }
            } catch (UriFormatException) {
            }
            // item wasn't able to match any known URI, UNC or Local Path format.
            // or was file not found
            return new RecognitionInfo {
                FullPath = item,
                IsInvalid = true,
            }.AsResultTask();
        }
示例#14
0
 private static RecognitionInfo Cache(string itemPath, RecognitionInfo recognitionInfo)
 {
     lock (typeof(Recognizer)) {
         return SessionData.Current.RecognitionInfo[itemPath] = recognitionInfo;
     }
 }
示例#15
0
        internal static Task<RecognitionInfo> Recognize(string item, string baseDirectory = null, string baseUrl = null, bool ensureLocal = false)
        {
            if (_cache.ContainsKey(item)) {
                return CoTaskFactory<RecognitionInfo>.AsTaskResult(_cache[item]);
            }

            baseDirectory = baseDirectory ?? Environment.CurrentDirectory;

            var result = new RecognitionInfo();

            if (item.StartsWith("pkg:", StringComparison.CurrentCultureIgnoreCase)) {
                // this is a coapp package reference
                result.IsReference = true;
                result.IsCoAppMSI = true;
            }

            if (item.StartsWith("nuget:", StringComparison.CurrentCultureIgnoreCase)) {
                // this is a nuget package reference
                result.IsReference = true;
                result.IsNugetPackage = true;
            }

            if (item.StartsWith("msi:", StringComparison.CurrentCultureIgnoreCase)) {
                // this is a msi package reference
                result.IsReference = true;
                result.IsLegacyMSI = true;
            }

            if (item.StartsWith("openwrap:", StringComparison.CurrentCultureIgnoreCase)) {
                // this is a msi package reference
                result.IsReference = true;
                result.IsOpenwrapPackage = true;
            }

            // Is this an URL of some kind?
            if (result.IsUnknown) {
                try {
                    if (item.IndexOf("://") > -1) {
                        // some sort of URL
                        result.IsURL = true;
                        result.FullUrl = new Uri(item);
                    }
                    else if (!string.IsNullOrEmpty(baseUrl)) {
                        // it's a relative URL?
                        result.IsURL = true;
                        result.FullUrl = new Uri(new Uri(baseUrl), item);
                    }

                    // for now, we've got a full URL and it looks like it point somewhere.
                    // until we attempt to retrieve the URL we really can't bank on knowing what it is.
                    if (result.IsURL) {
                        return CoTask<RecognitionInfo>.Factory.StartNew(() => {
                            result.RemoteFile.Preview().Wait();

                            if (result.RemoteFile.LastStatus != HttpStatusCode.OK) {
                                result.IsInvalid = true;
                                result.Recognized.Value = true;
                                lock (_cache) {
                                    _cache.Add(item, result);
                                }
                                return result;
                            }

                            if (result.RemoteFile.IsRedirect) {
                                result.RemoteFile.Folder = _transferManager[result.RemoteFile.ActualRemoteLocation].Folder;
                            }

                            result.FullPath = result.RemoteFile.LocalFullPath;

                            if (ensureLocal) {
                                if (!result.IsLocal) {
                                    result.RemoteFile.Get().Wait();
                                }

                                if (!result.IsLocal) {
                                    result.IsInvalid = true;
                                    result.Recognized.Value = true;
                                    lock (_cache) {
                                        _cache.Add(item, result);
                                    }
                                    return result;
                                }
                            }

                            if (result.IsLocal) {
                                var localFileInfo = Recognize(result.FullPath).Result;
                                // at this point, we should actually know the real file results.
                                result.CopyDetailsFrom(localFileInfo);
                                result.Recognized.Value = true;
                                lock (_cache) {
                                    _cache.Add(item, result);
                                }
                                return result;
                            }

                            // if it isn't local, and we've not been told to bring it local,
                            // we could guess?
                            // we could just tell im, we dunno...
                            // GS01: TODO : We're claiming ignorance right now.

                            lock (_cache) {
                                _cache.Add(item, result);
                            }
                            return result;
                        }); // GS01: TODO : This is bad mojo--replace with better use of returning the child task
                        /*
                        result.RemoteFile.Preview().ContinueWithParent(antecedent => {
                            if (result.RemoteFile.LastStatus != HttpStatusCode.OK) {
                                result.IsInvalid = true;
                                result.Recognized.Value = true;
                                return;
                            }

                            if (result.RemoteFile.IsRedirect) {
                                result.RemoteFile.Folder = _transferManager[result.RemoteFile.ActualRemoteLocation].Folder;
                            }

                            result.FullPath = result.RemoteFile.LocalFullPath;

                            if (ensureLocal) {
                                if (!result.IsLocal) {
                                    result.RemoteFile.Get().Wait();
                                }

                                if (!result.IsLocal) {
                                    result.IsInvalid = true;
                                    result.Recognized.Value = true;
                                    return;
                                }
                            }

                            if (result.IsLocal) {
                                var localFileInfo = Recognize(result.FullPath);
                                // at this point, we should actually know the real file results.
                                result.CopyDetailsFrom(localFileInfo);
                                result.Recognized.Value = true;
                                return;
                            }

                            // not local. all we can do is guess?
                            // TODO: Implement remote guess?
                        });
                         * * */
                    }

                }
                catch
                {
                }
            }

            if (result.IsUnknown) {
                if (item.IndexOf('?') > -1 || item.IndexOf('*') > -1) {
                    // this has a wildcard. Past that, we don't know what it is yet.
                    // assuming this is a local path expression:
                    //     c:\foo\*.msi
                    //     App*.msi          (matching in the current dir)
                    //     packages\*
                    var folder = baseDirectory;
                    var lastSlash = item.LastIndexOf("\\");
                    if (lastSlash > -1) {
                        folder = Path.GetFullPath(item.Substring(0, lastSlash));
                    }

                    if (folder.IndexOf('?') == -1 && folder.IndexOf('*') == -1) {
                        if (Directory.Exists(folder)) {
                            result.IsFolder = true;
                            result.FullPath = Path.GetFullPath(folder).ToLower();
                            result.Wildcard = item.Substring(lastSlash + 1);
                        }
                    }
                }
            }

            // Is this a directory?
            if (result.IsUnknown) {
                try {
                    if (Directory.Exists(item)) {
                        // a valid directory
                        result.IsFolder = true;
                        result.FullPath = Path.GetFullPath(item).ToLower();
                    }
                    else if (!string.IsNullOrEmpty(baseDirectory)) {
                        var path = Path.Combine(baseDirectory, item).ToLower();
                        if (Directory.Exists(path)) {
                            result.IsFolder = true;
                            result.FullPath = path;
                        }
                    }

                    if (result.IsFolder) {
                        result.IsPackageFeed = true;
                    }
                }
                catch {
                }
            }

            // maybe it's a file?
            if (result.IsUnknown) {
                try {
                    if (File.Exists(item)) {
                        // some type of file
                        result.IsFile = true;
                        result.FullPath = Path.GetFullPath(item).ToLower();
                    }
                    else if (!string.IsNullOrEmpty(baseDirectory)) {
                        var path = Path.Combine(baseDirectory, item);
                        if (File.Exists(path)) {
                            result.IsFile = true;
                            result.FullPath = Path.GetFullPath(path).ToLower();
                        }

                    }

                    if (result.IsFile) {
                        // so, this is a file.
                        // let's do a little bit of diggin'

                        var ext = Path.GetExtension(result.FullPath);

                        switch (ext) {
                            case ".msi":
                                result.IsCoAppMSI = CoAppMSI.IsCoAppPackageFile(result.FullPath);
                                result.IsLegacyMSI = !result.IsCoAppMSI;
                                result.IsPackageFile = true;
                                break;

                            case ".nupkg":
                                result.IsNugetPackage = true;
                                result.IsPackageFile = true;
                                break;

                            case ".exe":
                                result.IsLegacyEXE = true;
                                result.IsPackageFile = true;
                                break;

                            case ".zip":
                            case ".cab":
                            case ".rar":
                            case ".7z":
                                result.IsArchive = true;
                                result.IsPackageFeed = true;
                                break;

                            default:
                                if (result.FullPath.IsXmlFile()) {
                                    try {
                                        var feed = AtomFeed.Load(result.FullPath);
                                        if (feed != null) {
                                            result.IsPackageFeed = true;
                                            result.IsAtom = true;
                                        }
                                    }
                                    catch {
                                    }
                                }
                                break;
                        }
                    }
                }
                catch {
                }
            }
            if (!result.IsUnknown) {
                result.Recognized.Value = true;
            }

            lock (_cache) {
                _cache.Add(item, result);
            }
            return CoTaskFactory<RecognitionInfo>.AsTaskResult(result);
        }
示例#16
0
文件: Recognizer.cs 项目: caoxk/coapp
 private static Task <RecognitionInfo> CacheAndReturnTask(string itemPath, RecognitionInfo recognitionInfo)
 {
     lock (typeof(Recognizer)) {
         return((SessionData.Current.RecognitionInfo[itemPath] = recognitionInfo).AsResultTask());
     }
 }
示例#17
0
文件: Recognizer.cs 项目: caoxk/coapp
        internal static Task <RecognitionInfo> Recognize(string item, bool forceRescan = false)
        {
            var cachedResult = SessionData.Current.RecognitionInfo[item];

            if (cachedResult != null)
            {
                if (forceRescan)
                {
                    SessionData.Current.RecognitionInfo[item] = null;
                }
                else
                {
                    return(cachedResult.AsResultTask());
                }
            }

            try {
                var location = new Uri(item);
                if (!location.IsFile)
                {
                    // some sort of remote item.
                    // since we can't do anything with a remote item directly,
                    // we have to issue a request to the client to get it for us

                    // before we go down this, check to see if we asked for it in this session
                    // in the last five minutes or so. We don't need to pound away at a URL for
                    // no reason.
                    var peek = SessionData.Current.RecognitionInfo[location.AbsoluteUri];
                    if (peek != null)
                    {
                        if (DateTime.Now.Subtract(peek.LastAccessed) < new TimeSpan(0, 5, 0))
                        {
                            return(peek.AsResultTask());
                        }
                    }

                    // since we're expecting that the canonicalname will be used as a filename
                    // in the .cache directory, we need to generate a safe filename based on the
                    // data in the URL
                    var safeCanonicalName = location.GetLeftPart(UriPartial.Path).MakeSafeFileName();

                    return(SessionData.Current.RequireRemoteFile(safeCanonicalName, location.SingleItemAsEnumerable(), PackageManagerSettings.CoAppPackageCache, forceRescan, state => {
                        if (state == null || string.IsNullOrEmpty(state.LocalLocation))
                        {
                            // didn't fill in the local location? -- this happens when the client can't download.
                            return Cache(location.AbsoluteUri, new RecognitionInfo {
                                FullPath = location.AbsoluteUri,
                                FullUrl = location,
                                IsURL = true,
                                IsInvalid = true,
                            });
                        }

                        var newLocation = new Uri(state.LocalLocation);
                        if (newLocation.IsFile)
                        {
                            var continuedResult = Recognize(state.LocalLocation).Result;

                            // create the result object
                            var result = new RecognitionInfo {
                                FullUrl = location,
                            };

                            result.CopyDetailsFrom(continuedResult);
                            result.IsURL = true;

                            return Cache(item, result);
                        }

                        // so, the callback comes, but it's not a file.
                        // session cache it
                        return Cache(location.AbsoluteUri, new RecognitionInfo {
                            FullPath = location.AbsoluteUri,
                            IsInvalid = true,
                        });
                    }) as Task <RecognitionInfo>);
                }

                //----------------------------------------------------------------
                // we've managed to find a file system path.
                // let's figure out what it is.
                var localPath = location.LocalPath;

                if (localPath.Contains("?") || localPath.Contains("*"))
                {
                    // looks like a wildcard package feed.
                    // which is a directory feed with a filter.
                    var i = localPath.IndexOfAny(new[] { '*', '?' });

                    var lastSlash = localPath.LastIndexOf('\\', i);
                    var folder    = localPath.Substring(0, lastSlash);
                    if (Directory.Exists(folder))
                    {
                        return(CacheAndReturnTask(item, new RecognitionInfo {
                            FullPath = folder,
                            Filter = localPath.Substring(lastSlash + 1),
                            IsFolder = true,
                            IsPackageFeed = true
                        }));
                    }
                }

                if (Directory.Exists(localPath))
                {
                    // it's a directory.
                    // which means that it's a package feed.
                    return(CacheAndReturnTask(item, new RecognitionInfo {
                        FullPath = localPath,
                        Filter = "*.msi", // TODO: evenutally, we have to expand this to detect other types.
                        IsFolder = true,
                        IsPackageFeed = true,
                    }));
                }

                if (File.Exists(localPath))
                {
                    var ext    = Path.GetExtension(localPath);
                    var result = new RecognitionInfo {
                        IsFile   = true,
                        FullPath = localPath
                    };

                    switch (ext)
                    {
                    case ".msi":
                        result.IsCoAppMSI    = CoAppMSI.IsValidPackageFile(localPath);
                        result.IsLegacyMSI   = !result.IsCoAppMSI;
                        result.IsPackageFile = true;
                        break;

                    case ".nupkg":
                        result.IsNugetPackage = true;
                        result.IsPackageFile  = true;
                        break;

                    case ".exe":
                        result.IsLegacyEXE   = true;
                        result.IsPackageFile = true;
                        break;

                    case ".zip":
                    case ".cab":
                    case ".rar":
                    case ".7z":
                        result.IsArchive     = true;
                        result.IsPackageFeed = true;
                        break;

                    default:
                        // guess based on file contents
                        try {
                            if (CoAppMSI.IsValidPackageFile(localPath))
                            {
                                result.IsCoAppMSI    = true;
                                result.IsPackageFile = true;
                            }
                        } catch {
                            // not a coapp file...
                        }

                        if (localPath.IsXmlFile())
                        {
                            try {
                                // this could be an atom feed
                                var feed = AtomFeed.LoadFile(localPath);
                                if (feed != null)
                                {
                                    result.IsPackageFeed = true;
                                    result.IsAtom        = true;
                                }
                            } catch {
                                // can't seem to figure out what this is.
                                result.IsInvalid = true;
                            }
                        }
                        break;
                    }
                    return(CacheAndReturnTask(item, result));
                }
            } catch (UriFormatException) {
            }
            // item wasn't able to match any known URI, UNC or Local Path format.
            // or was file not found
            return(new RecognitionInfo {
                FullPath = item,
                IsInvalid = true,
            }.AsResultTask());
        }
示例#18
0
文件: Recognizer.cs 项目: caoxk/coapp
 private static RecognitionInfo Cache(string itemPath, RecognitionInfo recognitionInfo)
 {
     lock (typeof(Recognizer)) {
         return(SessionData.Current.RecognitionInfo[itemPath] = recognitionInfo);
     }
 }