Example #1
0
        internal MSSQLTypeDesc(short typeIndex, NativeTypes baseType, string name, TypeOptions options,
            TypeUsageInfo typeInfo)
        {
            Contract.Requires(typeIndex > 256);
            Contract.Requires(typeInfo != null);
            
            Id = typeIndex;
            BaseType = baseType;
            IsDerived = Id != (short) BaseType;

            Name = name;
            Options = options;
            TypeInfo = typeInfo;
        }
Example #2
0
        /// <summary>
        /// Focuses the element, and sends a <c>keydown</c>, <c>keypress</c>/<c>input</c>, and <c>keyup</c> event for each character in the text.
        /// </summary>
        /// <param name="text">A text to type into a focused element</param>
        /// <param name="options">type options</param>
        /// <remarks>
        /// To press a special key, like <c>Control</c> or <c>ArrowDown</c> use <see cref="ElementHandle.PressAsync(string, PressOptions)"/>
        /// </remarks>
        /// <example>
        /// <code>
        /// elementHandle.TypeAsync("#mytextarea", "Hello"); // Types instantly
        /// elementHandle.TypeAsync("#mytextarea", "World", new TypeOptions { Delay = 100 }); // Types slower, like a user
        /// </code>
        /// An example of typing into a text field and then submitting the form:
        /// <code>
        /// var elementHandle = await page.GetElementAsync("input");
        /// await elementHandle.TypeAsync("some text");
        /// await elementHandle.PressAsync("Enter");
        /// </code>
        /// </example>
        /// <returns>Task</returns>
        public async Task TypeAsync(string text, TypeOptions options = null)
        {
            await FocusAsync().ConfigureAwait(false);

            await Page.Keyboard.TypeAsync(text, options).ConfigureAwait(false);
        }
