示例#1
0
 /// <summary>
 /// <para>Destroys a saved search for the authenticating user.</para>
 /// <para>The authenticating user must be the owner of saved search id being destroyed.</para>
 /// <para>Available parameters:</para>
 /// <para>- <c>long</c> id (required)</para>
 /// </summary>
 /// <param name="parameters">The Parameters.</param>
 /// <returns>The saved search.</returns>
 public SearchQueryResponse Destroy <T>(T parameters)
 {
     return(this.Tokens.AccessParameterReservedApi <SearchQueryResponse>(MethodType.Get, "saved_searches/destroy/{0}", "id", InternalUtils.ResolveObject(parameters)));
 }
示例#2
0
 /// <summary>
 /// <para>Uploads videos or chunked images to Twitter for use in a Tweet or Twitter-hosted Card as an asynchronous operation.</para>
 /// <para>Available parameters:</para>
 /// <para>- <c>string</c> media_category (optional)</para>
 /// <para>- <c>IEnumerbale&lt;long&gt;</c> additional_owners (optional)</para>
 /// </summary>
 /// <param name="media">The raw binary file content being uploaded.</param>
 /// <param name="totalBytes">The size of the media being uploaded in bytes.</param>
 /// <param name="mediaType">The type of the media being uploaded.</param>
 /// <param name="parameters">The parameters.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>
 /// <para>The task object representing the asynchronous operation.</para>
 /// <para>The Result property on the task object returns the result for the uploaded media.</para>
 /// </returns>
 public Task <MediaUploadResult> UploadChunkedWithRetryAsync(Stream media, long totalBytes, UploadMediaType mediaType, int retryCount, int retryDelayInMilliseconds, object parameters, CancellationToken cancellationToken = default(CancellationToken), IProgress <UploadChunkedProgressInfo> progress = null)
 {
     return(this.UploadChunkedAsyncImpl(media, totalBytes, mediaType, InternalUtils.ResolveObject(parameters), retryCount, retryDelayInMilliseconds, cancellationToken, progress));
 }
 protected override Tuple<string, string> GetCredentials() {
     return InternalUtils.GetGoogleDriveAppFolderCredentials();
 }
    public override void Package(ProjectParams Params, DeploymentContext SC, int WorkingCL)
    {
        Log("Package {0}", Params.RawProjectPath);

        // ensure the ue4game binary exists, if applicable
        string FullExePath = CombinePaths(Path.GetDirectoryName(Params.ProjectGameExeFilename), SC.StageExecutables[0] + (UnrealBuildTool.BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac ? ".stub" : ""));

        if (!SC.IsCodeBasedProject && !FileExists_NoExceptions(FullExePath))
        {
            Log("Failed to find game binary " + FullExePath);
            throw new AutomationException(ErrorCodes.Error_MissingExecutable, "Stage Failed. Could not find binary {0}. You may need to build the UE4 project with your target configuration and platform.", FullExePath);
        }

        //@TODO: We should be able to use this code on both platforms, when the following issues are sorted:
        //   - Raw executable is unsigned & unstripped (need to investigate adding stripping to IPP)
        //   - IPP needs to be able to codesign a raw directory
        //   - IPP needs to be able to take a .app directory instead of a Payload directory when doing RepackageFromStage (which would probably be renamed)
        //   - Some discrepancy in the loading screen pngs that are getting packaged, which needs to be investigated
        //   - Code here probably needs to be updated to write 0 byte files as 1 byte (difference with IPP, was required at one point when using Ionic.Zip to prevent issues on device, maybe not needed anymore?)
        if (UnrealBuildTool.BuildHostPlatform.Current.Platform == UnrealTargetPlatform.Mac)
        {
            // copy in all of the artwork and plist
            var DeployHandler = UEBuildDeploy.GetBuildDeploy(UnrealTargetPlatform.IOS);

            DeployHandler.PrepForUATPackageOrDeploy(Params.ShortProjectName,
                                                    Path.GetDirectoryName(Params.RawProjectPath),
                                                    CombinePaths(Path.GetDirectoryName(Params.ProjectGameExeFilename), SC.StageExecutables[0]),
                                                    CombinePaths(SC.LocalRoot, "Engine"),
                                                    Params.Distribution,
                                                    "",
                                                    false);

            // figure out where to pop in the staged files
            string AppDirectory = string.Format("{0}/Payload/{1}.app",
                                                Path.GetDirectoryName(Params.ProjectGameExeFilename),
                                                Path.GetFileNameWithoutExtension(Params.ProjectGameExeFilename));

            // delete the old cookeddata
            InternalUtils.SafeDeleteDirectory(AppDirectory + "/cookeddata", true);
            InternalUtils.SafeDeleteFile(AppDirectory + "/ue4commandline.txt", true);

            if (!Params.IterativeDeploy)
            {
                // copy the Staged files to the AppDirectory
                string[] StagedFiles = Directory.GetFiles(SC.StageDirectory, "*", SearchOption.AllDirectories);
                foreach (string Filename in StagedFiles)
                {
                    string DestFilename = Filename.Replace(SC.StageDirectory, AppDirectory);
                    Directory.CreateDirectory(Path.GetDirectoryName(DestFilename));
                    InternalUtils.SafeCopyFile(Filename, DestFilename, true);
                }
            }
            else
            {
                // copy just the root stage directory files
                string[] StagedFiles = Directory.GetFiles(SC.StageDirectory, "*", SearchOption.TopDirectoryOnly);
                foreach (string Filename in StagedFiles)
                {
                    string DestFilename = Filename.Replace(SC.StageDirectory, AppDirectory);
                    Directory.CreateDirectory(Path.GetDirectoryName(DestFilename));
                    InternalUtils.SafeCopyFile(Filename, DestFilename, true);
                }
            }
        }

        if (SC.StageTargetConfigurations.Count != 1)
        {
            throw new AutomationException("iOS is currently only able to package one target configuration at a time, but StageTargetConfigurations contained {0} configurations", SC.StageTargetConfigurations.Count);
        }
        bCreatedIPA = false;
        bool bNeedsIPA = false;

        if (Params.IterativeDeploy)
        {
            String NonUFSManifestPath = SC.GetNonUFSDeploymentDeltaPath();
            // check to determine if we need to update the IPA
            if (File.Exists(NonUFSManifestPath))
            {
                string   NonUFSFiles = File.ReadAllText(NonUFSManifestPath);
                string[] Lines       = NonUFSFiles.Split('\n');
                bNeedsIPA = Lines.Length > 0 && !string.IsNullOrWhiteSpace(Lines[0]);
            }
        }

        if (String.IsNullOrEmpty(Params.Provision))
        {
            UnrealBuildTool.IOSPlatform BuildPlat = UEBuildPlatform.GetBuildPlatform(UnrealTargetPlatform.IOS) as UnrealBuildTool.IOSPlatform;
            BuildPlat.SetUpProjectEnvironment(UnrealTargetPlatform.IOS);
            Params.Provision = UnrealBuildTool.IOSPlatform.MobileProvision;
        }
        if (String.IsNullOrEmpty(Params.Certificate))
        {
            UnrealBuildTool.IOSPlatform BuildPlat = UEBuildPlatform.GetBuildPlatform(UnrealTargetPlatform.IOS) as UnrealBuildTool.IOSPlatform;
            BuildPlat.SetUpProjectEnvironment(UnrealTargetPlatform.IOS);
            Params.Certificate = UnrealBuildTool.IOSPlatform.SigningCertificate;
        }

        var TargetConfiguration = SC.StageTargetConfigurations[0];

        // Scheme name and configuration for code signing with Xcode project
        string SchemeName          = Params.IsCodeBasedProject ? Path.GetFileNameWithoutExtension(Params.RawProjectPath) : "UE4";
        string SchemeConfiguration = TargetConfiguration.ToString();

        if (Params.Client)
        {
            SchemeConfiguration += " Client";
        }

        if (UnrealBuildTool.BuildHostPlatform.Current.Platform != UnrealTargetPlatform.Mac)
        {
            var ProjectIPA  = MakeIPAFileName(TargetConfiguration, Params);
            var ProjectStub = Path.GetFullPath(Params.ProjectGameExeFilename);

            // package a .ipa from the now staged directory
            var IPPExe = CombinePaths(CmdEnv.LocalRoot, "Engine/Binaries/DotNET/IOS/IPhonePackager.exe");

            Log("ProjectName={0}", Params.ShortProjectName);
            Log("ProjectStub={0}", ProjectStub);
            Log("ProjectIPA={0}", ProjectIPA);
            Log("IPPExe={0}", IPPExe);

            bool cookonthefly = Params.CookOnTheFly || Params.SkipCookOnTheFly;

            // if we are incremental check to see if we need to even update the IPA
            if (!Params.IterativeDeploy || !File.Exists(ProjectIPA) || bNeedsIPA)
            {
                // delete the .ipa to make sure it was made
                DeleteFile(ProjectIPA);

                bCreatedIPA = true;

                if (RemoteToolChain.bUseRPCUtil)
                {
                    string IPPArguments = "RepackageFromStage \"" + (Params.IsCodeBasedProject ? Params.RawProjectPath : "Engine") + "\"";
                    IPPArguments += " -config " + TargetConfiguration.ToString();
                    IPPArguments += " -schemename " + SchemeName + " -schemeconfig \"" + SchemeConfiguration + "\"";

                    if (TargetConfiguration == UnrealTargetConfiguration.Shipping)
                    {
                        IPPArguments += " -compress=best";
                    }

                    // Determine if we should sign
                    bool bNeedToSign = GetCodeSignDesirability(Params);

                    if (!String.IsNullOrEmpty(Params.BundleName))
                    {
                        // Have to sign when a bundle name is specified
                        bNeedToSign   = true;
                        IPPArguments += " -bundlename " + Params.BundleName;
                    }

                    if (bNeedToSign)
                    {
                        IPPArguments += " -sign";
                        if (Params.Distribution)
                        {
                            IPPArguments += " -distribution";
                        }
                    }

                    IPPArguments += (cookonthefly ? " -cookonthefly" : "");
                    IPPArguments += " -stagedir \"" + CombinePaths(Params.BaseStageDirectory, "IOS") + "\"";
                    IPPArguments += " -project \"" + Params.RawProjectPath + "\"";
                    if (Params.IterativeDeploy)
                    {
                        IPPArguments += " -iterate";
                    }
                    if (!string.IsNullOrEmpty(Params.Provision))
                    {
                        IPPArguments += " -provision \"" + Params.Provision + "\"";
                    }
                    if (!string.IsNullOrEmpty(Params.Certificate))
                    {
                        IPPArguments += " -certificate \"" + Params.Certificate + "\"";
                    }

                    RunAndLog(CmdEnv, IPPExe, IPPArguments);
                }
                else
                {
                    List <string> IPPArguments = new List <string>();
                    IPPArguments.Add("RepackageFromStage");
                    IPPArguments.Add(Params.IsCodeBasedProject ? Params.RawProjectPath : "Engine");
                    IPPArguments.Add("-config");
                    IPPArguments.Add(TargetConfiguration.ToString());
                    IPPArguments.Add("-schemename");
                    IPPArguments.Add(SchemeName);
                    IPPArguments.Add("-schemeconfig");
                    IPPArguments.Add("\"" + SchemeConfiguration + "\"");

                    if (TargetConfiguration == UnrealTargetConfiguration.Shipping)
                    {
                        IPPArguments.Add("-compress=best");
                    }

                    // Determine if we should sign
                    bool bNeedToSign = GetCodeSignDesirability(Params);

                    if (!String.IsNullOrEmpty(Params.BundleName))
                    {
                        // Have to sign when a bundle name is specified
                        bNeedToSign = true;
                        IPPArguments.Add("-bundlename");
                        IPPArguments.Add(Params.BundleName);
                    }

                    if (bNeedToSign)
                    {
                        IPPArguments.Add("-sign");
                    }

                    if (cookonthefly)
                    {
                        IPPArguments.Add(" -cookonthefly");
                    }
                    IPPArguments.Add(" -stagedir");
                    IPPArguments.Add(CombinePaths(Params.BaseStageDirectory, "IOS"));
                    IPPArguments.Add(" -project");
                    IPPArguments.Add(Params.RawProjectPath);
                    if (Params.IterativeDeploy)
                    {
                        IPPArguments.Add(" -iterate");
                    }
                    if (!string.IsNullOrEmpty(Params.Provision))
                    {
                        IPPArguments.Add(" -provision");
                        IPPArguments.Add(Params.Provision);
                    }
                    if (!string.IsNullOrEmpty(Params.Certificate))
                    {
                        IPPArguments.Add(" -certificate");
                        IPPArguments.Add(Params.Certificate);
                    }

                    if (RunIPP(IPPArguments.ToArray()) != 0)
                    {
                        throw new AutomationException("IPP Failed");
                    }
                }
            }

            // verify the .ipa exists
            if (!FileExists(ProjectIPA))
            {
                throw new AutomationException(ErrorCodes.Error_FailedToCreateIPA, "PACKAGE FAILED - {0} was not created", ProjectIPA);
            }

            if (WorkingCL > 0)
            {
                // Open files for add or edit
                var ExtraFilesToCheckin = new List <string>
                {
                    ProjectIPA
                };

                // check in the .ipa along with everything else
                UE4Build.AddBuildProductsToChangelist(WorkingCL, ExtraFilesToCheckin);
            }

            //@TODO: This automatically deploys after packaging, useful for testing on PC when iterating on IPP
            //Deploy(Params, SC);
        }
        else
        {
            // create the ipa
            string IPAName = CombinePaths(Path.GetDirectoryName(Params.RawProjectPath), "Binaries", "IOS", (Params.Distribution ? "Distro_" : "") + Params.ShortProjectName + (SC.StageTargetConfigurations[0] != UnrealTargetConfiguration.Development ? ("-IOS-" + SC.StageTargetConfigurations[0].ToString()) : "") + ".ipa");

            if (!Params.IterativeDeploy || !File.Exists(IPAName) || bNeedsIPA)
            {
                bCreatedIPA = true;

                // code sign the app
                CodeSign(Path.GetDirectoryName(Params.ProjectGameExeFilename), Params.IsCodeBasedProject ? Params.ShortProjectName : Path.GetFileNameWithoutExtension(Params.ProjectGameExeFilename), Params.RawProjectPath, SC.StageTargetConfigurations[0], SC.LocalRoot, Params.ShortProjectName, Path.GetDirectoryName(Params.RawProjectPath), SC.IsCodeBasedProject, Params.Distribution, Params.Provision, Params.Certificate, SchemeName, SchemeConfiguration);

                // now generate the ipa
                PackageIPA(Path.GetDirectoryName(Params.ProjectGameExeFilename), Params.IsCodeBasedProject ? Params.ShortProjectName : Path.GetFileNameWithoutExtension(Params.ProjectGameExeFilename), Params.ShortProjectName, Path.GetDirectoryName(Params.RawProjectPath), SC.StageTargetConfigurations[0], Params.Distribution);
            }
        }

        PrintRunTime();
    }
