Exemplo n.º 1
0
        internal void RemoveTask(ABInfo abInfo, BackGroundQueue bQueue)
        {
            loadingTasks.Remove(abInfo);
            bool isError    = abInfo.state != ABInfoState.Success;
            var  mainAbInfo = ManifestManager.GetABInfo(abInfo.abName);

            if (mainAbInfo != null)
            {
                mainAbInfo.state = abInfo.state;
            }
#if UNITY_EDITOR
            Debug.LogFormat("task complete abName={0},size={1},isError={2},loadingTasks.Count={3},bQueue.count={4}", abInfo.abName, abInfo.size, isError, loadingTasks.Count, bQueue.Count);
#endif
            bQueue.Complete(abInfo, isError);

            if (!bQueue.IsError)
            {
                LoadingQueue();
            }
        }
Exemplo n.º 2
0
        // Start is called before the first frame update
        void Awake()
        {
            DontDestroyOnLoad(this.gameObject);
            Executor.Initialize();
            if (ManifestManager.fileManifest == null)
            {
                ManifestManager.LoadFileManifest(null);
            }

            if (luaenv == null)
            {
                luaenv = new LuaEnv();
            }
            luaenv.AddLoader(Loader);
            luaenv.DoString("require('" + enterLua + "')");
#if UNITY_EDITOR
            Debug.LogFormat("<color=green>running {0} mode </color> <color=#8cacbc> change( menu Hugula->Debug Lua)</color>", isDebug ? "debug" : "release");
#endif
            Manager.Add(this.GetType(), this);
        }
Exemplo n.º 3
0
        // Start is called before the first frame update
        IEnumerator Start()
        {
            ResourcesLoader.Initialize();
            ResourcesLoader.RegisterOverrideBaseAssetbundleURL(OverrideBaseAssetbundleURL);
            ManifestManager.LoadFileManifest(null);

#if  UNITY_ANDROID && !UNITY_EDITOR
            if (ManifestManager.fileManifest == null)
            {
                //todo obb丢失
            }
#endif
#if UNITY_EDITOR
            yield return(null);

            LoadBeginScene();
#else
            return(LoadRemoteVersion());
#endif
        }
Exemplo n.º 4
0
        /// <summary>
        /// Start synchronous dispose
        /// </summary>
        /// <returns>can we continue with dispose or not</returns>
        private bool DisposeStart()
        {
            if (Interlocked.CompareExchange(ref startedDisposing, 1, 0) == 1)
            {
                return(false);
            }
            disposeLatencyTimer = new Stopwatch();
            disposeLatencyTimer.Start();
            if (!isInitialized)
            {
                if (!isSessionStarted)
                {
                    Start();
                }
                if (!ManifestManager.ForceReadManifest())
                {
                    TelemetryManifestUpdateStatus(this, new TelemetryManifestEventArgs(null));
                }
                MACAddressHashCalculationCompleted(this, EventArgs.Empty);
                HardwareIdCalculationCompleted(this, EventArgs.Empty);
            }
            macInformationProvider.MACAddressHashCalculationCompleted -= MACAddressHashCalculationCompleted;
            identityTelemetry.IdentityInformationProvider.HardwareIdCalculationCompleted -= HardwareIdCalculationCompleted;
            ManifestManager.UpdateTelemetryManifestStatusEvent -= TelemetryManifestUpdateStatus;
            ManifestManager.Dispose();
            cancellationTokenSource.Cancel();
            defaultContextPropertyManager.Dispose();
            EventProcessor.PostDiagnosticInformationIfNeeded();
            customEventPostProtection.TryEnterWriteLock(1000);
            List <TelemetryContext> list;

            lock (sessionContextStack)
            {
                list = sessionContextStack.Reverse().ToList();
            }
            foreach (TelemetryContext item in list)
            {
                item.Dispose();
            }
            return(true);
        }
Exemplo n.º 5
0
    public void GetManifest(bool forceRedownloadAsset = false)
    {
        if (null == Instance)
        {
            return;
        }

        if (null == mMainfestMgr)
        {
            mMainfestMgr = new ManifestManager();
        }

        string cachePath = Application.persistentDataPath + "/UnityCache/Shared/";

        if (forceRedownloadAsset && Caching.CleanCache())
        {
            Debug.Log("Successfully cleaned the cache.");
        }

        StartCoroutine(StartDownload());
    }