Example #3
0
        public async Task <int> Run(CLIOptions cliOptions)
        {
            if (!File.Exists(cliOptions.LicenseFile))
            {
                Console.WriteLine($"Error: File not found: ${cliOptions.LicenseFile}");
                if (cliOptions.LicenseFile.StartsWith("'"))
                {
                    Console.WriteLine("' is not supported for the LicenseFile path. Please use \"");
                }
                throw new FileNotFoundException(cliOptions.LicenseFile);
            }

            var slowerTypeOptions = new TypeOptions()
            {
                Delay = 5
            };

            Console.WriteLine("Downloading browser");
            var refInfo = await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);

            Console.WriteLine($"Obtained Chrome: {refInfo.Revision}");

            string[] args = Array.Empty <string>();

            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                Console.WriteLine($"Disabling Chrome Sandbox because we're running in a Docker container...");
                args = new string[] { "--no-sandbox", "--disable-setuid-sandbox" };
            }

            using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions
            {
                Headless = !cliOptions.ShowWindow,
                Args = args,
            }))
            {
                Console.WriteLine("Opening page...");

                using (var page = await browser.NewPageAsync())
                {
                    await page.SetViewportAsync(new ViewPortOptions()
                    {
                        Width = 1280, Height = 1024
                    });

                    await page.GoToAsync(Constants.UnityLicenseUrl);

                    try
                    {
                        //Login
                        await page.WaitForSelectorAsync("#conversations_create_session_form_email");

                        await page.WaitForSelectorAsync("#conversations_create_session_form_password");

                        Console.WriteLine("Logging in...");

                        await Task.Delay(500);

                        //await page.TypeAsync("#conversations_create_session_form_email", cliOptions.Email, slowerTypeOptions);
                        //await page.TypeAsync("#conversations_create_session_form_password", cliOptions.Password, slowerTypeOptions);
                        await page.EvaluateExpressionAsync($"document.querySelector('#conversations_create_session_form_email').value = \"{cliOptions.Email}\"");

                        await page.EvaluateExpressionAsync($"document.querySelector('#conversations_create_session_form_password').value = \"{cliOptions.Password}\"");

                        await page.ClickAsync("#new_conversations_create_session_form input[value='Sign in']");

                        await page.WaitForExpressionAsync("document.querySelectorAll('#conversations_tfa_required_form_verify_code, #licenseFile').length > 0 || document.querySelectorAll(\"button[name='conversations_accept_updated_tos_form[accept]'\").length > 0");

                        //await page.WaitForAnySelectors(null, "#conversations_accept_updated_tos_form[accept]", "document.querySelectorAll('#conversations_tfa_required_form_verify_code, #licenseFile').length");

                        await AcceptTosIfRequired(page);

                        var twoFactorBox = await page.QuerySelectorAsync("#conversations_tfa_required_form_verify_code");

                        if (twoFactorBox != null)
                        {
                            //2fa
                            Console.WriteLine("Logging in using 2fa...");

                            var code = VipAccess.CreateCurrentTotpKey(cliOptions.Secret2fa);
                            Console.WriteLine($"Using code: {code}");

                            //await twoFactorBox.TypeAsync(code, slowerTypeOptions);
                            await page.EvaluateExpressionAsync($"document.querySelector('#conversations_tfa_required_form_verify_code').value = \"{code}\"");

                            await page.ClickAsync("input[value='Verify']");
                        }

                        await page.WaitForExpressionAsync("document.querySelectorAll('#licenseFile').length > 0 || document.querySelectorAll(\"button[name='conversations_accept_updated_tos_form[accept]'\").length > 0");
                        await AcceptTosIfRequired(page);

                        //Upload file
                        await page.WaitForSelectorAsync("#licenseFile");

                        Console.WriteLine("Uploading file...");

                        var fileChooserTask = page.WaitForFileChooserAsync();
                        await page.ClickAsync("#licenseFile");

                        var fileChooser = await fileChooserTask;

                        await fileChooser.AcceptAsync(cliOptions.LicenseFile);

                        await page.ClickAsync("input[value='Next']");

                        //Activate your license
                        var unityPersonalEditionButton = await page.WaitForSelectorAsync("label[for='type_personal']");

                        Console.WriteLine("Selecting edition...");

                        await unityPersonalEditionButton.ClickAsync();

                        var notUseUnityInProfessionalCapacity = await page.WaitForSelectorAsync("label[for='option3']");

                        await notUseUnityInProfessionalCapacity.ClickAsync();

                        var nextButton = await page.WaitForSelectorAsync(".selected input[value='Next']");

                        await nextButton.ClickAsync();

                        //Download license file
                        await page.WaitForSelectorAsync("input[value='Download license file']");

                        Console.WriteLine("Downloading license file...");

                        var downloadManager = new DownloadManager(Directory.GetCurrentDirectory());
                        await downloadManager.SetupPageAsync(page);


                        await page.ClickAsync("input[value='Download license file']");

                        var response = await page.WaitForResponseAsync(r => r.Url.Equals($"https://license.unity3d.com/genesis/activation/download-license", StringComparison.OrdinalIgnoreCase));

                        var data = await response.JsonAsync();

                        var xmlData  = data["xml"].ToString();
                        var fileName = data["name"].ToString();

                        File.WriteAllText("Unity_lic.ulf", xmlData);

                        Console.WriteLine($"File 'Unity_lic.ulf' created. Size: {new FileInfo("Unity_lic.ulf").Length}");
                        return(0);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Error: {ex}");
                        var ssstream = await page.ScreenshotStreamAsync();

                        var curDir     = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
                        var outputFile = Path.Combine(curDir, "error.png");

                        Console.WriteLine($"Writing error screenshot to: {outputFile}");
                        using (var fileStream = File.Create(outputFile))
                        {
                            ssstream.Seek(0, SeekOrigin.Begin);
                            ssstream.CopyTo(fileStream);
                        }
                        Console.WriteLine($"Done writing error screenshot to: {outputFile}");
                        return(1);
                    }
                }
            }
        }