示例#5
0
 /// <summary>
 /// <para>Uploads videos or chunked images to Twitter for use in a Tweet or Twitter-hosted Card as an asynchronous operation.</para>
 /// <para>Available parameters:</para>
 /// <para>- <c>string</c> media_category (optional)</para>
 /// <para>- <c>IEnumerbale&lt;long&gt;</c> additional_owners (optional)</para>
 /// </summary>
 /// <param name="media">The raw binary file content being uploaded.</param>
 /// <param name="totalBytes">The size of the media being uploaded in bytes.</param>
 /// <param name="mediaType">The type of the media being uploaded.</param>
 /// <param name="parameters">The parameters.</param>
 /// <returns>
 /// <para>The task object representing the asynchronous operation.</para>
 /// <para>The Result property on the task object returns the result for the uploaded media.</para>
 /// </returns>
 public Task <MediaUploadResult> UploadChunkedAsync(Stream media, long totalBytes, UploadMediaType mediaType, params Expression <Func <string, object> >[] parameters)
 {
     return(this.UploadChunkedAsyncImpl(media, totalBytes, mediaType, InternalUtils.ExpressionsToDictionary(parameters), 0, 0, CancellationToken.None));
 }
示例#6
0
 /// <summary>
 /// <para>Returns all the information about a known place as an asynchronous operation.</para>
 /// <para>Available parameters: </para>
 /// <para>- <c>string</c> place_id (required)</para>
 /// </summary>
 /// <param name="parameters">The parameters.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>
 /// <para>The task object representing the asynchronous operation.</para>
 /// <para>The Result property on the task object returns the geo.</para>
 /// </returns>
 public Task <PlaceResponse> IdAsync <T>(T parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     return(this.Tokens.AccessParameterReservedApiAsync <PlaceResponse>(MethodType.Get, "geo/id/{place_id}", "place_id", InternalUtils.ResolveObject(parameters), cancellationToken));
 }