Exemplo n.º 6
0
        internal void RemoveTask(ABInfo abInfo, BackGroundQueue bQueue, bool isError)
        {
            if (isError)
            {
                abInfo.state = ABInfoState.Fail;
            }
            else
            {
                abInfo.state = ABInfoState.Success;
            }

            var mainAbInfo = ManifestManager.GetABInfo(abInfo.abName);

            if (mainAbInfo != null)
            {
                mainAbInfo.state = abInfo.state;
            }
            this.loadingTasks.Remove(abInfo);
            // Debug.LogFormat("task complete abName={0},size={1},loadingTasks.Count={2},bQueue.count={3}", abInfo.abName, abInfo.size, loadingTasks.Count, bQueue.Count);
            bQueue.Complete(abInfo, isError);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Initializes the <see cref="SecurePassword"/> class.
        /// </summary>
        /// <remarks>This class needed the capacity ID_CAP_IDENTITY_DEVICE</remarks>
        static SecurePassword()
        {
            var    keyString = HostInformation.PublisherHostId;
            string productId = null;

            ManifestManager mgr = new ManifestManager();

            mgr.Load();

            var result = ManifestManager.Current.TryGetValue("ProductID", out productId);

            Debug.Assert(result, "The product ID is missing in the manifest");

            var keyBytes   = Encoding.UTF8.GetBytes(keyString + "#" + productId);
            var baseString = Convert.ToBase64String(keyBytes);

            key = Encoding.UTF8.GetBytes(baseString);

            fileKey  = Convert.ToBase64String(Encoding.UTF8.GetBytes(keyString + typeof(T).ToString()));
            fileName = productId;
        }
Exemplo n.º 8
0
    // Use this for initialization
    IEnumerator Start()
    {
        CUtils.DebugCastTime("LoadingFirst.Start");
        //load manifest
        ResourcesLoader.Initialize();
        CUtils.DebugCastTime("LoadingFirst.Initialize");
        LogSys();
        LoadFirstHelper.LoadFileManifest();
        yield return(new WaitForSeconds(0.16f));

        Hugula.Localization.language = PlayerPrefs.GetString("Language", Application.systemLanguage.ToString());
        yield return(new WaitForLanguageHasBeenSet());

        LoadFirstHelper.SetScene(sceneAssetBundleName, sceneName);
        if (ManifestManager.CheckNeedUncompressStreamingAssets())
        {
            // todo
        }

        LoadFirstHelper.BeginLoadScene();
    }
Exemplo n.º 9
0
        /// <summary>
        /// GetAssetSize
        /// Return the current asset size on disk: audio chunks, video chunks and manifest
        /// </summary>
        public async Task <ulong> GetAssetSize(ManifestManager cache)
        {
            ulong  val  = 0;
            string path = string.Empty;

            path = Path.Combine(Path.Combine(root, cache.StoragePath), manifestFileName);
            if (!string.IsNullOrEmpty(path))
            {
                val += GetFileSize(path);
            }

            using (var releaser = await internalVideoDiskLock.ReaderLockAsync())
            {
                path = Path.Combine(Path.Combine(root, cache.StoragePath), videoIndexFileName);
                if (!string.IsNullOrEmpty(path))
                {
                    val += GetFileSize(path);
                }
                path = Path.Combine(Path.Combine(root, cache.StoragePath), videoContentFileName);
                if (!string.IsNullOrEmpty(path))
                {
                    val += GetFileSize(path);
                }
            }

            using (var releaser = await internalAudioDiskLock.ReaderLockAsync())
            {
                path = Path.Combine(Path.Combine(root, cache.StoragePath), audioIndexFileName);
                if (!string.IsNullOrEmpty(path))
                {
                    val += GetFileSize(path);
                }
                path = Path.Combine(Path.Combine(root, cache.StoragePath), audioContentFileName);
                if (!string.IsNullOrEmpty(path))
                {
                    val += GetFileSize(path);
                }
            }
            return(val);
        }
Exemplo n.º 10
0
        /// <summary>
        /// ProcessChunks
        /// Process the received the audio/video/text chunks
        /// </summary>
        public async Task <bool> ProcessChunks(ManifestManager cache)

        {
            bool bResult = true;

            if (!(await SendAudioChunks(cache)))
            {
                bResult = false;
                LogMessage(Options.LogLevel.Error, "Error while sending audio chunks for url: " + cache.ManifestUri.ToString());
            }
            if (!(await SendVideoChunks(cache)))
            {
                bResult = false;
                LogMessage(Options.LogLevel.Error, "Error while sending video chunks for url: " + cache.ManifestUri.ToString());
            }
            if (!(await SendTextChunks(cache)))
            {
                bResult = false;
                LogMessage(Options.LogLevel.Error, "Error while sending text chunks for url: " + cache.ManifestUri.ToString());
            }
            return(bResult);
        }
Exemplo n.º 11
0
        /// <summary>
        /// ProcessChunks
        /// Process the received the audio/video/text chunks
        /// </summary>
        public async Task <bool> ProcessChunks(ManifestManager cache)

        {
            bool bResult = true;

            if (!(await SendAudioChunks(cache)))
            {
                bResult = false;
                System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Error while sending audio chunks for url: " + cache.ManifestUri.ToString());
            }
            if (!(await SendVideoChunks(cache)))
            {
                bResult = false;
                System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Error while sending video chunks for url: " + cache.ManifestUri.ToString());
            }
            if (!(await SendTextChunks(cache)))
            {
                bResult = false;
                System.Diagnostics.Debug.WriteLine(string.Format("{0:d/M/yyyy HH:mm:ss.fff}", DateTime.Now) + " Error while sending text chunks for url: " + cache.ManifestUri.ToString());
            }
            return(bResult);
        }
Exemplo n.º 12
0
        /// <summary>
        /// load lua bytes
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private byte[] LoadLuaBytes(string name)
        {
            byte[] ret      = null;
            string abName   = name + Common.CHECK_ASSETBUNDLE_SUFFIX;
            bool   isupdate = ManifestManager.CheckIsUpdateFile(abName);
            string path;

            if (isupdate && File.Exists(path = CUtils.PathCombine(CUtils.realPersistentDataPath, abName)))
            {
                ret = File.ReadAllBytes(path);
            }
            else
            {
                var textAsset = (TextAsset)Resources.Load("luac/" + name);
                if (textAsset != null)
                {
                    ret = textAsset.bytes; // --Resources.Load
                    Resources.UnloadAsset(textAsset);
                }
            }
            return(ret);
        }
Exemplo n.º 13
0
        internal void RunningTask(ABInfo abInfo, BackGroundQueue bQueue)
        {
            var download = WebDownload.Get();

            download.userData = new object[] { abInfo, bQueue, };
            download.DownloadFileCompleted   -= OnDownloadFileCompleted;
            download.DownloadProgressChanged -= OnDownloadProgressChanged;
            download.DownloadFileCompleted   += OnDownloadFileCompleted;
            download.DownloadProgressChanged += OnDownloadProgressChanged;
            loadingTasks[abInfo]              = download;

            if (ManifestManager.CheckPersistentCrc(abInfo)) //验证crc
            {
                webClients.Add(download);
                return;
            }
            else
            {
                string urlHost = hosts[0];
                RealLoad(download, abInfo, bQueue, urlHost);
            }
        }
Exemplo n.º 14
0
        internal void RunningTask(ABInfo abInfo, BackGroundQueue bQueue, bool useHost1 = false)
        {
            var download = WebDownload.Get();

            download.userData = new object[] { abInfo, bQueue, useHost1 ? "host1" : "host" };
            download.DownloadFileCompleted   -= OnDownloadFileCompleted;
            download.DownloadProgressChanged -= OnDownloadProgressChanged;
            download.DownloadFileCompleted   += OnDownloadFileCompleted;
            download.DownloadProgressChanged += OnDownloadProgressChanged;
            loadingTasks[abInfo]              = download;

            // download.CancelAsync()
            // Debug.LogFormat("RunningTask abName={0},state={1}", abInfo.abName, abInfo.state);
            if (ManifestManager.CheckPersistentCrc(abInfo)) //验证crc
            {
                webClients.Add(download);
                return;
            }
            else
            {
                string abName = abInfo.abName;
                bool   appCrc = HugulaSetting.instance != null ? HugulaSetting.instance.appendCrcToFile : false;
                if (abInfo.crc32 > 0 && appCrc)
                {
                    abName = CUtils.InsertAssetBundleName(abName, "_" + abInfo.crc32.ToString());
                }

                string h   = useHost1 ? host1 : host;
                Uri    url = new Uri(CUtils.PathCombine(h, abName));

                string path = CUtils.PathCombine(outputPath, abInfo.abName);
                FileHelper.CheckCreateFilePathDirectory(path);
                download.DownloadFileAsync(url, path);
                // #if UNITY_EDITOR
                // Debug.LogFormat(" begin load {0} ,save path ={1},abInfo.state={2} ,webClient({3})", url.AbsoluteUri, path, abInfo.state, download);
                // #endif
            }
        }
Exemplo n.º 15
0
        internal void RunningTask(ABInfo abInfo, BackGroundQueue bQueue)
        {
            var userData = new object[] { abInfo, bQueue, };

            if (ManifestManager.CheckPersistentCrc(abInfo)) //验证crc
            {
                webClients.Add(userData);                   // completa
#if UNITY_EDITOR
                Debug.LogFormat("RunningTask abName={0},Persistent is down ", abInfo.abName);
#endif
                return;
            }
            else
            {
                var download = WebDownload.Get();
                download.userData = userData;
                download.DownloadFileCompleted   = OnDownloadFileCompleted;
                download.DownloadProgressChanged = OnDownloadProgressChanged;
                loadingTasks[abInfo]             = download;
                string urlHost = hosts[0];
                RealLoad(download, abInfo, bQueue, urlHost);
            }
        }
 private static void ExecuteInBackground(object index)
 {
     CommonData.packageName          = packageConfiguration.Packages[(int)index].PackageName.ToLower();
     CommonData.packageVersion       = packageConfiguration.Packages[(int)index].Version;
     CommonData.packageServerAddress = packageConfiguration.Packages[(int)index].ServerAddress;
     CommonData.updatePackageName();
     ManifestManager.GetAllManifests();
     if (DownloadManager.startDownload())
     {
         ForgeInstaller.installForge();
         /* start the selected version */
         MinecraftManager.StartMinecraft();
         ChangeDownloadButtonContent(null);
         ChangeDownloadButtonVisibility(Visibility.Hidden);
     }
     else
     {
         MessageBox.Show("Erreur lors du téléchargement...", "Erreur", MessageBoxButton.OK);
         ChangeDownloadButtonContent(null);
     }
     ChangeDownloadButtonContent(null);
     ChangeDownloadButtonVisibility(Visibility.Hidden);
 }
Exemplo n.º 17
0
        public LaunchPage(string deploymentPath, string outputFileName)
        {
            var fi = new DirectoryInfo(deploymentPath).GetFiles("*.cltw").FirstOrDefault();

            if (fi == null)
            {
                var mgr      = new ManifestManager(string.Empty, deploymentPath, InformationSource.AppManifest);
                var manifest = mgr.CreateAppManifest();
                this.Manifest = manifest;
            }
            else
            {
                Manifest = ManifestManager.ReadFromFile(fi.FullName);
            }
            this.DeploymentDir = new DirectoryInfo(deploymentPath);

            AppLauncher = DeploymentDir.GetFiles("*.application").First();
            if (Manifest.FrameworkVersion == null)
            {
                Manifest.FrameworkVersion = new Version(4, 5);
            }
            this.Model          = new LaunchPageModel(Manifest);
            this.OutputFileName = outputFileName;
        }
Exemplo n.º 18
0
        /// <summary>
        /// SendVideoChunks
        /// Send video chunks
        /// </summary>
        public bool SendVideoChunks(ManifestManager cache)
        {
            bool bResult = false;


            int VideoTrack = 0;

            foreach (var cl in cache.VideoChunkListList)
            {
                if (cl.OutputChunks == 0)
                {
                    if (cl.ftypData != null)
                    {
                        // Ready to talk to the server, moov box has been received
                        SmoothPushManager spm = new SmoothPushManager();
                        if (spm != null)
                        {
                            spm.NetworkClient = new TcpClient();
                            Uri u = new Uri(pushurl);
                            spm.NetworkClient.NoDelay = true;
                            spm.NetworkClient.Connect(u.Host, 80);
                            if (spm.NetworkClient.Connected == true)
                            {
                                string FirstPostData = "POST " + u.LocalPath + " HTTP/1.1\r\nConnection: Keep-Alive\r\nUser-Agent: NSPlayer/7.0 IIS-LiveStream/7.0\r\nContent-Length: 0\r\nHost: " + u.Host + "\r\n\r\n";
                                spm.NetworkStream = spm.NetworkClient.GetStream();
                                if (spm.NetworkStream != null)
                                {
                                    byte[] sb = UTF8Encoding.UTF8.GetBytes(FirstPostData);
                                    if (sb != null)
                                    {
                                        spm.NetworkStream.Write(sb, 0, sb.Length);
                                        if (IsResponseOk(spm.NetworkStream) == true)
                                        {
                                            string url = string.Format("{0}/Streams({1}-stream{2})", pushurl, AssetID, StreamID);
                                            u = new Uri(url);
                                            string NextPostData = "POST " + u.LocalPath + " HTTP/1.1\r\nConnection : Keep-Alive\r\nTransfer-Encoding: Chunked\r\nUser-Agent: NSPlayer/7.0 IIS-LiveStream/7.0\r\nHost: " + u.Host + "\r\n\r\n";
                                            sb = UTF8Encoding.UTF8.GetBytes(NextPostData);
                                            spm.NetworkStream.Write(sb, 0, sb.Length);
                                            spm.NetworkStream.Flush();
                                            System.Threading.Thread.Sleep(1);

                                            // Initialization Done
                                            spm.TrackName = cl.Configuration.TrackName;
                                            spm.Bitrate   = cl.Configuration.Bitrate;
                                            spm.StreamID  = StreamID++;
                                            ListPushManager.Add(SmoothPushManager.GetKeyName(spm.TrackName, spm.Bitrate), spm);

                                            // Sending ftyp
                                            int    BoxLen  = ISMHelper.Mp4Box.ReadMp4BoxInt32(cl.ftypData, 0);
                                            string BoxType = ISMHelper.Mp4Box.ReadMp4BoxType(cl.ftypData, 0);
                                            if (options != null)
                                            {
                                                options.LogVerbose("Source " + cl.Configuration.GetSourceName() + " Streaming MP4 Box " + BoxType + " " + BoxLen.ToString() + " Bytes");
                                            }
                                            if (SendBox(spm.NetworkStream, cl.ftypData) == false)
                                            {
                                                return(false);
                                            }

                                            // Sending Live Manifest
                                            int  uuidHeaderSize            = 4 + 4 + 16 + 4;
                                            uint flags                     = 0;
                                            VideoChunkListConfiguration ac = cl.Configuration as VideoChunkListConfiguration;
                                            if (ac != null)
                                            {
                                                string outerXml = GetVideoManifest(
                                                    ac.TrackID,
                                                    ac.TrackName,
                                                    ac.Bitrate,
                                                    ac.GetSourceName(),
                                                    ac.TimeScale,
                                                    ac.FourCC,
                                                    ac.CodecPrivateData,
                                                    ac.Width,
                                                    ac.Height
                                                    );

                                                byte[] extendedData = UTF8Encoding.UTF8.GetBytes(outerXml);
                                                byte[] buffer       = new byte[(uuidHeaderSize + extendedData.Length)]; // double it
                                                if (ISMHelper.Mp4BoxHelper.WriteExtendedBox(
                                                        buffer, LiveServerManBoxGuid,
                                                        1, flags,
                                                        extendedData,
                                                        0) > 0)
                                                {
                                                    BoxLen  = ISMHelper.Mp4Box.ReadMp4BoxInt32(buffer, 0);
                                                    BoxType = ISMHelper.Mp4Box.ReadMp4BoxType(buffer, 0);
                                                    if (options != null)
                                                    {
                                                        options.LogVerbose("Source " + cl.Configuration.GetSourceName() + " Streaming MP4 Box " + BoxType + " " + BoxLen.ToString() + " Bytes");
                                                    }

                                                    if (SendBox(spm.NetworkStream, buffer) == false)
                                                    {
                                                        return(false);
                                                    }
                                                }
                                            }

                                            // Sending moov
                                            BoxLen  = ISMHelper.Mp4Box.ReadMp4BoxInt32(cl.moovData, 0);
                                            BoxType = ISMHelper.Mp4Box.ReadMp4BoxType(cl.moovData, 0);
                                            if (options != null)
                                            {
                                                options.LogVerbose("Source " + cl.Configuration.GetSourceName() + " Streaming MP4 Box " + BoxType + " " + BoxLen.ToString() + " Bytes");
                                            }
                                            if (SendBox(spm.NetworkStream, cl.moovData) == false)
                                            {
                                                return(false);
                                            }

                                            // Sending the other boxes
                                            if (SendVideoLoop(spm.NetworkStream, cl, cache) == false)
                                            {
                                                return(false);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (ListPushManager.ContainsKey(SmoothPushManager.GetKeyName(cl.Configuration.TrackName, cl.Configuration.Bitrate)))
                    {
                        SmoothPushManager spm = ListPushManager[SmoothPushManager.GetKeyName(cl.Configuration.TrackName, cl.Configuration.Bitrate)];
                        if (spm != null)
                        {
                            if (SendVideoLoop(spm.NetworkStream, cl, cache) == false)
                            {
                                return(false);
                            }
                        }
                    }
                }
                if (cl.InputChunks == cl.OutputChunks)
                {
                    bResult = true;
                }
                VideoTrack++;
            }


            return(bResult);
        }
Exemplo n.º 19
0
        public bool Initialize()
        {
            if (Initialized)
            {
                Debug.LogWarning("Element Dictionary is already initialized!");
            }
            try
            {
                #region Attempt to open the manifest text file.

                var manifestText = ManifestManager.OpenManifest();
                if (manifestText == null)
                {
                    return(false);
                }

                #endregion

                var folders = new List <string>();

                #region populate folders with string entries of all folders in Resources/Elements

                var tmpDictionary = new Dictionary <string, bool>();
                foreach (var text in manifestText)
                {
                    var textSplit = text.Split('\\', '/');
                    if (textSplit.Length == 1)
                    {
                        continue;
                    }
                    if (textSplit[0] != ElementDir)
                    {
                        continue;
                    }
                    if (tmpDictionary.ContainsKey(textSplit[1]))
                    {
                        continue;
                    }
                    folders.Add(textSplit[1]);
                    tmpDictionary.Add(textSplit[1], true);
                }
                tmpDictionary.Clear();

                #endregion

                foreach (var folder in folders)
                {
                    #region Obtain the text asset and find the element name and Id.

                    var attributeList = Resources.Load(ElementDir + "/" + folder + "/" + AttributesFile) as TextAsset;
                    if (!attributeList)
                    {
                        Debug.Log("Could not load the attribute file of " + folder);
                        return(false);
                    }
                    var elementAttributes = new ElementAttributes();
                    var elementId         = int.Parse(folder.Split('_')[0]);
                    var elementName       = folder.Split('_')[1];

                    #endregion

                    ElementNameToId.Add(elementName, elementId);
                    ElementIdToName.Add(elementId, elementName);

                    #region Get parse the element's attributes and store into an attribute object and referenced by a dictionary.

                    var attributeStrings = attributeList.text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
                    foreach (var attributeString in attributeStrings)
                    {
                        var tmp  = attributeString.Trim().Replace(" ", "");
                        var tmp2 = tmp.Split(':');
                        if (tmp2.Length == 1)
                        {
                            continue;
                        }
                        var attribute = tmp2[0];
                        var value     = tmp2[1];
                        switch (attribute)
                        {
                        case "Strength":
                            elementAttributes.Strength.Add(value); break;

                        case "Weakness":
                            elementAttributes.Weakness.Add(value); break;

                        case "Ineffective":
                            elementAttributes.Ineffective.Add(value); break;
                        }
                    }

                    #endregion

                    ElementIdToAttributes.Add(elementId, elementAttributes);
                    ElementNameToAttributes.Add(elementName, elementAttributes);
                    ElementFullNameToAttributes.Add("" + elementId + "_" + elementName, elementAttributes);
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
                Debug.LogError(e.StackTrace);
                _clearDictionaries();
                return(false);
            }
            return(Initialized = true);
        }
Exemplo n.º 20
0
 public Item AddSubItemsTest(Item parentItem, Node parentNode, int courseId, ManifestManager helper,
                             ref Manifest manifest)
 {
     return(AddSubItems(parentItem, parentNode, courseId, helper, ref manifest));
 }
Exemplo n.º 21
0
        public bool Initialize()
        {
            if (Initialized)
            {
                Debug.LogWarning("Mob Dictionary is already initialized!");
            }
            try
            {
                #region Attempt to open the manifest text file.

                var manifestText = ManifestManager.OpenManifest();
                if (manifestText == null)
                {
                    return(false);
                }

                #endregion

                var folders = new List <string>();

                #region populate folders with string entries of all folders in Resources/Mobs

                var tmpDictionary = new Dictionary <string, bool>();
                foreach (var text in manifestText)
                {
                    var textSplit = text.Split('\\', '/');
                    if (textSplit.Length == 1)
                    {
                        continue;
                    }
                    if (textSplit[0] != MobDir)
                    {
                        continue;
                    }
                    if (tmpDictionary.ContainsKey(textSplit[1]))
                    {
                        continue;
                    }
                    folders.Add(textSplit[1]);
                    tmpDictionary.Add(textSplit[1], true);
                }
                tmpDictionary.Clear();

                #endregion

                foreach (var folder in folders)
                {
                    #region Obtain the text asset and find the mob name and Id.

                    var attributeList = Resources.Load(MobDir + "/" + folder + "/" + AttributesFile) as TextAsset;
                    if (!attributeList)
                    {
                        Debug.Log("Could not load the attribute file of " + folder);
                        return(false);
                    }
                    var mobAttributes = new MobAttributes();
                    var mobId         = int.Parse(folder.Split('_')[0]);
                    var mobName       = folder.Split('_')[1];

                    #endregion

                    MobNameToId.Add(mobName, mobId);
                    MobIdToName.Add(mobId, mobName);

                    #region Get parse the mob's attributes and store into an attribute object and referenced by a dictionary.

                    var attributeStrings =
                        attributeList.text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
                    foreach (var attributeString in attributeStrings)
                    {
                        var tmp  = attributeString.Trim().Replace(" ", "");
                        var tmp2 = tmp.Split(':');
                        if (tmp2.Length == 1)
                        {
                            continue;
                        }
                        var attribute = tmp2[0];
                        var value     = tmp2[1];
                        switch (attribute)
                        {
                        case "Health":
                            mobAttributes.Health = float.Parse(value);
                            break;

                        case "Defense":
                            mobAttributes.Defense = float.Parse(value);
                            break;

                        case "SpecialDefense":
                            mobAttributes.SpecialDefense = float.Parse(value);
                            break;

                        case "MoveSpeed":
                            mobAttributes.MoveSpeed = float.Parse(value);
                            break;

                        case "Flying":
                            mobAttributes.Flying = Convert.ToBoolean(int.Parse(value));
                            break;

                        case "HitSphere":
                            mobAttributes.HitSphere = float.Parse(value);
                            break;

                        case "DeathAnimationDelay":
                            mobAttributes.DeathAnimationDelay = int.Parse(value);
                            break;

                        case "DeathFadeDelay":
                            mobAttributes.DeathAnimationDelay = int.Parse(value);
                            break;

                        case "DeathFadeDuration":
                            mobAttributes.DeathAnimationDelay = int.Parse(value);
                            break;

                        case "Type":
                            if (mobAttributes.Types[0] == null)
                            {
                                mobAttributes.Types[0] = value;
                            }
                            else if (mobAttributes.Types[1] == null)
                            {
                                mobAttributes.Types[1] = value;
                            }
                            break;
                        }
                    }

                    #endregion

                    MobIdToAttributes.Add(mobId, mobAttributes);
                    MobNameToAttributes.Add(mobName, mobAttributes);
                    MobFullNameToAttributes.Add("" + mobId + "_" + mobName, mobAttributes);

                    #region Set the mob type-to-name/id dictionary.

                    if (mobAttributes.Types[0] != null)
                    {
                        List <int>    mobIdList;
                        List <string> mobNameList;
                        if (MobTypeToId.TryGetValue(mobAttributes.Types[0], out mobIdList))
                        {
                            mobIdList.Add(mobId);
                        }
                        else
                        {
                            MobTypeToId.Add(mobAttributes.Types[0], new List <int> {
                                mobId
                            });
                        }

                        if (MobTypeToName.TryGetValue(mobAttributes.Types[0], out mobNameList))
                        {
                            mobNameList.Add(mobName);
                        }
                        else
                        {
                            MobTypeToName.Add(mobAttributes.Types[0], new List <string> {
                                mobName
                            });
                        }
                        if (MobTypeToFullName.TryGetValue(mobAttributes.Types[0], out mobNameList))
                        {
                            mobNameList.Add("" + mobId + "_" + mobName);
                        }
                        else
                        {
                            MobTypeToFullName.Add(mobAttributes.Types[0],
                                                  new List <string> {
                                "" + mobId + "_" + mobName
                            });
                        }
                    }
                    if (mobAttributes.Types[1] != null)
                    {
                        List <int>    mobIdList;
                        List <string> mobNameList;
                        if (MobTypeToId.TryGetValue(mobAttributes.Types[1], out mobIdList))
                        {
                            mobIdList.Add(mobId);
                        }
                        else
                        {
                            MobTypeToId.Add(mobAttributes.Types[1], new List <int> {
                                mobId
                            });
                        }

                        if (MobTypeToName.TryGetValue(mobAttributes.Types[1], out mobNameList))
                        {
                            mobNameList.Add(mobName);
                        }
                        else
                        {
                            MobTypeToName.Add(mobAttributes.Types[1], new List <string> {
                                mobName
                            });
                        }
                        if (MobTypeToFullName.TryGetValue(mobAttributes.Types[1], out mobNameList))
                        {
                            mobNameList.Add("" + mobId + "_" + mobName);
                        }
                        else
                        {
                            MobTypeToFullName.Add(mobAttributes.Types[1],
                                                  new List <string> {
                                "" + mobId + "_" + mobName
                            });
                        }
                    }

                    #endregion
                }
            }
            catch (Exception e)
            {
                Debug.LogError(e.Message);
                Debug.LogError(e.StackTrace);
                _clearDictionaries();
                return(false);
            }
            return(Initialized = true);
        }
Exemplo n.º 22
0
 void OnDecomper()
 {
     ManifestManager.CompleteUncompressStreamingAssets();
     LoadFirstHelper.BeginLoadScene(enterLua);
 }
Exemplo n.º 23
0
        static bool PullPush(Options opt)
        {
            bool result = false;

            opt.Status            = Options.TheadStatus.Running;
            opt.ThreadStartTime   = DateTime.Now;
            opt.ThreadCounterTime = DateTime.Now;


            opt.LogInformation("\r\nPullPush " + opt.Name + "\r\n Pulling from : " + opt.InputUri + "\r\n Pushing to : " + opt.OutputUri);

            SmoothLiveOutput d = new SmoothLiveOutput();

            if (d != null)
            {
                bool InitResult = d.Initialize(opt);
                if (InitResult == true)
                {
                    ManifestManager mc = ManifestManager.CreateManifestCache(new Uri(opt.InputUri), (ulong)opt.MinBitrate, (ulong)opt.MaxBitrate, opt.AudioTrackName, opt.TextTrackName, opt.MaxDuration, (ulong)opt.BufferSize, opt.LiveOffset, opt);
                    if (mc != null)
                    {
                        if (mc.SetManifestOutput(d) == true)
                        {
                            var t = mc.DownloadManifest();
                            t.Wait();
                            result = t.Result;
                            if (result == true)
                            {
                                var tt = mc.StartDownloadChunks();
                                tt.Wait();
                                result = tt.Result;
                                DateTime startTime   = DateTime.Now;
                                DateTime currentTime = DateTime.Now;
                                while (mc.GetAssetStatus() != AssetStatus.ChunksDownloaded)
                                {
                                    if (opt.CounterPeriod > 0)
                                    {
                                        System.Threading.Tasks.Task.Delay(opt.CounterPeriod * 1000 / 10).Wait();
                                        if ((opt.ListCounters == null) || (opt.ListCounters.Count == 0))
                                        {
                                            CreatePullPushCounters(opt, mc);
                                        }
                                        else
                                        {
                                            UpdatePullPushCounters(opt, mc);
                                        }
                                    }
                                    else
                                    {
                                        System.Threading.Tasks.Task.Delay(1000).Wait();
                                    }



                                    // Force Garbage Collection in Container
                                    currentTime = DateTime.Now;
                                    if ((currentTime - startTime).TotalSeconds > 300)
                                    {
                                        startTime = currentTime;
                                        if (InDocker)
                                        {
                                            opt.LogInformation("\r\nCalling Garbage Collection " + opt.Name + "\r\n Pulling from : " + opt.InputUri + "\r\n Pushing to : " + opt.OutputUri);
                                            GC.Collect();
                                            GC.WaitForPendingFinalizers();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            opt.LogInformation("PullPush " + opt.Name + " done");
            opt.Status = Options.TheadStatus.Stopped;
            return(result);
        }
Exemplo n.º 24
0
 /// <summary>
 /// ProcessManifest
 /// Initialize the output to receive the audio/video/text chunks based on the manifest content
 /// </summary>
 public Task <bool> ProcessManifest(ManifestManager manifest)
 {
     return(Task.FromResult(false));
 }
Exemplo n.º 25
0
        // private void RegisterFunc()
        // {
        //  Lua.mainState.loaderDelegate = Loader;
        // }

        /// <summary>
        ///  loader
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        private byte[] Loader(string name)
        {
            byte[] str = null;
#if UNITY_EDITOR
            string name1 = name.Replace('.', '/');
            string path  = Application.dataPath + "/Lua/" + name1 + ".lua";
            if (!File.Exists(path))
            {
                path = Application.dataPath + "/Config/" + name1 + ".lua";
            }

            if (File.Exists(path))
            {
                str = File.ReadAllBytes(path);
            }
            else
            {
                Debug.LogWarningFormat("lua({0}) path={1} not exists.", name, path);
                name = name.Replace('.', '+').Replace('/', '+');
                str  = LoadLuaBytes(name);
            }
#else
            name = name.Replace('.', '+').Replace('/', '+');
            string cryName = "";
            if (System.IntPtr.Size == 4)
            {
                cryName = CUtils.GetRightFileName(name);
            }
            else
            {
                cryName = CUtils.GetRightFileName(string.Format("{0}_64", name));
            }

            string abName   = cryName + Common.CHECK_ASSETBUNDLE_SUFFIX;
            bool   isupdate = ManifestManager.CheckIsUpdateFile(abName);

            #if !HUGULA_NO_LOG
            Debug.LogFormat("loader lua {0}={1}", name, cryName);
            #endif

            string path = null;
            if (isupdate && File.Exists(path = CUtils.PathCombine(CUtils.realPersistentDataPath, abName)))
            {
                str = File.ReadAllBytes(path);
            }
            else
            {
                var textAsset = (TextAsset)Resources.Load("luac/" + cryName);
                if (textAsset == null)
                {
                    Debug.LogWarningFormat("lua({0}={1}) bytes error!", name, cryName);
                }
                else
                {
                    str = textAsset.bytes; // --Resources.Load
                }
                Resources.UnloadAsset(textAsset);
            }
#endif
            return(str);
        }
Exemplo n.º 26
0
 ///<summary>
 /// 从配置获取加载cdn的url地址
 ///</summary>
 public void LoadBeginScene()
 {
     ManifestManager.LoadUpdateFileManifest(null);
     SetSliderProgress(Localization.Get("main_enter_game"), 5, 1);
     ResourcesLoader.LoadScene(SCENE_ASSETBUNDLE_NAME, SCENE_NAME, null, null, null, true, UnityEngine.SceneManagement.LoadSceneMode.Single);
 }
Exemplo n.º 27
0
        /// <summary>
        /// SaveVideoChunks
        /// Save video chunks on disk
        /// </summary>
        public async Task <bool> SaveVideoChunks(ManifestManager cache)
        {
            bool   bResult          = false;
            string VideoIndexFile   = Path.Combine(Path.Combine(root, cache.StoragePath), videoIndexFileName);
            string VideoContentFile = Path.Combine(Path.Combine(root, cache.StoragePath), videoContentFileName);

            if ((!string.IsNullOrEmpty(VideoIndexFile)) &&
                (!string.IsNullOrEmpty(VideoContentFile)))
            {
                if (!DirectoryExists(Path.Combine(root, cache.StoragePath)))
                {
                    CreateDirectory(Path.Combine(root, cache.StoragePath));
                }

                using (var releaser = await internalVideoDiskLock.WriterLockAsync())
                {
                    // delete the initial files

                    /*
                     * await DeleteFile(VideoIndexFile);
                     * await DeleteFile(VideoContentFile);
                     * cache.VideoSavedChunks = 0;
                     */
                    int VideoTrack = 0;
                    foreach (var cl in cache.VideoChunkListList)
                    {
                        string FilePath           = VideoContentFile + "_" + VideoTrack.ToString() + ".ismv";
                        ulong  InitialVideoOffset = 0;
                        ulong  VideoOffset        = GetFileSize(FilePath);

                        if (VideoOffset == 0)
                        {
                            if (cl.ftypData != null)
                            {
                                Append(FilePath, cl.ftypData);
                                Append(FilePath, cl.moovData);
                                VideoOffset = GetFileSize(FilePath);
                            }
                        }
                        else
                        {
                            InitialVideoOffset = VideoOffset;
                            ChunkBuffer cc;
                            while (cl.ChunksQueue.TryDequeue(out cc) == true)
                            //    foreach (var cc in cl.ChunksQueue)
                            //for (int Index = (int)cl.OutputChunks; Index < (int)cl.InputChunks; Index++)
                            {
                                //  var cc = cl.ChunksList.Values.ElementAt(Index);
                                if ((cc != null) && (cc.GetLength() > 0))
                                {
                                    IndexCache ic = new IndexCache(cc.Time, VideoOffset, cc.GetLength());
                                    if (ic != null)
                                    {
                                        ulong res = Append(FilePath, cc.chunkBuffer);
                                        if (res == cc.GetLength())
                                        {
                                            VideoOffset += res;
                                            ulong result = Append(VideoIndexFile + "_" + VideoTrack.ToString(), ic.GetByteData());
                                            if (result == indexSize)
                                            {
                                                // free buffer
                                                cc.chunkBuffer  = null;
                                                cl.OutputBytes += res;
                                                cl.OutputChunks++;
                                            }
                                            else
                                            {
                                                bResult = false;
                                                System.Diagnostics.Debug.WriteLine("Error while archiving video");
                                            }
                                        }
                                        else
                                        {
                                            System.Diagnostics.Debug.WriteLine("Error while archiving video");
                                        }
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                        VideoTrack++;
                        if (InitialVideoOffset < VideoOffset)
                        {
                            bResult = true;
                        }
                        if (cache.GetOutputVideoSize() == cache.GetInputVideoSize())
                        {
                            bResult = true;
                        }
                    }
                }
            }

            return(bResult);
        }
Exemplo n.º 28
0
 /// <summary>
 /// SaveManifest
 /// Save manifest on disk
 /// </summary>
 public async Task <bool> ProcessManifest(ManifestManager cache)
 {
     return(await SaveManifest(cache));
 }
Exemplo n.º 29
0
        public string Export(int id)
        {
            var course = GetCourse(id);

            var path = GetCoursePath(id);

            if (course.Locked != null && course.Locked.Value)
            {
                return(path + ".zip");
            }

            path = Path.Combine(path, Guid.NewGuid().ToString());
            path = Path.Combine(path, course.Name);

            Directory.CreateDirectory(path);


            var nodes = GetNodes(id).ToList();

            for (var i = 0; i < nodes.Count; i++)
            {
                if (nodes[i].IsFolder == false)
                {
                    File.Copy(GetNodePath(nodes[i].Id) + ".html", Path.Combine(path, nodes[i].Id + ".html"));
                }
                else
                {
                    var subNodes = GetNodes(id, nodes[i].Id);
                    nodes.AddRange(subNodes);
                }
            }

            var coursePath = GetCoursePath(id);

            FileHelper.DirectoryCopy(Path.Combine(coursePath, "Node"), Path.Combine(path, "Node"));

            foreach (var file in _TemplateFiles)
            {
                File.Copy(Path.Combine(coursePath, file), Path.Combine(path, file));
            }

            var helper = new ManifestManager();

            var manifest   = new Manifest();
            var sw         = new StreamWriter(Path.Combine(path, SCORM.ImsManifset));
            var parentItem = new Item();

            parentItem                      = AddSubItems(parentItem, null, id, helper, ref manifest);
            manifest.Organizations          = ManifestManager.AddOrganization(manifest.Organizations, helper.CreateOrganization());
            manifest.Organizations.Default  = manifest.Organizations[0].Identifier;
            manifest.Organizations[0].Items = parentItem.Items;
            manifest.Organizations[0].Title = course.Name;

            if (course.Sequencing != null)
            {
                var xml = new XmlSerializer(typeof(Sequencing));
                manifest.Organizations[0].Sequencing = (Sequencing)xml.DeserializeXElement(course.Sequencing);
            }
            var resource = new Resource
            {
                Identifier = _ResourceIdForTemplateFiles,
                Files      = _TemplateFiles.Select(file => new ManifestModels.ResourceModels.File(file)).ToList(),
                ScormType  = ScormType.Asset
            };

            manifest.Resources = ManifestManager.AddResource(manifest.Resources, resource);

            ManifestManager.Serialize(manifest, sw);
            sw.Close();

            Zipper.CreateZip(path + ".zip", path);

            return(path + ".zip");
        }
Exemplo n.º 30
0
 void Awake()
 {
     Instance = this;
 }