Example #4
0
        /// <summary>
        /// Refreshes from provider.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="libraryOptions">The library options.</param>
        /// <param name="provider">The provider.</param>
        /// <param name="refreshOptions">The refresh options.</param>
        /// <param name="savedOptions">The saved options.</param>
        /// <param name="backdropLimit">The backdrop limit.</param>
        /// <param name="screenshotLimit">The screenshot limit.</param>
        /// <param name="downloadedImages">The downloaded images.</param>
        /// <param name="result">The result.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        private async Task RefreshFromProvider(
            BaseItem item,
            LibraryOptions libraryOptions,
            IRemoteImageProvider provider,
            ImageRefreshOptions refreshOptions,
            TypeOptions savedOptions,
            int backdropLimit,
            int screenshotLimit,
            ICollection <ImageType> downloadedImages,
            RefreshResult result,
            CancellationToken cancellationToken)
        {
            try
            {
                if (!item.SupportsRemoteImageDownloading)
                {
                    return;
                }

                if (!refreshOptions.ReplaceAllImages &&
                    refreshOptions.ReplaceImages.Length == 0 &&
                    ContainsImages(item, provider.GetSupportedImages(item).ToList(), savedOptions, backdropLimit, screenshotLimit))
                {
                    return;
                }

                _logger.LogDebug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);

                var images = await _providerManager.GetAvailableRemoteImages(
                    item,
                    new RemoteImageQuery(provider.Name)
                {
                    IncludeAllLanguages      = false,
                    IncludeDisabledProviders = false,
                },
                    cancellationToken).ConfigureAwait(false);

                var list = images.ToList();
                int minWidth;

                foreach (var imageType in _singularImages)
                {
                    if (!IsEnabled(savedOptions, imageType, item))
                    {
                        continue;
                    }

                    if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType)))
                    {
                        minWidth = savedOptions.GetMinWidth(imageType);
                        var downloaded = await DownloadImage(item, libraryOptions, provider, result, list, minWidth, imageType, cancellationToken).ConfigureAwait(false);

                        if (downloaded)
                        {
                            downloadedImages.Add(imageType);
                        }
                    }
                }

                minWidth = savedOptions.GetMinWidth(ImageType.Backdrop);
                await DownloadBackdrops(item, libraryOptions, ImageType.Backdrop, backdropLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false);

                var hasScreenshots = item as IHasScreenshots;
                if (hasScreenshots != null)
                {
                    minWidth = savedOptions.GetMinWidth(ImageType.Screenshot);
                    await DownloadBackdrops(item, libraryOptions, ImageType.Screenshot, screenshotLimit, provider, result, list, minWidth, cancellationToken).ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
                _logger.LogError(ex, "Error in {provider}", provider.Name);
            }
        }
Example #5
0
 private bool IsEnabled(TypeOptions options, ImageType type, BaseItem item)
 {
     return(options.IsEnabled(type));
 }
Example #6
0
 public bool Has(TypeOptions f)
 {
     return(TypeOptions.HasFlag(f));
 }