示例#7
0
        public static void CreateAndRun(bool forceSoftwareRenderingMode)
        {
            FilesStorage.Initialize(EntryPoint.ApplicationDataDirectory);

            if (!AppArguments.GetBool(AppFlag.DisableLogging))
            {
                var logFilename = EntryPoint.GetLogName("Main Log");
                Logging.Initialize(FilesStorage.Instance.GetFilename("Logs", logFilename), AppArguments.GetBool(AppFlag.OptimizeLogging));
                Logging.Write($"App version: {BuildInformation.AppVersion} ({BuildInformation.Platform}, {WindowsVersionHelper.GetVersion()})");
            }

            if (AppArguments.GetBool(AppFlag.DisableSaving))
            {
                ValuesStorage.Initialize();
                CacheStorage.Initialize();
                AuthenticationStorage.Initialize();
            }
            else
            {
                ValuesStorage.Initialize(FilesStorage.Instance.GetFilename("Values.data"),
                                         InternalUtils.GetValuesStorageEncryptionKey(),
                                         AppArguments.GetBool(AppFlag.DisableValuesCompression));
                CacheStorage.Initialize(FilesStorage.Instance.GetFilename("Cache.data"), AppArguments.GetBool(AppFlag.DisableValuesCompression));
                AuthenticationStorage.Initialize(FilesStorage.Instance.GetFilename("Authentication.data"),
                                                 AppArguments.GetBool(AppFlag.DisableValuesCompression));
                if (MathUtils.Random(0, 10) == 0)
                {
                    LazierCached.Purge();
                }

                FatalErrorHandler.FatalError += OnFatalError;
            }

            if (AppArguments.GetBool(AppFlag.NoProxy, true))
            {
                WebRequest.DefaultWebProxy = null;
            }

            NonfatalError.Initialize();
            LocaleHelper.InitializeAsync().Wait();

            var softwareRenderingModeWasEnabled = IsSoftwareRenderingModeEnabled();

            if (forceSoftwareRenderingMode)
            {
                ValuesStorage.Set(AppAppearanceManager.KeySoftwareRendering, true);
            }

            if (IsSoftwareRenderingModeEnabled())
            {
                SwitchToSoftwareRendering();
            }

            var app = new App();

            // Some sort of safe mode
            if (forceSoftwareRenderingMode && !softwareRenderingModeWasEnabled)
            {
                Toast.Show("Safe mode", "Failed to start the last time, now CM uses software rendering", () => {
                    if (ModernDialog.ShowMessage(
                            "Would you like to switch back to hardware rendering? You can always do that in Settings/Appearance. App will be restarted.",
                            "Switch back", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        ValuesStorage.Set(AppAppearanceManager.KeySoftwareRendering, false);
                        Storage.SaveBeforeExit(); // Just in case
                        WindowsHelper.RestartCurrentApplication();
                    }
                });
            }

            app.Run();
        }
示例#8
0
 private IEnumerable <StreamingMessage> AccessStreamingApi(StreamingType type, object parameters)
 {
     return(this.AccessStreamingApiImpl(type, InternalUtils.ResolveObject(parameters)));
 }
示例#9
0
 /// <summary>
 /// <para>Initializes a new instance of the <see cref="CoreTweet.Streaming.StreamingParameters"/> class with a specified option.</para>
 /// <para>Available parameters: </para>
 /// <para>*Note: In filter stream, at least one predicate parameter (follow, locations, or track) must be specified.</para>
 /// <para><c>bool</c> stall_warnings (optional)" : Specifies whether stall warnings should be delivered.</para>
 /// <para><c>string / IEnumerable&lt;long&gt;</c> follow (optional*, required in site stream, ignored in user stream)</para>
 /// <para><c>string / IEnumerable&lt;string&gt;</c> track (optional*)</para>
 /// <para><c>string / IEnumerable&lt;string&gt;</c> location (optional*)</para>
 /// <para><c>string</c> with (optional)</para>
 /// </summary>
 /// <param name="streamingParameters">The streaming parameters.</param>
 public StreamingParameters(params Expression <Func <string, object> >[] streamingParameters)
     : this(InternalUtils.ExpressionsToDictionary(streamingParameters))
 {
 }
示例#10
0
 private static void SetSteamIdInner_Impl(string value)
 {
     InternalUtils.SetSteamId(value);
 }
示例#11
0
 private IEnumerable <StreamingMessage> AccessStreamingApi(StreamingType type, Expression <Func <string, object> >[] parameters)
 {
     return(this.AccessStreamingApiImpl(type, InternalUtils.ExpressionsToDictionary(parameters)));
 }
示例#12
0
 /// <summary>
 /// <para>Returns all the information about a known place.</para>
 /// <para>Available parameters: </para>
 /// <para>- <c>string</c> place_id (required)</para>
 /// </summary>
 /// <param name="parameters">The parameters.</param>
 /// <returns>The geo.</returns>
 public PlaceResponse Id <T>(T parameters)
 {
     return(this.Tokens.AccessParameterReservedApi <PlaceResponse>(MethodType.Get, "geo/id/{place_id}", "place_id", InternalUtils.ResolveObject(parameters)));
 }
示例#13
0
        //FIXME: The format of "attribute:street_address" isn't known. Needed to check the format by "OAuth tool".

#if !(PCL || WIN_RT || WP)
        //GET Methods

        /// <summary>
        /// <para>Returns all the information about a known place.</para>
        /// <para>Available parameters: </para>
        /// <para>- <c>string</c> place_id (required)</para>
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <returns>The geo.</returns>
        public PlaceResponse Id(params Expression <Func <string, object> >[] parameters)
        {
            return(this.Tokens.AccessParameterReservedApi <PlaceResponse>(MethodType.Get, "geo/id/{place_id}", "place_id", InternalUtils.ExpressionsToDictionary(parameters)));
        }
示例#14
0
 /// <summary>
 /// <para>Retrieve the information for the saved search represented by the given id.</para>
 /// <para>The authenticating user must be the owner of saved search ID being requested.</para>
 /// <para>Available parameters:</para>
 /// <para>- <c>long</c> id (required)</para>
 /// </summary>
 /// <param name="parameters">The Parameters.</param>
 /// <returns>The saved search.</returns>
 public SearchQueryResponse Show(params Expression <Func <string, object> >[] parameters)
 {
     return(this.Tokens.AccessParameterReservedApi <SearchQueryResponse>(MethodType.Get, "saved_searches/show/{id}", "id", InternalUtils.ExpressionsToDictionary(parameters)));
 }
示例#15
0
 /// <summary>
 /// <para>Provides additional information about the uploaded media_id.</para>
 /// <para>Available parameters:</para>
 /// <para>- <c>long</c> media_id</para>
 /// <para>- JSON-Object alt_text</para>
 /// </summary>
 /// <param name="parameters">The parameters.</param>
 public void Create(params Expression <Func <string, object> >[] parameters)
 {
     this.Create(InternalUtils.ExpressionsToDictionary(parameters));
 }
示例#16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CoreTweet.Streaming.StreamingParameters"/> class with a specified option.
 /// </summary>
 /// <param name="streamingParameters">The streaming parameters.</param>
 public static StreamingParameters Create <T>(T streamingParameters)
 {
     return(new StreamingParameters(InternalUtils.ResolveObject(streamingParameters)));
 }
示例#17
0
        //GET Methods

        /// <summary>
        /// <para>Returns all the information about a known place as an asynchronous operation.</para>
        /// <para>Available parameters: </para>
        /// <para>- <c>string</c> place_id (required)</para>
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <returns>
        /// <para>The task object representing the asynchronous operation.</para>
        /// <para>The Result property on the task object returns the geo.</para>
        /// </returns>
        public Task <PlaceResponse> IdAsync(params Expression <Func <string, object> >[] parameters)
        {
            return(this.Tokens.AccessParameterReservedApiAsync <PlaceResponse>(MethodType.Get, "geo/id/{place_id}", "place_id", InternalUtils.ExpressionsToDictionary(parameters), CancellationToken.None));
        }
示例#18
0
        /// <summary>
        /// <para>Returns settings (including current trend, geo and sleep time information) for the authenticating user or updates the authenticating user's settings.</para>
        /// <para>Available parameters: </para>
        /// <para>- <c>int</c> trend_location_woeid (optional)</para>
        /// <para>- <c>bool</c> sleep_time_enabled (optional)</para>
        /// <para>- <c>int</c> start_sleep_time (optional)</para>
        /// <para>- <c>int</c> end_sleep_time (optional)</para>
        /// <para>- <c>string</c> time_zone (optional)</para>
        /// <para>- <c>string</c> lang (optional)</para>
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <returns>The settings of the user.</returns>
        public Setting Settings <T>(T parameters)
        {
            var param = InternalUtils.ResolveObject(parameters).ToArray();

            return(this.Tokens.AccessApiImpl <Setting>(param.Any() ? MethodType.Post : MethodType.Get, "account/settings", param, ""));
        }
示例#19
0
        private App()
        {
            if (AppArguments.GetBool(AppFlag.IgnoreHttps))
            {
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
            }

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            AppArguments.Set(AppFlag.SyncNavigation, ref ModernFrame.OptionUseSyncNavigation);
            AppArguments.Set(AppFlag.DisableTransitionAnimation, ref ModernFrame.OptionDisableTransitionAnimation);
            AppArguments.Set(AppFlag.RecentlyClosedQueueSize, ref LinkGroupFilterable.OptionRecentlyClosedQueueSize);

            AppArguments.Set(AppFlag.NoProxy, ref KunosApiProvider.OptionNoProxy);

            var proxy = AppArguments.Get(AppFlag.Proxy);

            if (!string.IsNullOrWhiteSpace(proxy))
            {
                try {
                    var s = proxy.Split(':');
                    WebRequest.DefaultWebProxy = new WebProxy(s[0], FlexibleParser.ParseInt(s.ArrayElementAtOrDefault(1), 1080));
                } catch (Exception e) {
                    Logging.Error(e);
                }
            }

            // TODO: AppArguments.Set(AppFlag.ScanPingTimeout, ref RecentManagerOld.OptionScanPingTimeout);
            AppArguments.Set(AppFlag.LanSocketTimeout, ref KunosApiProvider.OptionLanSocketTimeout);
            AppArguments.Set(AppFlag.LanPollTimeout, ref KunosApiProvider.OptionLanPollTimeout);
            AppArguments.Set(AppFlag.WebRequestTimeout, ref KunosApiProvider.OptionWebRequestTimeout);
            AppArguments.Set(AppFlag.DirectRequestTimeout, ref KunosApiProvider.OptionDirectRequestTimeout);
            AppArguments.Set(AppFlag.CommandTimeout, ref GameCommandExecutorBase.OptionCommandTimeout);
            AppArguments.Set(AppFlag.WeatherExtMode, ref WeatherProceduralHelper.Option24HourMode);

            AppArguments.Set(AppFlag.DisableAcRootChecking, ref AcPaths.OptionEaseAcRootCheck);
            AppArguments.Set(AppFlag.AcObjectsLoadingConcurrency, ref BaseAcManagerNew.OptionAcObjectsLoadingConcurrency);
            AppArguments.Set(AppFlag.SkinsLoadingConcurrency, ref CarObject.OptionSkinsLoadingConcurrency);
            AppArguments.Set(AppFlag.KunosCareerIgnoreSkippedEvents, ref KunosCareerEventsManager.OptionIgnoreSkippedEvents);
            AppArguments.Set(AppFlag.IgnoreMissingSkinsInKunosEvents, ref KunosEventObjectBase.OptionIgnoreMissingSkins);

            AppArguments.Set(AppFlag.CanPack, ref AcCommonObject.OptionCanBePackedFilter);
            AppArguments.Set(AppFlag.CanPackCars, ref CarObject.OptionCanBePackedFilter);

            AppArguments.Set(AppFlag.ForceToastFallbackMode, ref Toast.OptionFallbackMode);

            AppArguments.Set(AppFlag.SmartPresetsChangedHandling, ref UserPresetsControl.OptionSmartChangedHandling);
            AppArguments.Set(AppFlag.EnableRaceIniRestoration, ref Game.OptionEnableRaceIniRestoration);
            AppArguments.Set(AppFlag.EnableRaceIniTestMode, ref Game.OptionRaceIniTestMode);
            AppArguments.Set(AppFlag.RaceOutDebug, ref Game.OptionDebugMode);

            AppArguments.Set(AppFlag.NfsPorscheTribute, ref RaceGridViewModel.OptionNfsPorscheNames);
            AppArguments.Set(AppFlag.KeepIniComments, ref IniFile.OptionKeepComments);
            AppArguments.Set(AppFlag.AutoConnectPeriod, ref OnlineServer.OptionAutoConnectPeriod);
            AppArguments.Set(AppFlag.GenericModsLogging, ref GenericModsEnabler.OptionLoggingEnabled);
            AppArguments.Set(AppFlag.SidekickOptimalRangeThreshold, ref SidekickHelper.OptionRangeThreshold);
            AppArguments.Set(AppFlag.GoogleDriveLoaderDebugMode, ref GoogleDriveLoader.OptionDebugMode);
            AppArguments.Set(AppFlag.GoogleDriveLoaderManualRedirect, ref GoogleDriveLoader.OptionManualRedirect);
            AppArguments.Set(AppFlag.DebugPing, ref ServerEntry.OptionDebugPing);
            AppArguments.Set(AppFlag.DebugContentId, ref AcObjectNew.OptionDebugLoading);
            AppArguments.Set(AppFlag.JpegQuality, ref ImageUtilsOptions.JpegQuality);
            AppArguments.Set(AppFlag.FbxMultiMaterial, ref Kn5.OptionJoinToMultiMaterial);

            Acd.Factory       = new AcdFactory();
            Lazier.SyncAction = ActionExtension.InvokeInMainThreadAsync;
            KeyboardListenerFactory.Register <KeyboardListener>();

            LimitedSpace.Initialize();
            DataProvider.Initialize();
            SteamIdHelper.Initialize(AppArguments.Get(AppFlag.ForceSteamId));
            TestKey();

            AppDomain.CurrentDomain.ProcessExit += OnProcessExit;

            if (!AppArguments.GetBool(AppFlag.PreventDisableWebBrowserEmulationMode) && (
                    ValuesStorage.Get <int>(WebBrowserEmulationModeDisabledKey) < WebBrowserHelper.EmulationModeDisablingVersion ||
                    AppArguments.GetBool(AppFlag.ForceDisableWebBrowserEmulationMode)))
            {
                try {
                    WebBrowserHelper.DisableBrowserEmulationMode();
                    ValuesStorage.Set(WebBrowserEmulationModeDisabledKey, WebBrowserHelper.EmulationModeDisablingVersion);
                } catch (Exception e) {
                    Logging.Warning("Can’t disable emulation mode: " + e);
                }
            }

            JsonConvert.DefaultSettings = () => new JsonSerializerSettings {
                Formatting           = Formatting.None,
                NullValueHandling    = NullValueHandling.Ignore,
                DefaultValueHandling = DefaultValueHandling.Include,
                Culture = CultureInfo.InvariantCulture
            };

            AcToolsLogging.Logger = (s, m, p, l) => Logging.Write($"{s} (AcTools)", m, p, l);
            AcToolsLogging.NonFatalErrorHandler = (s, c, e, b) => {
                if (b)
                {
                    NonfatalError.NotifyBackground(s, c, e);
                }
                else
                {
                    NonfatalError.Notify(s, c, e);
                }
            };

            AppArguments.Set(AppFlag.ControlsDebugMode, ref ControlsSettings.OptionDebugControlles);
            AppArguments.Set(AppFlag.ControlsRescanPeriod, ref DirectInputScanner.OptionMinRescanPeriod);
            var ignoreControls = AppArguments.Get(AppFlag.IgnoreControls);

            if (!string.IsNullOrWhiteSpace(ignoreControls))
            {
                ControlsSettings.OptionIgnoreControlsFilter = Filter.Create(new StringTester(), ignoreControls);
            }

            var sseStart = AppArguments.Get(AppFlag.SseName);

            if (!string.IsNullOrWhiteSpace(sseStart))
            {
                SseStarter.OptionStartName = sseStart;
            }
            AppArguments.Set(AppFlag.SseLogging, ref SseStarter.OptionLogging);

            FancyBackgroundManager.Initialize();
            if (AppArguments.Has(AppFlag.UiScale))
            {
                AppearanceManager.Instance.AppScale = AppArguments.GetDouble(AppFlag.UiScale, 1d);
            }
            if (AppArguments.Has(AppFlag.WindowsLocationManagement))
            {
                AppearanceManager.Instance.ManageWindowsLocation = AppArguments.GetBool(AppFlag.WindowsLocationManagement, true);
            }

            if (!InternalUtils.IsAllRight)
            {
                AppAppearanceManager.OptionCustomThemes = false;
            }
            else
            {
                AppArguments.Set(AppFlag.CustomThemes, ref AppAppearanceManager.OptionCustomThemes);
            }

            AppArguments.Set(AppFlag.FancyHintsDebugMode, ref FancyHint.OptionDebugMode);
            AppArguments.Set(AppFlag.FancyHintsMinimumDelay, ref FancyHint.OptionMinimumDelay);
            AppArguments.Set(AppFlag.WindowsVerbose, ref DpiAwareWindow.OptionVerboseMode);
            AppArguments.Set(AppFlag.ShowroomUiVerbose, ref LiteShowroomFormWrapperWithTools.OptionAttachedToolsVerboseMode);
            AppArguments.Set(AppFlag.BenchmarkReplays, ref GameDialog.OptionBenchmarkReplays);
            AppArguments.Set(AppFlag.HideRaceCancelButton, ref GameDialog.OptionHideCancelButton);

            // Shared memory, now as an app flag
            SettingsHolder.Drive.WatchForSharedMemory = !AppArguments.GetBool(AppFlag.DisableSharedMemory);

            /*AppAppearanceManager.OptionIdealFormattingModeDefaultValue = AppArguments.GetBool(AppFlag.IdealFormattingMode,
             *      !Equals(DpiAwareWindow.OptionScale, 1d));*/
            NonfatalErrorSolution.IconsDictionary = new Uri("/AcManager.Controls;component/Assets/IconData.xaml", UriKind.Relative);
            AppearanceManager.DefaultValuesSource = new Uri("/AcManager.Controls;component/Assets/ModernUI.Default.xaml", UriKind.Relative);
            AppAppearanceManager.Initialize(Pages.Windows.MainWindow.GetTitleLinksEntries());
            VisualExtension.RegisterInput <WebBlock>();

            ContentUtils.Register("AppStrings", AppStrings.ResourceManager);
            ContentUtils.Register("ControlsStrings", ControlsStrings.ResourceManager);
            ContentUtils.Register("ToolsStrings", ToolsStrings.ResourceManager);
            ContentUtils.Register("UiStrings", UiStrings.ResourceManager);

            AcObjectsUriManager.Register(new UriProvider());

            {
                var uiFactory = new GameWrapperUiFactory();
                GameWrapper.RegisterFactory(uiFactory);
                ServerEntry.RegisterFactory(uiFactory);
            }

            GameWrapper.RegisterFactory(new DefaultAssistsFactory());
            LapTimesManager.Instance.SetListener();
            RaceResultsStorage.Instance.SetListener();

            AcError.RegisterFixer(new AcErrorFixer());
            AcError.RegisterSolutionsFactory(new SolutionsFactory());

            InitializePresets();

            SharingHelper.Initialize();
            SharingUiHelper.Initialize(AppArguments.GetBool(AppFlag.ModernSharing) ? new Win10SharingUiHelper() : null);

            {
                var addonsDir  = FilesStorage.Instance.GetFilename("Addons");
                var pluginsDir = FilesStorage.Instance.GetFilename("Plugins");
                if (Directory.Exists(addonsDir) && !Directory.Exists(pluginsDir))
                {
                    Directory.Move(addonsDir, pluginsDir);
                }
                else
                {
                    pluginsDir = FilesStorage.Instance.GetDirectory("Plugins");
                }

                PluginsManager.Initialize(pluginsDir);
                PluginsWrappers.Initialize(
                    new AssemblyResolvingWrapper(KnownPlugins.Fmod, FmodResolverService.Resolver),
                    new AssemblyResolvingWrapper(KnownPlugins.Fann, FannResolverService.Resolver),
                    new AssemblyResolvingWrapper(KnownPlugins.Magick, ImageUtils.MagickResolver),
                    new AssemblyResolvingWrapper(KnownPlugins.CefSharp, CefSharpResolverService.Resolver));
            }

            {
                var onlineMainListFile   = FilesStorage.Instance.GetFilename("Online Servers", "Main List.txt");
                var onlineFavouritesFile = FilesStorage.Instance.GetFilename("Online Servers", "Favourites.txt");
                if (File.Exists(onlineMainListFile) && !File.Exists(onlineFavouritesFile))
                {
                    Directory.Move(onlineMainListFile, onlineFavouritesFile);
                }
            }

            Storage.TemporaryBackupsDirectory = FilesStorage.Instance.GetTemporaryDirectory("Storages Backups");
            CupClient.Initialize();
            Superintendent.Initialize();
            ModsWebBrowser.Initialize();

            AppArguments.Set(AppFlag.OfflineMode, ref AppKeyDialog.OptionOfflineMode);

            WebBlock.DefaultDownloadListener  = new WebDownloadListener();
            FlexibleLoader.CmRequestHandler   = new CmRequestHandler();
            ContextMenus.ContextMenusProvider = new ContextMenusProvider();
            PrepareUi();

            AppShortcut.Initialize("Content Manager", "Content Manager");

            // If shortcut exists, make sure it has a proper app ID set for notifications
            if (File.Exists(AppShortcut.ShortcutLocation))
            {
                AppShortcut.CreateShortcut();
            }

            AppIconService.Initialize(new AppIconProvider());

            Toast.SetDefaultAction(() => (Current.Windows.OfType <ModernWindow>().FirstOrDefault(x => x.IsActive) ??
                                          Current.MainWindow as ModernWindow)?.BringToFront());
            BbCodeBlock.ImageClicked             += OnBbImageClick;
            BbCodeBlock.OptionEmojiProvider       = new EmojiProvider();
            BbCodeBlock.OptionImageCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Images");
            BbCodeBlock.OptionEmojiCacheDirectory = FilesStorage.Instance.GetTemporaryFilename("Emoji");

            BbCodeBlock.AddLinkCommand(new Uri("cmd://findMissing/car"),
                                       new DelegateCommand <string>(
                                           id => {
                WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Car));
            }));

            BbCodeBlock.AddLinkCommand(new Uri("cmd://findMissing/track"),
                                       new DelegateCommand <string>(
                                           id => {
                WindowsHelper.ViewInBrowser(SettingsHolder.Content.MissingContentSearch.GetUri(id, SettingsHolder.MissingContentType.Track));
            }));

            BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/car"), new DelegateCommand <string>(id => {
                var s = id.Split('|');
                IndexDirectDownloader.DownloadCarAsync(s[0], s.ArrayElementAtOrDefault(1)).Forget();
            }));

            BbCodeBlock.AddLinkCommand(new Uri("cmd://downloadMissing/track"), new DelegateCommand <string>(id => {
                var s = id.Split('|');
                IndexDirectDownloader.DownloadTrackAsync(s[0], s.ArrayElementAtOrDefault(1)).Forget();
            }));

            BbCodeBlock.AddLinkCommand(new Uri("cmd://createNeutralLut"),
                                       new DelegateCommand <string>(id => NeutralColorGradingLut.CreateNeutralLut(id.As(16))));

            BbCodeBlock.DefaultLinkNavigator.PreviewNavigate += (sender, args) => {
                if (args.Uri.IsAbsoluteUri && args.Uri.Scheme == "acmanager")
                {
                    ArgumentsHandler.ProcessArguments(new[] { args.Uri.ToString() }, true).Forget();
                    args.Cancel = true;
                }
            };

            AppArguments.SetSize(AppFlag.ImagesCacheLimit, ref BetterImage.OptionCacheTotalSize);
            AppArguments.Set(AppFlag.ImagesMarkCached, ref BetterImage.OptionMarkCached);
            BetterImage.RemoteUserAgent      = CmApiProvider.UserAgent;
            BetterImage.RemoteCacheDirectory = BbCodeBlock.OptionImageCacheDirectory;
            GameWrapper.Started += (sender, args) => {
                BetterImage.CleanUpCache();
                GCHelper.CleanUp();
            };

            AppArguments.Set(AppFlag.UseVlcForAnimatedBackground, ref DynamicBackground.OptionUseVlc);
            Filter.OptionSimpleMatching = true;

            GameResultExtension.RegisterNameProvider(new GameSessionNameProvider());
            CarBlock.CustomShowroomWrapper   = new CustomShowroomWrapper();
            CarBlock.CarSetupsView           = new CarSetupsView();
            SettingsHolder.Content.OldLayout = AppArguments.GetBool(AppFlag.CarsOldLayout);

            var acRootIsFine = Superintendent.Instance.IsReady && !AcRootDirectorySelector.IsReviewNeeded();

            if (acRootIsFine && SteamStarter.Initialize(AcRootDirectory.Instance.Value))
            {
                if (SettingsHolder.Drive.SelectedStarterType != SettingsHolder.DriveSettings.SteamStarterType)
                {
                    SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.SteamStarterType;
                    Toast.Show("Starter changed to replacement", "Enjoy Steam being included into CM");
                }
            }
            else if (SettingsHolder.Drive.SelectedStarterType == SettingsHolder.DriveSettings.SteamStarterType)
            {
                SettingsHolder.Drive.SelectedStarterType = SettingsHolder.DriveSettings.DefaultStarterType;
                Toast.Show($"Starter changed to {SettingsHolder.Drive.SelectedStarterType.DisplayName}", "Steam Starter is unavailable", () => {
                    ModernDialog.ShowMessage(
                        "To use Steam Starter, please make sure CM is taken place of the official launcher and AC root directory is valid.",
                        "Steam Starter is unavailable", MessageBoxButton.OK);
                });
            }

            InitializeUpdatableStuff();
            BackgroundInitialization();
            ExtraProgressRings.Initialize();

            FatalErrorMessage.Register(new AppRestartHelper());
            ImageUtils.SafeMagickWrapper = fn => {
                try {
                    return(fn());
                } catch (OutOfMemoryException e) {
                    NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, ToolsStrings.MagickNet_CannotLoad_Commentary, e);
                } catch (Exception e) {
                    NonfatalError.Notify(ToolsStrings.MagickNet_CannotLoad, e);
                }
                return(null);
            };

            DataFileBase.ErrorsCatcher = new DataSyntaxErrorCatcher();
            AppArguments.Set(AppFlag.SharedMemoryLiveReadingInterval, ref AcSharedMemory.OptionLiveReadingInterval);
            AcSharedMemory.Initialize();

            AppArguments.Set(AppFlag.RunRaceInformationWebserver, ref PlayerStatsManager.OptionRunStatsWebserver);
            AppArguments.Set(AppFlag.RaceInformationWebserverFile, ref PlayerStatsManager.OptionWebserverFilename);

            PlayerStatsManager.Instance.SetListener();
            RhmService.Instance.SetListener();

            WheelOptionsBase.SetStorage(new WheelAnglesStorage());

            _hibernator = new AppHibernator();
            _hibernator.SetListener();

            VisualCppTool.Initialize(FilesStorage.Instance.GetDirectory("Plugins", "NativeLibs"));

            try {
                SetRenderersOptions();
            } catch (Exception e) {
                VisualCppTool.OnException(e, null);
            }

            CommonFixes.Initialize();

            CmPreviewsTools.MissingShowroomHelper = new CarUpdatePreviewsDialog.MissingShowroomHelper();

            // Paint shop+livery generator?
            LiteShowroomTools.LiveryGenerator = new LiveryGenerator();

            // Discord
            if (AppArguments.Has(AppFlag.DiscordCmd))
            {
                // Do not show main window and wait for futher instructions?
            }

            if (SettingsHolder.Integrated.DiscordIntegration)
            {
                AppArguments.Set(AppFlag.DiscordVerbose, ref DiscordConnector.OptionVerboseMode);
                DiscordConnector.Initialize(AppArguments.Get(AppFlag.DiscordClientId) ?? InternalUtils.GetDiscordClientId(), new DiscordHandler());
                DiscordImage.OptionDefaultImage = @"track_ks_brands_hatch";
                GameWrapper.Started            += (sender, args) => args.StartProperties.SetAdditional(new GameDiscordPresence(args.StartProperties, args.Mode));
            }

            // Reshade?
            var loadReShade = AppArguments.GetBool(AppFlag.ForceReshade);

            if (!loadReShade && string.Equals(AppArguments.Get(AppFlag.ForceReshade), "kn5only", StringComparison.OrdinalIgnoreCase))
            {
                loadReShade = AppArguments.Values.Any(x => x.EndsWith(".kn5", StringComparison.OrdinalIgnoreCase));
            }

            if (loadReShade)
            {
                var reshade = Path.Combine(MainExecutingFile.Directory, "dxgi.dll");
                if (File.Exists(reshade))
                {
                    Kernel32.LoadLibrary(reshade);
                }
            }

            // Auto-show that thing
            InstallAdditionalContentDialog.Initialize();

            // Let’s roll
            ShutdownMode = ShutdownMode.OnExplicitShutdown;
            new AppUi(this).Run();
        }
示例#20
0
        internal static IEnumerable <T> Enumerate <TV>(TokensBase tokens, string apiName, EnumerateMode mode, TV parameters)
        {
            var p = InternalUtils.ResolveObject(parameters);

            return(Enumerate(tokens, apiName, mode, p));
        }
示例#21
0
        static StreamingMessage ExtractRoot(JObject jo)
        {
            JToken jt;

            if (jo.TryGetValue("disconnect", out jt))
            {
                return(jt.ToObject <DisconnectMessage>());
            }
            else if (jo.TryGetValue("warning", out jt))
            {
                return(jt.ToObject <WarningMessage>());
            }
            else if (jo.TryGetValue("control", out jt))
            {
                return(jt.ToObject <ControlMessage>());
            }
            else if (jo.TryGetValue("delete", out jt))
            {
                JToken        status;
                DeleteMessage id;
                if (((JObject)jt).TryGetValue("status", out status))
                {
                    id             = status.ToObject <DeleteMessage>();
                    id.messageType = MessageType.DeleteStatus;
                }
                else
                {
                    id             = jt["direct_message"].ToObject <DeleteMessage>();
                    id.messageType = MessageType.DeleteDirectMessage;
                }
                var timestamp = jt["timestamp_ms"];
                if (timestamp != null)
                {
                    id.Timestamp = InternalUtils.GetUnixTimeMs(long.Parse((string)timestamp));
                }
                return(id);
            }
            else if (jo.TryGetValue("scrub_geo", out jt))
            {
                return(jt.ToObject <ScrubGeoMessage>());
            }
            else if (jo.TryGetValue("limit", out jt))
            {
                return(jt.ToObject <LimitMessage>());
            }
            else if (jo.TryGetValue("status_withheld", out jt))
            {
                return(jt.ToObject <StatusWithheldMessage>());
            }
            else if (jo.TryGetValue("user_withheld", out jt))
            {
                return(jt.ToObject <UserWithheldMessage>());
            }
            else if (jo.TryGetValue("user_delete", out jt))
            {
                var m = jt.ToObject <UserMessage>();
                m.messageType = MessageType.UserDelete;
                return(m);
            }
            else if (jo.TryGetValue("user_undelete", out jt))
            {
                var m = jt.ToObject <UserMessage>();
                m.messageType = MessageType.UserUndelete;
                return(m);
            }
            else if (jo.TryGetValue("user_suspend", out jt))
            {
                // user_suspend doesn't have 'timestamp_ms' field
                var m = jt.ToObject <UserMessage>();
                m.messageType = MessageType.UserSuspend;
                return(m);
            }
            else
            {
                throw new ParsingException("on streaming, cannot parse the json: unsupported type", jo.ToString(Formatting.Indented), null);
            }
        }