Example #7
0
        /// <summary>
        /// Refreshes from provider.
        /// </summary>
        private async Task RefreshFromProvider(BaseItem item,
                                               IDynamicImageProvider provider,
                                               ImageRefreshOptions refreshOptions,
                                               TypeOptions savedOptions,
                                               LibraryOptions libraryOptions,
                                               ICollection <ImageType> downloadedImages,
                                               RefreshResult result,
                                               CancellationToken cancellationToken)
        {
            try
            {
                var images = provider.GetSupportedImages(item);

                foreach (var imageType in images)
                {
                    if (!IsEnabled(savedOptions, imageType, item))
                    {
                        continue;
                    }

                    if (!HasImage(item, imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType)))
                    {
                        _logger.LogDebug("Running {0} for {1}", provider.GetType().Name, item.Path ?? item.Name);

                        var response = await provider.GetImage(item, imageType, cancellationToken).ConfigureAwait(false);

                        if (response.HasImage)
                        {
                            if (!string.IsNullOrEmpty(response.Path))
                            {
                                if (response.Protocol == MediaProtocol.Http)
                                {
                                    _logger.LogDebug("Setting image url into item {0}", item.Id);
                                    item.SetImage(new ItemImageInfo
                                    {
                                        Path = response.Path,
                                        Type = imageType
                                    }, 0);
                                }
                                else
                                {
                                    var mimeType = MimeTypes.GetMimeType(response.Path);

                                    var stream = new FileStream(response.Path, FileMode.Open, FileAccess.Read, FileShare.Read, IODefaults.FileStreamBufferSize, true);

                                    await _providerManager.SaveImage(item, stream, mimeType, imageType, null, cancellationToken).ConfigureAwait(false);
                                }
                            }
                            else
                            {
                                var mimeType = "image/" + response.Format.ToString().ToLowerInvariant();

                                await _providerManager.SaveImage(item, response.Stream, mimeType, imageType, null, cancellationToken).ConfigureAwait(false);
                            }

                            downloadedImages.Add(imageType);
                            result.UpdateType = result.UpdateType | ItemUpdateType.ImageUpdate;
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
                _logger.LogError(ex, "Error in {provider}", provider.Name);
            }
        }
Example #8
0
        /// <summary>
        /// Focuses the element, and sends a <c>keydown</c>, <c>keypress</c>/<c>input</c>, and <c>keyup</c> event for each character in the text.
        /// </summary>
        /// <param name="text">A text to type into a focused element</param>
        /// <param name="options">type options</param>
        /// <remarks>
        /// To press a special key, like <c>Control</c> or <c>ArrowDown</c> use <see cref="ElementHandle.PressAsync(string, PressOptions)"/>
        /// </remarks>
        /// <example>
        /// <code>
        /// elementHandle.TypeAsync("#mytextarea", "Hello"); // Types instantly
        /// elementHandle.TypeAsync("#mytextarea", "World", new TypeOptions { Delay = 100 }); // Types slower, like a user
        /// </code>
        /// An example of typing into a text field and then submitting the form:
        /// <code>
        /// var elementHandle = await page.GetElementAsync("input");
        /// await elementHandle.TypeAsync("some text");
        /// await elementHandle.PressAsync("Enter");
        /// </code>
        /// </example>
        /// <returns>Task</returns>
        public async Task TypeAsync(string text, TypeOptions options = null)
        {
            await FocusAsync();

            await Page.Keyboard.TypeAsync(text, options);
        }
Example #9
0
 /// <summary>
 /// Sends a <c>keydown</c>, <c>keypress</c>/<c>input</c>, and <c>keyup</c> event for each character in the text.
 /// </summary>
 /// <param name="selector">A selector of an element to type into. If there are multiple elements satisfying the selector, the first will be used.</param>
 /// <param name="text">A text to type into a focused element</param>
 /// <param name="options"></param>
 /// <exception cref="SelectorException">If there's no element matching <paramref name="selector"/></exception>
 /// <remarks>
 /// To press a special key, like <c>Control</c> or <c>ArrowDown</c> use <see cref="Keyboard.PressAsync(string, PressOptions)"/>
 /// </remarks>
 /// <example>
 /// <code>
 /// page.TypeAsync("#mytextarea", "Hello"); // Types instantly
 /// page.TypeAsync("#mytextarea", "World", new TypeOptions { Delay = 100 }); // Types slower, like a user
 /// </code>
 /// </example>
 /// <returns>Task</returns>
 public Task TypeAsync(string selector, string text, TypeOptions options = null)
 => SecondaryWorld.TypeAsync(selector, text, options);
Example #10
0
        private async Task RefreshFromProvider(
            BaseItem item,
            IDynamicImageProvider provider,
            ImageRefreshOptions refreshOptions,
            TypeOptions savedOptions,
            ICollection <ImageType> downloadedImages,
            RefreshResult result,
            CancellationToken cancellationToken)
        {
            try
            {
                var images = provider.GetSupportedImages(item);

                foreach (var imageType in images)
                {
                    if (!savedOptions.IsEnabled(imageType))
                    {
                        continue;
                    }

                    if (!item.HasImage(imageType) || (refreshOptions.IsReplacingImage(imageType) && !downloadedImages.Contains(imageType)))
                    {
                        _logger.LogDebug("Running {Provider} for {Item}", provider.GetType().Name, item.Path ?? item.Name);

                        var response = await provider.GetImage(item, imageType, cancellationToken).ConfigureAwait(false);

                        if (response.HasImage)
                        {
                            if (string.IsNullOrEmpty(response.Path))
                            {
                                var mimeType = response.Format.GetMimeType();

                                await _providerManager.SaveImage(item, response.Stream, mimeType, imageType, null, cancellationToken).ConfigureAwait(false);
                            }
                            else
                            {
                                if (response.Protocol == MediaProtocol.Http)
                                {
                                    _logger.LogDebug("Setting image url into item {Item}", item.Id);
                                    var index = item.AllowsMultipleImages(imageType) ? item.GetImages(imageType).Count() : 0;
                                    item.SetImage(
                                        new ItemImageInfo
                                    {
                                        Path = response.Path,
                                        Type = imageType
                                    },
                                        index);
                                }
                                else
                                {
                                    var mimeType = MimeTypes.GetMimeType(response.Path);

                                    var stream = AsyncFile.OpenRead(response.Path);

                                    await _providerManager.SaveImage(item, stream, mimeType, imageType, null, cancellationToken).ConfigureAwait(false);
                                }
                            }

                            downloadedImages.Add(imageType);
                            result.UpdateType |= ItemUpdateType.ImageUpdate;
                        }
                    }
                }
            }
            catch (OperationCanceledException)
            {
                throw;
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
                _logger.LogError(ex, "Error in {Provider}", provider.Name);
            }
        }
Example #11
0
        private static Func <DeserializationContext, object> ForComplex(Type type, TypeOptions options, Func <Type, TypeDescriptor> descriptorSource)
        {
            var info = type.GetTypeInfo();

            if (info.IsClass && info.GetConstructor(Type.EmptyTypes) == null)
            {
                return(reader => throw new JsonException(info.IsAbstract
                                        ? $"Type {type} is abstract. Add {nameof(ITypeSelector)} to {nameof(SerializationSettings)} in order to deserialize this type."
                                        : $"Type {type} must define public parameterless constructor."));
            }

            var properties = info
                             .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                             .Where(i => i.SetMethod != null && i.GetMethod != null)
                             .Select(i => new { Property = (MemberInfo)i, Setter = ReflectionUtils.BuildSetter(i), Descriptor = descriptorSource(i.PropertyType) });

            var fields = info
                         .GetFields(BindingFlags.Instance | BindingFlags.Public)
                         .Select(i => new { Property = (MemberInfo)i, Setter = ReflectionUtils.BuildFieldSetter(i), Descriptor = descriptorSource(i.FieldType) });

            var all = properties
                      .Concat(fields)
                      .SelectMany(i => JsonNames(i.Property).Select(j => new PropertyBinding {
                Name = j, Setter = i.Setter, Descriptor = i.Descriptor
            }))
                      .GroupBy(i => i.Name)
                      .ToDictionary(i => i.Key, i => i.First());

            var constructor = info.IsClass
                                ? ReflectionUtils.BuildConstructor(type)
                                : () => Activator.CreateInstance(typeof(Box <>).MakeGenericType(type));

            //struct types are internally wrapped into Box<T> type (see ReflectionUtils)
            var unwrapper = !info.IsClass
                                ? new Func <object, object>(i => ((IBox)i).Value)
                                : null;

            return(context =>
            {
                var bufferPart = new BufferPart();
                var reader = context.Reader;
                var token = reader.Read(ref bufferPart, out var _);
                if (token == JsonToken.Null)
                {
                    return info.IsClass ? (object)null : throw new JsonException($"Unable to assign null value to struct type near line {reader.Line}, column {reader.Column}.");
                }
                if (token != JsonToken.ObjectStart)
                {
                    throw Exceptions.BadToken(reader, token, JsonToken.ObjectStart);
                }
                var target = constructor();
                var deferred = ReadProperties(target, context, all);
                var unwrapped = unwrapper != null?unwrapper(target) : target;

                if (deferred == null)
                {
                    return unwrapped;
                }

                foreach (var entry in deferred)
                {
                    var runtimeType = entry.Selector.FindPropertyType(entry.Binding.Name, unwrapped);
                    var descriptor = context.Catalog.GetDescriptor(runtimeType, options);
                    using (reader.LoadSnapshot(entry.Snapshot))
                        entry.Binding.Setter(target, descriptor.Reader(context));
                }
                return unwrapper != null?unwrapper(target) : target;
            });
        }
Example #12
0
 /// <inheritdoc cref="IKeyboard.TypeAsync(string, TypeOptions)"/>
 public Task TypeAsync(string text, TypeOptions options = null)
 {
     throw new NotImplementedException();
 }