示例#22
0
        internal static IEnumerable <T> Enumerate(TokensBase tokens, string apiName, EnumerateMode mode, params Expression <Func <string, object> >[] parameters)
        {
            var p = InternalUtils.ExpressionsToDictionary(parameters);

            return(Enumerate(tokens, apiName, mode, p));
        }
示例#23
0
        //POST methods

        internal Task <AsyncResponse> AccessUploadApiAsync(IEnumerable <KeyValuePair <string, object> > parameters, CancellationToken cancellationToken, IProgress <UploadProgressInfo> progress)
        {
            var options = Tokens.ConnectionOptions ?? ConnectionOptions.Default;

            return(this.Tokens.SendRequestAsyncImpl(MethodType.Post, InternalUtils.GetUrl(options, options.UploadUrl, true, "media/upload.json"), parameters, cancellationToken, progress));
        }
示例#24
0
 /**
  * <inheritdoc/>
  */
 public Tag <List <ITag> > CreateFromData(byte[] value)
 {
     this.value = InternalUtils.GetListData <ITag>(value);
     return(this);
 }
示例#25
0
 /// <summary>
 /// <para>Uploads videos or chunked images to Twitter for use in a Tweet or Twitter-hosted Card as an asynchronous operation.</para>
 /// <para>Available parameters:</para>
 /// <para>- <c>string</c> media_category (optional)</para>
 /// <para>- <c>IEnumerbale&lt;long&gt;</c> additional_owners (optional)</para>
 /// </summary>
 /// <param name="media">The raw binary file content being uploaded.</param>
 /// <param name="totalBytes">The size of the media being uploaded in bytes.</param>
 /// <param name="mediaType">The type of the media being uploaded.</param>
 /// <param name="parameters">The parameters.</param>
 /// <returns>
 /// <para>The task object representing the asynchronous operation.</para>
 /// <para>The Result property on the task object returns the result for the uploaded media.</para>
 /// </returns>
 public Task <MediaUploadResult> UploadChunkedWithRetryAsync(Stream media, long totalBytes, UploadMediaType mediaType, int retryCount, int retryDelayInMilliseconds, params Expression <Func <string, object> >[] parameters)
 {
     return(this.UploadChunkedAsyncImpl(media, totalBytes, mediaType, InternalUtils.ExpressionsToDictionary(parameters), retryCount, retryDelayInMilliseconds, CancellationToken.None));
 }
示例#26
0
 public async Task LoadAsync(CancellationToken cancellationToken)
 {
     _changelog = await Task.Run(() => InternalUtils.LoadChangelog(CmApiProvider.UserAgent, false));
 }
示例#27
0
 /// <summary>
 /// <para>Upload media (images) to Twitter for use in a Tweet or Twitter-hosted Card.</para>
 /// <para>Available parameters:</para>
 /// <para>- <c>Stream</c> media (any one is required)</para>
 /// <para>- <c>IEnumerable&lt;byte&gt;</c> media (any one is required)</para>
 /// <para>- <c>FileInfo</c> media (any one is required)</para>
 /// <para>- <c>string</c> media_data (any one is required)</para>
 /// <para>- <c>IEnumerable&lt;long&gt;</c> additional_owners (optional)</para>
 /// </summary>
 /// <param name="parameters">The parameters.</param>
 /// <param name="cancellationToken">The cancellation token.</param>
 /// <returns>The result for the uploaded media.</returns>
 public Task <MediaUploadResult> UploadAsync(object parameters, CancellationToken cancellationToken = default(CancellationToken), IProgress <UploadProgressInfo> progress = null)
 {
     return(this.UploadAsyncImpl(InternalUtils.ResolveObject(parameters), cancellationToken, progress));
 }
示例#28
0
 public void Load()
 {
     _changelog = InternalUtils.LoadChangelog(CmApiProvider.UserAgent, false);
 }
示例#29
0
        public static void SendLogs(string message = null)
        {
            var logsDirectory = FilesStorage.Instance.GetDirectory("Logs");

            using (var memory = new MemoryStream()) {
                using (var writer = WriterFactory.Open(memory, ArchiveType.Zip, CompressionType.Deflate)) {
                    if (!string.IsNullOrWhiteSpace(message))
                    {
                        try {
                            writer.WriteString("Message.txt", message);
                        } catch (Exception e) {
                            Logging.Warning("Can’t attach Message.txt: " + e);
                        }
                    }

                    try {
                        writer.Write("AC Log.txt", FileUtils.GetLogFilename());
                    } catch (Exception e) {
                        Logging.Warning("Can’t attach AC Log.txt: " + e);
                    }

                    string wpfVersion;
                    try {
                        using (var r = Registry.LocalMachine.OpenSubKey(
                                   @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0\Setup\Windows Presentation Foundation")) {
                            wpfVersion = r?.GetValue("Version")?.ToString();
                        }
                    } catch (Exception e) {
                        Logging.Warning("Can’t get WPF version: " + e);
                        wpfVersion = null;
                    }

                    try {
                        writer.WriteString("Description.txt", JsonConvert.SerializeObject(new {
                            BuildInformation.AppVersion,
                            BuildInformation.Platform,
                            MainExecutingFile.Location,
                            Environment.OSVersion,
                            Environment.CommandLine,
                            Environment = Environment.GetEnvironmentVariables(),
                            SteamId     = SteamIdHelper.Instance.Value,
                            typeof(string).Assembly.ImageRuntimeVersion,
                            WpfVersion = wpfVersion
                        }, Formatting.Indented));
                    } catch (Exception e) {
                        Logging.Warning("Can’t attach Description.txt: " + e);
                    }

                    try {
                        writer.WriteString("Values.txt", ValuesStorage.Storage.GetData());
                    } catch (Exception e) {
                        Logging.Warning("Can’t attach Values.data: " + e);
                    }

                    try {
                        if (File.Exists(FilesStorage.Instance.GetFilename("Arguments.txt")))
                        {
                            writer.Write("Arguments.txt", FilesStorage.Instance.GetFilename("Arguments.txt"));
                        }
                    } catch (Exception e) {
                        Logging.Warning("Can’t attach Arguments.txt: " + e);
                    }

                    foreach (var fileInfo in new DirectoryInfo(FileUtils.GetDocumentsCfgDirectory()).GetFiles("*.ini").Where(x => x.Length < 500000).Take(100))
                    {
                        try {
                            writer.Write("Config/" + fileInfo.Name, fileInfo.FullName);
                        } catch (Exception e) {
                            Logging.Warning("Can’t attach Config/" + fileInfo.Name + ": " + e);
                        }
                    }

                    if (AcRootDirectory.Instance.Value != null)
                    {
                        foreach (var fileInfo in new DirectoryInfo(FileUtils.GetSystemCfgDirectory(AcRootDirectory.Instance.RequireValue)).GetFiles("*.ini")
                                 .Where(x => x.Length < 500000)
                                 .Take(100))
                        {
                            try {
                                writer.Write("SysConfig/" + fileInfo.Name, fileInfo.FullName);
                            } catch (Exception e) {
                                Logging.Warning("Can’t attach SysConfig/" + fileInfo.Name + ": " + e);
                            }
                        }
                    }

                    var raceOut = FileUtils.GetResultJsonFilename();
                    if (File.Exists(raceOut))
                    {
                        try {
                            writer.Write("Race.json", raceOut);
                        } catch (Exception e) {
                            Logging.Warning("Can’t attach Race.json:" + e);
                        }
                    }

                    var career = FileUtils.GetKunosCareerProgressFilename();;
                    if (File.Exists(career))
                    {
                        try {
                            writer.Write("Career.ini", career);
                        } catch (Exception e) {
                            Logging.Warning("Can’t attach Career.ini:" + e);
                        }
                    }

                    foreach (var filename in Directory.GetFiles(logsDirectory, "Main*.log").TakeLast(35)
                             .Union(Directory.GetFiles(logsDirectory, "Packed*.log").TakeLast(35)))
                    {
                        var name = Path.GetFileName(filename);
                        try {
                            writer.Write("Logs/" + name, filename);
                        } catch (Exception e) {
                            Logging.Warning("Can’t attach Logs/" + name + ": " + e);
                        }
                    }
                }

                var data = memory.ToArray();
                if (data.Length > 20000000)
                {
                    File.WriteAllBytes(FilesStorage.Instance.GetTemporaryFilename("Report.zip"), data);
                    throw new Exception("Size limit exceeded");
                }

                InternalUtils.SendAppReport(memory.ToArray(), $@"Name: {GetUserName()}
Operating system: {GetWindowsName()}
App version: {BuildInformation.AppVersion}", CmApiProvider.UserAgent);
            }
        }
示例#30
0
        public static void CreateAndRun(bool forceSoftwareRenderingMode)
        {
            FilesStorage.Initialize(EntryPoint.ApplicationDataDirectory);

            if (!AppArguments.GetBool(AppFlag.DisableLogging))
            {
                var logFilename = EntryPoint.GetLogName("Main Log");
                Logging.Initialize(FilesStorage.Instance.GetFilename("Logs", logFilename), AppArguments.GetBool(AppFlag.OptimizeLogging));
                Logging.Write($"App version: {BuildInformation.AppVersion} ({BuildInformation.Platform}, {WindowsVersionHelper.GetVersion()})");
            }

            if (AppArguments.GetBool(AppFlag.DisableSaving))
            {
                ValuesStorage.Initialize();
                CacheStorage.Initialize();
                AuthenticationStorage.Initialize();
            }
            else
            {
                ValuesStorage.Initialize(FilesStorage.Instance.GetFilename("Values.data"),
                                         InternalUtils.GetValuesStorageEncryptionKey(),
                                         AppArguments.GetBool(AppFlag.DisableValuesCompression));
                CacheStorage.Initialize(FilesStorage.Instance.GetFilename("Cache.data"), AppArguments.GetBool(AppFlag.DisableValuesCompression));
                AuthenticationStorage.Initialize(FilesStorage.Instance.GetFilename("Authentication.data"),
                                                 AppArguments.GetBool(AppFlag.DisableValuesCompression));
                if (MathUtils.Random(0, 10) == 0)
                {
                    LazierCached.Purge();
                }

                FatalErrorHandler.FatalError += OnFatalError;
            }

            if (AppArguments.GetBool(AppFlag.NoProxy, true))
            {
                WebRequest.DefaultWebProxy = null;
            }

            NonfatalError.Initialize();
            LocaleHelper.InitializeAsync().Wait();

            var softwareRenderingModeWasEnabled = IsSoftwareRenderingModeEnabled();

            if (forceSoftwareRenderingMode)
            {
                ValuesStorage.Set(AppAppearanceManager.KeySoftwareRendering, true);
            }

            if (IsSoftwareRenderingModeEnabled())
            {
                SwitchToSoftwareRendering();
            }

            var app = new App();

            // Some sort of safe mode
            if (forceSoftwareRenderingMode && !softwareRenderingModeWasEnabled)
            {
                Toast.Show("Safe mode", "Failed to start the last time, now CM uses software rendering", () => {
                    if (MessageDialog.Show(
                            "Would you like to switch back to hardware rendering? You can always do that in Settings/Appearance. App will be restarted.",
                            "Switch back", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        ValuesStorage.Set(AppAppearanceManager.KeySoftwareRendering, false);
                        Storage.SaveBeforeExit(); // Just in case
                        WindowsHelper.RestartCurrentApplication();
                    }
                });
            }

            var move = AppArguments.Get(AppFlag.MoveApp);

            if (move != null && File.Exists(move))
            {
                for (var i = 0; i < 10; i++)
                {
                    if (FileUtils.TryToDelete(move) || !File.Exists(move))
                    {
                        break;
                    }
                    Thread.Sleep(100);
                }
                Toast.Show("App moved", $"App moved from AC root folder, now Oculus Rift should work better", () => {
                    var originalRemoved = File.Exists(move) ? "failed to remove original file" : "original file removed";
                    if (MessageDialog.Show(
                            $"New location is “{MainExecutingFile.Location}”, {originalRemoved}. Please don’t forget to recreate any shortcuts you might have created.",
                            "Content Manager is moved",
                            new MessageDialogButton {
                        [MessageBoxResult.Yes] = "View new location",
                        [MessageBoxResult.No] = UiStrings.Ok
                    }) == MessageBoxResult.Yes)
                    {
                        WindowsHelper.ViewFile(MainExecutingFile.Location);
                    }
                });
            }

            app.Run();
        }