[
  {
    "path": ".gitattributes",
    "content": "/.gitattributes            export-ignore\n/phpunit.xml               export-ignore\n/tests                     export-ignore\n/ISSUE_TEMPLATE.md         export-ignore\n/PULL_REQUEST_TEMPLATE.md  export-ignore"
  },
  {
    "path": ".gitignore",
    "content": ".idea\nvendor/\n/composer.lock"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\nAll Notable changes to `visitor` will be documented in this file.\n\nUpdates should follow the [Keep a CHANGELOG](http://keepachangelog.com/) principles.\n\n## Date - 2019-01-09\n\n### Fixed\n- Nothing\n\n### Added\n- Nothing\n\n### Deprecated\n- Nothing\n\n### Fixed\n- Nothing\n\n### Removed\n- Nothing\n\n### Security\n- Nothing\n"
  },
  {
    "path": "CONDUCT.md",
    "content": "# Contributor Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and maintainers pledge to making participation in our project and\nour community a harassment-free experience for everyone, regardless of age, body\nsize, disability, ethnicity, gender identity and expression, level of experience,\nnationality, personal appearance, race, religion, or sexual identity and\norientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment\ninclude:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or\nadvances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic\n  address, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\n  professional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable\nbehavior and are expected to take appropriate and fair corrective action in\nresponse to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or\nreject comments, commits, code, wiki edits, issues, and other contributions\nthat are not aligned to this Code of Conduct, or to ban temporarily or\npermanently any contributor for other behaviors that they deem inappropriate,\nthreatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies both within project spaces and in public spaces\nwhen an individual is representing the project or its community. Examples of\nrepresenting a project or community include using an official project e-mail\naddress, posting via an official social media account, or acting as an appointed\nrepresentative at an online or offline event. Representation of a project may be\nfurther defined and clarified by project maintainers.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported by contacting the project team at `khanzadimahdi@gmail.com`. All\ncomplaints will be reviewed and investigated and will result in a response that\nis deemed necessary and appropriate to the circumstances. The project team is\nobligated to maintain confidentiality with regard to the reporter of an incident.\nFurther details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good\nfaith may face temporary or permanent repercussions as determined by other\nmembers of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\navailable at [http://contributor-covenant.org/version/1/4][version]\n\n[homepage]: http://contributor-covenant.org\n[version]: http://contributor-covenant.org/version/1/4/\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\nContributions are **welcome** and will be fully **credited**.\n\nWe accept contributions via Pull Requests on [Github](https://github.com/shetabit/visitor).\n\n## Pull Requests\n\n- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - Check the code style with ``$ composer check-style`` and fix it with ``$ composer fix-style``.\n\n- **Add tests!** - Your patch won't be accepted if it doesn't have tests.\n\n- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.\n\n- **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option.\n\n- **Create feature branches** - Don't ask us to pull from your master branch.\n\n- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.\n\n- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.\n\n\n**Happy coding**!\n"
  },
  {
    "path": "ISSUE_TEMPLATE.md",
    "content": "<!-- Provide a general summary of the issue in the Title above -->\n\n## Detailed description\n\nProvide a detailed description of the change or addition you are proposing.\n\nMake it clear if the issue is a bug, an enhancement or just a question.\n\n## Context\n\nWhy is this change important to you? How would you use it?\n\nHow can it benefit other users?\n\n## Possible implementation\n\nNot obligatory, but suggest an idea for implementing addition or change.\n\n## Your environment\n\nInclude as many relevant details about the environment you experienced the bug in and how to reproduce it.\n\n* Version used (e.g. PHP 7.2, HHVM 3):\n* Operating system and version (e.g. Ubuntu 19.04, Windows 10):\n* Link to your project:\n* ...\n* ...\n"
  },
  {
    "path": "LICENSE.md",
    "content": "# The MIT License (MIT)\n\nCopyright (c) 2019 Mahdi Khanzadi <khanzadimahdi@gmail.com>\n\n> Permission is hereby granted, free of charge, to any person obtaining a copy\n> of this software and associated documentation files (the \"Software\"), to deal\n> in the Software without restriction, including without limitation the rights\n> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n> copies of the Software, and to permit persons to whom the Software is\n> furnished to do so, subject to the following conditions:\n>\n> The above copyright notice and this permission notice shall be included in\n> all copies or substantial portions of the Software.\n>\n> THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n> THE SOFTWARE.\n"
  },
  {
    "path": "PULL_REQUEST_TEMPLATE.md",
    "content": "<!--- Provide a general summary of your changes in the Title above -->\n\n## Description\n\nDescribe your changes in detail.\n\n## Motivation and context\n\nWhy is this change required? What problem does it solve?\n\nIf it fixes an open issue, please link to the issue here (if you write `fixes #num`\nor `closes #num`, the issue will be automatically closed when the pull is accepted.)\n\n## How has this been tested?\n\nPlease describe in detail how you tested your changes.\n\nInclude details of your testing environment, and the tests you ran to\nsee how your change affects other areas of the code, etc.\n\n## Screenshots (if appropriate)\n\n## Types of changes\n\nWhat types of changes does your code introduce? Put an `x` in all the boxes that apply:\n- [ ] Bug fix (non-breaking change which fixes an issue)\n- [ ] New feature (non-breaking change which adds functionality)\n- [ ] Breaking change (fix or feature that would cause existing functionality to change)\n\n## Checklist:\n\nGo over all the following points, and put an `x` in all the boxes that apply.\n\nPlease, please, please, don't send your pull request until all of the boxes are ticked. Once your pull request is created, it will trigger a build on our [continuous integration](http://www.phptherightway.com/#continuous-integration) server to make sure your [tests and code style pass](https://help.github.com/articles/about-required-status-checks/).\n\n- [ ] I have read the **[CONTRIBUTING](CONTRIBUTING.md)** document.\n- [ ] My pull request addresses exactly one patch/feature.\n- [ ] I have created a branch for this patch/feature.\n- [ ] Each individual commit in the pull request is meaningful.\n- [ ] I have added tests to cover my changes.\n- [ ] If my change requires a change to the documentation, I have updated it accordingly.\n\nIf you're unsure about any of these, don't hesitate to ask. We're here to help!\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\"><img width=\"200\" src=\"resources/images/visitor.png?raw=true\"></p>\n\n# Laravel Visitor\n\nThis is a laravel package to extract and access visitors' information such as `browser`, `ip`, `device` and etc.\n\n**In this package, you can recognize online users and determine if a user is online or not**\n\n### Install\n\nVia composer\n\n```bash\ncomposer require shetabit/visitor\n```\n\n### Configure\n\nIf you are using Laravel 5.5 or higher then you don't need to add the provider and alias.\n\n```php\n# In your providers array.\n'providers' => [\n    ...\n    Shetabit\\Visitor\\Provider\\VisitorServiceProvider::class,\n],\n\n# In your aliases array.\n'aliases' => [\n    ...\n    'Visitor' => Shetabit\\Visitor\\Facade\\Visitor::class,\n],\n```\n\nThen, run the below commands to publish migrations and create tables\n\n```bash\nphp artisan vendor:publish\n\nphp artisan migrate\n```\n\n### How to use\n\nYou can access to `visitor's information` using `$request->visitor()` in your controllers , and  you can access to the visitor's information using `visitor()` helper function any where.\n\nWe have the below methods to retrieve a visitor's information:\n\n- `device` : device's name\n- `platform` : platform's name\n- `browser` : browser's name\n- `languages` : language's name\n- `ip` : client's ip\n- `request` : the whole request inputs\n- `useragent` : the whole useragent\n- `isOnline` : determines if current (or given) user is online\n\n```php\n$request->visitor()->browser(); // firefox\n$request->visitor()->visit($post); // create log for post\n$request->visitor()->setVisitor($user)->visit($post); // create a log which says $user has visited $post\n```\n\n#### Store Logs\n\nYou can create logs using the `visit` method like the below\n\n```php\nvisitor()->visit(); // create a visit log\n```\n\nuse `Shetabit\\Visitor\\Traits\\Visitable` trait in your models, then you can save visit's log for your models like the below\n\n```php\n// or you can save log like the below\nvisitor()->visit($model);\n// or like the below\n$model->createVisitLog();\n\n// you can say which user has visited the given $model\n$model->createVisitLog($user);\n// or like the below\nvisitor()->setVisitor($user)->visit($model);\n\n```\n\nModel views can be loaded using `visits` relation.\n\nYou can count model visits like the below\n\n```php\n$model->visitLogs()->count();\n```\nunique users can be counted by their IP and by model.\n\n```php\n// by ip\n$model->visitLogs()->distinct('ip')->count('ip');\n\n// by user's model\n$model->visitLogs()->visitor()->count();\n```\n\nuse `Shetabit\\Visitor\\Traits\\Visitor` in your `User` class, then you can run below codes\n\n ```php\n$user->visit(); // create a visit log\n$user->visit($model); // create a log which says, $user has visited $model\n ```\n\n#### Retrieve and Determine Online users\n\nuse `Shetabit\\Visitor\\Traits\\Visitor` in your `User` class at first.\n\nThen you can retrieve online users which are instance of `User` class and determine if a user is online.\n\n```php\nvisitor()->onlineVisitors(User::class); // returns collection of online users\nUser::online()->get(); // another way\n\nvisitor()->isOnline($user); // determines if the given user is online\n$user->isOnline(); // another way\n```\n\n#### Automatic logging\n\nYour application can store visitor's log automatically using `LogVisits` middleware.\n\nAdd the `Shetabit\\Visitor\\Middlewares\\LogVisits` middleware if you want to save logs automatically.\n\nThe middleware will store logs for models which has binded in router (router model binding) and has used `Shetabit\\Visitor\\Traits\\Visitable` trait.\n\n## Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=shetabit/visitor&type=Date)](https://star-history.com/#shetabit/visitor&Date)\n\n"
  },
  {
    "path": "composer.json",
    "content": "{\n    \"name\": \"shetabit/visitor\",\n    \"type\": \"library\",\n    \"description\": \"Laravel visitor\",\n    \"keywords\": [\n        \"shetabit\",\n        \"visitor\",\n        \"track laravel visitors\",\n        \"trace laravel visitors\",\n        \"parse laravel user agents\"\n    ],\n    \"homepage\": \"https://github.com/shetabit/visitor\",\n    \"license\": \"MIT\",\n    \"authors\": [\n        {\n            \"name\": \"Mahdi Khanzadi\",\n            \"email\": \"khanzadimahdi@gmail.com\",\n            \"homepage\": \"https://github.com/khanzadimahdi\",\n            \"role\": \"Developer\"\n        }\n    ],\n    \"require\": {\n        \"php\": \">=8.0\",\n        \"illuminate/support\": \"9.*|10.*|11.*|12.*|^13.0\",\n        \"ua-parser/uap-php\": \"^3.9\",\n        \"mobiledetect/mobiledetectlib\": \"^4.8\",\n        \"jaybizzle/crawler-detect\": \"^1.2\"\n    },\n    \"require-dev\": {\n        \"orchestra/testbench\": \"^4.0|^5.0|^6.0|^7.0|^8.0|^9.0|^10.0|^11.0\",\n        \"phpunit/phpunit\": \">=7.5\",\n        \"squizlabs/php_codesniffer\": \"^3.4|^4.0\"\n    },\n    \"autoload\": {\n        \"psr-4\": {\n            \"Shetabit\\\\Visitor\\\\\": \"src\"\n        },\n        \"files\": [\n            \"src/helpers.php\"\n        ]\n    },\n    \"autoload-dev\": {\n        \"psr-4\": {\n            \"Shetabit\\\\Visitor\\\\Tests\\\\\": \"tests\"\n        }\n    },\n    \"scripts\": {\n        \"test\": \"phpunit\",\n        \"check-style\": \"phpcs -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src tests\",\n        \"fix-style\": \"phpcbf -p --standard=PSR2 --runtime-set ignore_errors_on_exit 1 --runtime-set ignore_warnings_on_exit 1 src tests\"\n    },\n    \"extra\": {\n        \"laravel\": {\n            \"providers\": [\n                \"Shetabit\\\\Visitor\\\\Provider\\\\VisitorServiceProvider\"\n            ],\n            \"aliases\": {\n                \"Visitor\": \"Shetabit\\\\Visitor\\\\Facade\\\\Visitor\"\n            }\n        }\n    },\n    \"config\": {\n        \"sort-packages\": true\n    }\n}\n"
  },
  {
    "path": "config/visitor.php",
    "content": "<?php\nreturn [\n    /*\n    |--------------------------------------------------------------------------\n    | Default Driver\n    |--------------------------------------------------------------------------\n    |\n    | This value determines which of the following driver to use.\n    | You can switch to a different driver at runtime.\n    |\n    */\n    'default' => 'jenssegers',\n\n    //except save request or route names\n    'except' =>  ['login', 'register'],\n\n\n    //name of the table which visit records should save in\n    'table_name' =>  'shetabit_visits',\n\n    /*\n    |--------------------------------------------------------------------------\n    | List of Drivers\n    |--------------------------------------------------------------------------\n    |\n    | This is the array of Classes that maps to Drivers above.\n    | You can create your own driver if you like and add the\n    | config in the drivers array and the class to use for\n    | here with the same name. You will have to implement\n    | Shetabit\\Visitor\\Contracts\\UserAgentParser in your driver.\n    |\n    */\n    'drivers' => [\n        'jenssegers' => \\Shetabit\\Visitor\\Drivers\\JenssegersAgent::class,\n        'UAParser' => \\Shetabit\\Visitor\\Drivers\\UAParser::class,\n    ],\n\t\n\t/*\n\t|--------------------------------------------------------------------------\n\t| GeoIP Enrichment\n\t|--------------------------------------------------------------------------\n\t|\n\t| When enabled, visits can be enriched with geolocation data stored\n\t| in the \"geo_raw\" JSON column. This package ships with a default\n\t| resolver (stevebauman/location). You may implement your own by\n\t| adding it to the drivers array below. Each driver must implement\n\t| Shetabit\\Visitor\\Contracts\\GeoIpResolver.\n\t|\n\t*/\n\t'geoip'   => false,           // disable enrichment by default\n\t'resolver'=> 'stevebauman',   // default resolver\n\t'resolvers' => [\n\t\t'stevebauman' => \\Shetabit\\Visitor\\Resolvers\\GeoIp\\SteveBaumanResolver::class,\n\t\t'null'        => \\Shetabit\\Visitor\\Resolvers\\GeoIp\\NullResolver::class,\n\t],\t\n];\n"
  },
  {
    "path": "database/migrations/add_geo_raw_to_visits_table.php.stub",
    "content": "<?php\n\nuse Illuminate\\Database\\Migrations\\Migration;\nuse Illuminate\\Database\\Schema\\Blueprint;\nuse Illuminate\\Support\\Facades\\Schema;\n\nclass AddGeoRawToVisitsTable extends Migration\n{\n    public function up()\n    {\n        Schema::table(config('visitor.table_name'), function (Blueprint $table) {\n            $table->json('geo_raw')->nullable()->after('ip');\n        });\n    }\n\n    public function down()\n    {\n        Schema::table(config('visitor.table_name'), function (Blueprint $table) {\n            $table->dropColumn('geo_raw');\n        });\n    }\n}\n"
  },
  {
    "path": "database/migrations/create_visits_table.php.stub",
    "content": "<?php\n\nuse Illuminate\\Database\\Migrations\\Migration;\nuse Illuminate\\Database\\Schema\\Blueprint;\nuse Illuminate\\Support\\Facades\\Schema;\n\nclass CreateVisitsTable extends Migration\n{\n    /**\n     * Run the migrations.\n     *\n     * @return void\n     */\n    public function up()\n    {\n        Schema::create(config('visitor.table_name'), function (Blueprint $table) {\n            $table->bigIncrements('id');\n            $table->string('method')->nullable();\n            $table->mediumText('request')->nullable();\n            $table->mediumText('url')->nullable();\n            $table->mediumText('referer')->nullable();\n            $table->text('languages')->nullable();\n            $table->text('useragent')->nullable();\n            $table->text('headers')->nullable();\n            $table->text('device')->nullable();\n            $table->text('platform')->nullable();\n            $table->text('browser')->nullable();\n            $table->ipAddress('ip')->nullable();\n\t\t\t$table->json('geo_raw')->nullable()->comment('Optional GeoIP payload (country_code, region, city, lat/lng, …)');\n            $table->nullableMorphs('visitable'); // object model\n            $table->nullableMorphs('visitor'); // subject model\n            $table->timestamps();\n        });\n    }\n\n    /**\n     * Reverse the migrations.\n     *\n     * @return void\n     */\n    public function down()\n    {\n        Schema::dropIfExists(config('visitor.table_name'));\n    }\n}\n"
  },
  {
    "path": "phpunit.xml",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<phpunit backupGlobals=\"false\"\n        backupStaticAttributes=\"false\"\n        bootstrap=\"vendor/autoload.php\"\n        colors=\"true\"\n        convertErrorsToExceptions=\"true\"\n        convertNoticesToExceptions=\"true\"\n        convertWarningsToExceptions=\"true\"\n        processIsolation=\"false\"\n        stopOnFailure=\"false\">\n    <filter>\n        <whitelist>\n            <directory>./src/</directory>\n        </whitelist>\n    </filter>\n    <testsuites>\n        <testsuite name=\"Test Suite\">\n            <directory suffix=\"Test.php\">./tests/</directory>\n        </testsuite>\n    </testsuites>\n    <php>\n        <env name=\"APP_ENV\" value=\"testing\"/>\n    </php>\n</phpunit>\n"
  },
  {
    "path": "src/Agent.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor;\n\nuse BadMethodCallException;\nuse Closure;\nuse Detection\\Exception\\MobileDetectException;\nuse Detection\\MobileDetect;\nuse Jaybizzle\\CrawlerDetect\\CrawlerDetect;\nuse Random\\RandomException;\n\nclass Agent extends MobileDetect\n{\n\n    /**\n     * List of desktop devices.\n     *\n     * @var array<string, string>\n     */\n    protected static array $desktopDevices = [\n        'Macintosh' => 'Macintosh',\n    ];\n    /**\n     * List of additional operating systems.\n     *\n     * @var array<string, string>\n     */\n    protected static array $additionalOperatingSystems = [\n        'Windows' => 'Windows',\n        'Windows NT' => 'Windows NT',\n        'OS X' => 'Mac OS X',\n        'Debian' => 'Debian',\n        'Ubuntu' => 'Ubuntu',\n        'Macintosh' => 'PPC',\n        'OpenBSD' => 'OpenBSD',\n        'Linux' => 'Linux',\n        'ChromeOS' => 'CrOS',\n    ];\n    /**\n     * List of additional browsers.\n     *\n     * @var array<string, string>\n     */\n    protected static array $additionalBrowsers = [\n        'Opera Mini' => 'Opera Mini',\n        'Opera' => 'Opera|OPR',\n        'Edge' => 'Edge|Edg',\n        'Coc Coc' => 'coc_coc_browser',\n        'UCBrowser' => 'UCBrowser',\n        'Vivaldi' => 'Vivaldi',\n        'Chrome' => 'Chrome',\n        'Firefox' => 'Firefox',\n        'Safari' => 'Safari',\n        'IE' => 'MSIE|IEMobile|MSIEMobile|Trident/[.0-9]+',\n        'Netscape' => 'Netscape',\n        'Mozilla' => 'Mozilla',\n        'WeChat' => 'MicroMessenger',\n    ];\n\n    protected static CrawlerDetect $crawlerDetect;\n\n    /**\n     * Key value store for resolved strings.\n     *\n     * @var array<string, mixed>\n     */\n    protected array $store = [];\n\n    public function getRules(): array\n    {\n        static $rules;\n\n        if (!$rules) {\n            $rules = array_merge(\n                static::$browsers,\n                static::$operatingSystems,\n                static::$phoneDevices,\n                static::$tabletDevices,\n                static::$desktopDevices, // NEW\n                static::$additionalOperatingSystems, // NEW\n                static::$additionalBrowsers // NEW\n            );\n        }\n\n        return $rules;\n    }\n\n    /**\n     * Get accept languages.\n     * @param string|null $acceptLanguage\n     * @return array\n     */\n    public function languages(string $acceptLanguage = null): array\n    {\n        if ($acceptLanguage === null) {\n            $acceptLanguage = $this->getHttpHeader('HTTP_ACCEPT_LANGUAGE');\n        }\n\n        if (!$acceptLanguage) {\n            return [];\n        }\n\n        $languages = [];\n\n        // Parse accept language string.\n        foreach (explode(',', $acceptLanguage) as $piece) {\n            $parts = explode(';', $piece);\n            $language = strtolower($parts[0]);\n            $priority = empty($parts[1]) ? 1. : (float)str_replace('q=', '', $parts[1]);\n\n            $languages[$language] = $priority;\n        }\n\n        // Sort languages by priority.\n        arsort($languages);\n\n        return array_keys($languages);\n    }\n\n    /**\n     * Get the browser name.\n     * @return string|bool\n     */\n    public function browser(): bool|string\n    {\n        return $this->retrieveUsingCacheOrResolve('visitor.browser', function () {\n            return $this->findDetectionRulesAgainstUserAgent(\n                $this->mergeRules(static::$additionalBrowsers, MobileDetect::getBrowsers())\n            );\n        });\n    }\n\n    /**\n     * Retrieve from the given key from the cache or resolve the value.\n     *\n     * @param string $key\n     * @param \\Closure():mixed $callback\n     * @return mixed\n     */\n    protected function retrieveUsingCacheOrResolve(string $key, Closure $callback): mixed\n    {\n        $cacheKey = $this->createCacheKey($key);\n\n        if (!is_null($cacheItem = $this->store[$cacheKey] ?? null)) {\n            return $cacheItem;\n        }\n\n        return tap($callback(), function ($result) use ($cacheKey) {\n            $this->store[$cacheKey] = $result;\n        });\n    }\n\n    /**\n     * @throws RandomException\n     */\n    protected function createCacheKey(string $key): string\n    {\n        $userAgentKey = $this->hasUserAgent() ? $this->userAgent : '';\n        $randomBytes = random_bytes(16);\n        $randomHash = bin2hex($randomBytes);\n\n        return base64_encode(\"$key:$userAgentKey:$randomHash\");\n    }\n\n    /**\n     * Match a detection rule and return the matched key.\n     *\n     * @param array $rules\n     * @return string|null\n     */\n    protected function findDetectionRulesAgainstUserAgent(array $rules): ?string\n    {\n        $userAgent = $this->getUserAgent();\n\n        foreach ($rules as $key => $regex) {\n            if (empty($regex)) {\n                continue;\n            }\n\n            // regex is an array of \"strings\"\n            if (is_array($regex)) {\n                foreach ($regex as $regexString) {\n                    if ($this->match($regexString, $userAgent)) {\n                        return $key ?: reset($this->matchesArray);\n                    }\n                }\n            } else if ($this->match($regex, $userAgent)) {\n                return $key ?: reset($this->matchesArray);\n            }\n\n        }\n\n        return false;\n    }\n\n    /**\n     * Merge multiple rules into one array.\n     *\n     * @param array $all\n     * @return array<string, string>\n     */\n    protected function mergeRules(...$all): array\n    {\n        $merged = [];\n\n        foreach ($all as $rules) {\n            foreach ($rules as $key => $value) {\n                if (empty($merged[$key])) {\n                    $merged[$key] = $value;\n                } elseif (is_array($merged[$key])) {\n                    $merged[$key][] = $value;\n                } else {\n                    $merged[$key] .= '|' . $value;\n                }\n            }\n        }\n\n        return $merged;\n    }\n\n    /**\n     * Get the platform name.\n     *\n     * @return string|bool\n     */\n    public function platform(): bool|string\n    {\n        return $this->retrieveUsingCacheOrResolve('visitor.platform', function () {\n            return $this->findDetectionRulesAgainstUserAgent(\n                $this->mergeRules(static::$additionalOperatingSystems, MobileDetect::getOperatingSystems())\n            );\n        });\n    }\n\n    /**\n     * Get the device name.\n     * @return string|bool\n     */\n    public function device(): bool|string\n    {\n        return $this->findDetectionRulesAgainstUserAgent(\n            $this->mergeRules(\n                static::getDesktopDevices(),\n                static::getPhoneDevices(),\n                static::getTabletDevices()\n            )\n        );\n    }\n\n    /**\n     * Retrieve the list of known Desktop devices.\n     *\n     * @return array List of Desktop devices.\n     */\n    public static function getDesktopDevices(): array\n    {\n        return static::$desktopDevices;\n    }\n\n    /**\n     * Get the robot name.\n     * @return string|bool\n     */\n    public function robot(): bool|string\n    {\n        $userAgent = $this->getUserAgent();\n\n        if ($this->getCrawlerDetect()->isCrawler($userAgent ?: $this->userAgent)) {\n            return ucfirst($this->getCrawlerDetect()->getMatches());\n        }\n\n        return false;\n    }\n\n    /**\n     * @return CrawlerDetect\n     */\n    public function getCrawlerDetect(): CrawlerDetect\n    {\n        if (static::$crawlerDetect === null) {\n            static::$crawlerDetect = new CrawlerDetect();\n        }\n\n        return static::$crawlerDetect;\n    }\n\n    /**\n     * Get the device type\n     * @return string\n     * @throws MobileDetectException\n     */\n    public function deviceType(): string\n    {\n        if ($this->isDesktop()) {\n            return \"desktop\";\n        }\n\n        if ($this->isPhone()) {\n            return \"phone\";\n        }\n\n        if ($this->isTablet()) {\n            return \"tablet\";\n        }\n\n        if ($this->isRobot()) {\n            return \"robot\";\n        }\n\n        return \"other\";\n    }\n\n    /**\n     * Check if the device is a desktop computer.\n     * @return bool\n     * @throws MobileDetectException\n     */\n    public function isDesktop(): bool\n    {\n        $userAgent = $this->getUserAgent();\n\n        return $this->retrieveUsingCacheOrResolve('visitor.desktop', function () use ($userAgent) {\n\n            // Check specifically for cloudfront headers if the useragent === 'Amazon CloudFront'\n            if ($userAgent === static::$cloudFrontUA && $this->getHttpHeader('HTTP_CLOUDFRONT_IS_DESKTOP_VIEWER') === 'true') {\n                return true;\n            }\n\n            return !$this->isMobile() && !$this->isTablet() && !$this->isRobot($userAgent);\n        });\n\n    }\n\n    /**\n     * Check if device is a robot.\n     * @return bool\n     */\n    public function isRobot(): bool\n    {\n        $userAgent = $this->getUserAgent();\n\n        return $this->getCrawlerDetect()->isCrawler($userAgent ?: $this->userAgent);\n    }\n\n    /**\n     * Check if the device is a mobile phone.\n     * @return bool\n     * @throws MobileDetectException\n     */\n    public function isPhone(): bool\n    {\n        return $this->isMobile() && !$this->isTablet();\n    }\n\n    /**\n     * @inheritdoc\n     */\n    public function __call($name, $arguments)\n    {\n        // Make sure the name starts with 'is', otherwise\n        if (!str_starts_with($name, 'is')) {\n            throw new BadMethodCallException(\"No such method exists: $name\");\n        }\n\n        $key = substr($name, 2);\n\n        return $this->matchUserAgentWithRule($key);\n    }\n}\n"
  },
  {
    "path": "src/Contracts/GeoIpResolver.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Contracts;\n\ninterface GeoIpResolver\n{\n    /**\n     * Resolve a given IP address into a GeoIP payload.\n     *\n     * @param string $ip\n     * @return array|null\n     *\n     * Example return:\n     * [\n     *   'ip'           => '192.168.1.1',\n     *   'country_code' => 'FR',\n     *   'country_name' => 'France',\n     *   'region_name'  => 'Île-de-France',\n     *   'city_name'    => 'Paris',\n     *   'latitude'     => 48.8566,\n     *   'longitude'    => 2.3522,\n     * ]\n     */\n    public function resolve(string $ip): ?array;\n}\n"
  },
  {
    "path": "src/Contracts/UserAgentParser.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Contracts;\n\ninterface UserAgentParser\n{\n    /**\n     * Retrieve device's name.\n     *\n     * @return string\n     */\n    public function device() : string;\n\n    /**\n     * Retrieve platform's name.\n     *\n     * @return string\n     */\n    public function platform() : string;\n\n    /**\n     * Retrieve browser's name.\n     *\n     * @return string\n     */\n    public function browser() : string;\n\n    /**\n     * Retrieve languages.\n     *\n     * @return array\n     */\n    public function languages() : array;\n}\n"
  },
  {
    "path": "src/Drivers/JenssegersAgent.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Drivers;\n\nuse Illuminate\\Http\\Request;\nuse Shetabit\\Visitor\\Agent;\nuse Shetabit\\Visitor\\Contracts\\UserAgentParser;\n\nclass JenssegersAgent implements UserAgentParser\n{\n    /**\n     * Request container.\n     */\n    protected Request $request;\n\n    /**\n     * Agent parser.\n     */\n    protected Agent $parser;\n\n    /**\n     * Parser constructor.\n     *\n     * @param Request $request\n     */\n    public function __construct(Request $request)\n    {\n        $this->request = $request;\n        $this->parser = $this->initParser();\n    }\n\n    /**\n     * Retrieve device's name.\n     */\n    public function device() : string\n    {\n        return $this->parser->device();\n    }\n\n    /**\n     * Retrieve platform's name.\n     */\n    public function platform() : string\n    {\n        return $this->parser->platform();\n    }\n\n    /**\n     * Retrieve browser's name.\n     */\n    public function browser() : string\n    {\n        return $this->parser->browser();\n    }\n\n    /**\n     * Retrieve languages.\n     */\n    public function languages() : array\n    {\n        return $this->parser->languages();\n    }\n\n    /**\n     * Initialize userAgent parser.\n     */\n    protected function initParser(): Agent\n    {\n        $parser = new Agent();\n        $userAgent = $this->request->userAgent() ?? '';\n        \n        $parser->setUserAgent($userAgent);\n        $parser->setHttpHeaders((array)$this->request->headers);    \n        \n        return $parser;\n    }\n}\n"
  },
  {
    "path": "src/Drivers/UAParser.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Drivers;\n\nuse UAParser\\Parser;\nuse Illuminate\\Http\\Request;\nuse Shetabit\\Visitor\\Contracts\\UserAgentParser;\n\nclass UAParser implements UserAgentParser\n{\n    /**\n     * Request container.\n     */\n    protected Request $request;\n\n    /**\n     * Agent parser.\n     */\n    protected \\UAParser\\Result\\Client $parser;\n\n    /**\n     * UAParser constructor.\n     *\n     * @param Request $request\n     *\n     * @throws \\UAParser\\Exception\\FileNotFoundException\n     */\n    public function __construct(Request $request)\n    {\n        $this->request = $request;\n        $this->parser = $this->initParser();\n    }\n\n    /**\n     * Retrieve device's name.\n     */\n    public function device() : string\n    {\n        return $this->parser->device->family;\n    }\n\n    /**\n     * Retrieve platform's name.\n     */\n    public function platform() : string\n    {\n        return $this->parser->os->family;\n    }\n\n    /**\n     * Retrieve browser's name.\n     */\n    public function browser() : string\n    {\n        return $this->parser->ua->family;\n    }\n\n    /**\n     * Retrieve languages.\n     */\n    public function languages() : array\n    {\n        $languages = [];\n\n        if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {\n            $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);\n            $languages[] = $lang;\n        }\n\n        return $languages;\n    }\n\n    /**\n     * Initialize userAgent parser.\n     *\n     * @throws \\UAParser\\Exception\\FileNotFoundException\n     */\n    protected function initParser(): \\UAParser\\Result\\Client\n    {\n        return Parser::create()->parse($this->request->userAgent());\n    }\n}\n"
  },
  {
    "path": "src/Exceptions/DriverNotFoundException.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Exceptions;\n\nclass DriverNotFoundException extends \\Exception\n{\n    //\n}\n"
  },
  {
    "path": "src/Exceptions/ResolverNotFoundException.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Exceptions;\n\nclass ResolverNotFoundException extends \\Exception\n{\n    //\n}\n"
  },
  {
    "path": "src/Facade/Agent.php",
    "content": "<?php\n\nnamespace Shetabit\\Agent\\Facades;\n\nuse Illuminate\\Support\\Facades\\Facade;\n\nclass Agent extends Facade\n{\n    /**\n     * Get the registered name of the component.\n     *\n     * @return string\n     */\n    protected static function getFacadeAccessor(): string\n    {\n        return 'agent';\n    }\n}\n"
  },
  {
    "path": "src/Facade/Visitor.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Facade;\n\nuse Illuminate\\Support\\Facades\\Facade;\n\n/**\n * Class viewer\n *\n * @package Shetabit\\Visitor\\Facade\n */\nclass Visitor extends Facade\n{\n    /**\n     * Get the registered name of the component.\n     *\n     * @return string\n     */\n    public static function getFacadeAccessor(): string\n    {\n        return 'shetabit-visitor';\n    }\n}\n"
  },
  {
    "path": "src/Middlewares/LogVisits.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Middlewares;\n\nuse Closure;\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Support\\Facades\\Auth;\n\nclass LogVisits\n{\n    /**\n     * Handle an incoming request.\n     *\n     * @param  \\Illuminate\\Http\\Request  $request\n     * @param  \\Closure  $next\n     *\n     * @return mixed\n     */\n    public function handle($request, Closure $next)\n    {\n        $logHasSaved = false;\n\n        // create log for first binded model\n        foreach ($request->route()->parameters() as $parameter) {\n            if ($parameter instanceof Model) {\n                visitor()->visit($parameter);\n\n                $logHasSaved = true;\n\n                break;\n            }\n        }\n\n        // create log for normal visits\n        if (!$logHasSaved) {\n            visitor()->visit();\n        }\n\n        return $next($request);\n    }\n}\n"
  },
  {
    "path": "src/Models/Visit.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Models;\n\nuse Illuminate\\Database\\Eloquent\\Model;\n\nclass Visit extends Model\n{\n    public function __construct(array $attributes = [])\n    {\n        if (!isset($this->table)) {\n            $this->setTable(config('visitor.table_name'));\n        }\n        parent::__construct($attributes);\n    }\n    /**\n     * The attributes that aren't mass assignable.\n     *\n     * @var array\n     */\n    protected $fillable = [\n        'method', 'request', 'url', 'referer',\n        'languages', 'useragent', 'headers',\n        'device', 'platform', 'browser', 'ip',\n        'visitor_id', 'visitor_type', 'geo_raw',\n    ];\n\n    /**\n     * The attributes that should be cast to native types.\n     *\n     * @var array\n     */\n    protected $casts = [\n        'request'   => 'array',\n        'languages' => 'array',\n        'headers'   => 'array',\n\t\t'geo_raw' => 'array',\n    ];\n\n    /**\n     * Get the owning visitable model.\n     *\n     * @return \\Illuminate\\Database\\Eloquent\\Relations\\MorphTo\n     */\n    public function visitable()\n    {\n        return $this->morphTo('visitable');\n    }\n\n    /**\n     * Get the owning user model.\n     *\n     * @return \\Illuminate\\Database\\Eloquent\\Relations\\MorphTo\n     */\n    public function visitor()\n    {\n        return $this->morphTo('visitor');\n    }\n}\n"
  },
  {
    "path": "src/Provider/AgentServiceProvider.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Provider;\n\nuse Illuminate\\Support\\ServiceProvider;\nuse Shetabit\\Agent\\Agent;\n\nclass AgentServiceProvider extends ServiceProvider\n{\n    /**\n     * Indicates if loading of the provider is deferred.\n     *\n     * @var bool\n     */\n    protected $defer = true;\n\n    /**\n     * Register the service provider.\n     */\n    public function register()\n    {\n        $this->app->singleton('agent', function ($app) {\n            return new Agent($app['request']->server());\n        });\n\n        $this->app->alias('agent', Agent::class);\n    }\n\n    /**\n     * Get the services provided by the provider.\n     *\n     * @return array\n     */\n    public function provides()\n    {\n        return ['agent', Agent::class];\n    }\n}\n"
  },
  {
    "path": "src/Provider/VisitorServiceProvider.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Provider;\n\nuse Illuminate\\Http\\Request;\nuse Illuminate\\Support\\ServiceProvider;\nuse Shetabit\\Visitor\\Visitor;\n\nclass VisitorServiceProvider extends ServiceProvider\n{\n    /**\n     * Perform post-registration booting of services.\n     *\n     * @return void\n     */\n    public function boot(): void\n    {\n        /**\n         * Configurations that needs to be done by user.\n         */\n        $this->publishes(\n            [\n                __DIR__.'/../../config/visitor.php' => config_path('visitor.php'),\n            ],\n            'config'\n        );\n\n        $timestamp = date('Y_m_d_His', time());\n\n        if (! class_exists('CreateVisitsTable')) {\n            $this->publishes([\n                __DIR__ . '/../../database/migrations/create_visits_table.php.stub' => database_path(\"/migrations/{$timestamp}_create_visits_table.php\"),\n            ], 'migrations');\n        }\n\n        if (! class_exists('AddGeoRawToVisitsTable')) {\n            $this->publishes([\n                __DIR__ . '/../../database/migrations/add_geo_raw_to_visits_table.php.stub' => database_path(\"/migrations/{$timestamp}_add_geo_raw_to_visits_table.php\"),\n            ], 'migrations');\n        }\n\n        $this->registerMacroHelpers();\n    }\n\n    /**\n     * Register any package services.\n     */\n    public function register(): void\n    {\n        /**\n         * Load default configurations.\n         */\n        $this->mergeConfigFrom(__DIR__.'/../../config/visitor.php', 'visitor');\n\n        /**\n         * Bind to service container.\n         */\n        $this->app->singleton('shetabit-visitor', function () {\n            $request = app(Request::class);\n\n            return new Visitor($request, config('visitor'));\n        });\n    }\n\n    /**\n     * Register micros\n     */\n    protected function registerMacroHelpers(): void\n    {\n        Request::macro('visitor', function () {\n            return app('shetabit-visitor');\n        });\n    }\n}\n"
  },
  {
    "path": "src/Resolvers/GeoIp/NullResolver.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Resolvers\\GeoIp;\n\nuse Shetabit\\Visitor\\Contracts\\GeoIpResolver;\n\nclass NullResolver implements GeoIpResolver\n{\n    public function resolve(string $ip): ?array\n    {\n        return null;\n    }\n}\n"
  },
  {
    "path": "src/Resolvers/GeoIp/SteveBaumanResolver.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Resolvers\\GeoIp;\n\nuse Shetabit\\Visitor\\Contracts\\GeoIpResolver;\nuse Stevebauman\\Location\\Facades\\Location;\n\nclass SteveBaumanResolver implements GeoIpResolver\n{\n    public function resolve(string $ip): ?array\n    {\n        $position = Location::get($ip);\n\n        if (!$position) {\n            return null;\n        }\n\n        return [\n            'ip'           => $position->ip,\n            'country_code' => $position->countryCode,\n            'country_name' => $position->countryName,\n            'region_name'  => $position->regionName,\n            'city_name'    => $position->cityName,\n            'latitude'     => $position->latitude,\n            'longitude'    => $position->longitude,\n        ];\n    }\n}\n"
  },
  {
    "path": "src/Traits/CanVisit.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Traits;\n\nuse Illuminate\\Support\\Facades\\Auth;\nuse Shetabit\\Visitor\\Models\\Visit;\nuse Illuminate\\Database\\Eloquent\\Builder;\n\ntrait CanVisit\n{\n    /**\n     * Get all of the post's comments.\n     * @return mixed\n     */\n    public function visitLogs()\n    {\n        return $this->morphMany(Visit::class, 'visitor');\n    }\n\n    /**\n     * Retrieve online users\n     * @param $query\n     * @param int $seconds\n     * @return mixed\n     */\n    public function scopeOnline($query, $seconds = 180)\n    {\n        $time = now()->subSeconds($seconds);\n\n        return $query->whereHas('visitLogs', function ($query) use ($time) {\n            $query->where(config('visitor.table_name') . \".created_at\", '>=', $time->toDateTime());\n        });\n    }\n\n    /**\n     * check if user is online\n     * @param int $seconds\n     * @return bool\n     */\n    public function isOnline($seconds = 180)\n    {\n        $time = now()->subSeconds($seconds);\n\n        return $this->visitLogs()->whereHasMorph('user', [static::class], function ($query) use ($time) {\n                $query\n                    ->where('user_id', $this->id)\n                    ->where(config('visitor.table_name') . \".created_at\", '>=', $time->toDateTime());\n            })->count() > 0;\n    }\n}\n"
  },
  {
    "path": "src/Traits/Visitable.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Traits;\n\nuse Illuminate\\Support\\Facades\\Auth;\nuse Shetabit\\Visitor\\Models\\Visit;\nuse Illuminate\\Database\\Eloquent\\Builder;\nuse Illuminate\\Database\\Eloquent\\Model;\n\ntrait Visitable\n{\n    /**\n     * Get all of the model visit logs.\n     *\n     * @return mixed\n     */\n    public function visitLogs()\n    {\n        return $this->morphMany(Visit::class, 'visitable');\n    }\n\n    /**\n     * Create a visit log.\n     *\n     * @param Model|null $visitor\n     *\n     * @return mixed\n     */\n    public function createVisitLog(?Model $visitor)\n    {\n        return app('shetabit-visitor')->setVisitor($visitor)->visit($this);\n    }\n}\n"
  },
  {
    "path": "src/Traits/Visitor.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Traits;\n\nuse Illuminate\\Support\\Facades\\Auth;\nuse Shetabit\\Visitor\\Models\\Visit;\nuse Illuminate\\Database\\Eloquent\\Builder;\n\ntrait Visitor\n{\n    /**\n     * Get all of the post's comments.\n     * @return mixed\n     */\n    public function visits()\n    {\n        return $this->morphMany(Visit::class, 'visitor');\n    }\n\n    /**\n     * Create a visit log.\n     * @param Model|null $visitable\n     * @return mixed\n     */\n    public function visit(?Model $visitable = NULL)\n    {\n        return app('shetabit-visitor')->setVisitor($this)->visit($visitable);\n    }\n\n    /**\n     * Retrieve online users\n     * @param $query\n     * @param int $seconds\n     * @return mixed\n     */\n    public function scopeOnline($query, $seconds = 180)\n    {\n        $time = now()->subSeconds($seconds);\n\n        $query->whereHas('visits', function ($query) use ($time) {\n            $query->where(config('visitor.table_name') . \".created_at\", '>=', $time->toDateTime());\n\n        });\n    }\n\n    /**\n     * check if user is online\n     * @param int $seconds\n     * @return bool\n     */\n    public function isOnline($seconds = 180)\n    {\n        $time = now()->subSeconds($seconds);\n\n        return $this->visits()->whereHasMorph('visitor', [static::class], function ($query) use ($time) {\n                $query\n                    ->where('visitor_id', $this->id)\n                    ->where(config('visitor.table_name') . \".created_at\", '>=', $time->toDateTime());\n            })->count() > 0;\n    }\n}\n"
  },
  {
    "path": "src/Visitor.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Http\\Request;\nuse Shetabit\\Visitor\\Contracts\\{UserAgentParser,GeoIpResolver};\nuse Shetabit\\Visitor\\Exceptions\\DriverNotFoundException;\nuse Shetabit\\Visitor\\Models\\Visit;\n\nclass Visitor implements UserAgentParser, GeoIpResolver\n{\n    /**\n     * except.\n     *\n     * @var array\n     */\n    protected $except;\n    /**\n     * Configuration.\n     *\n     * @var array\n     */\n    protected $config;\n\n    /**\n     * Driver name.\n     *\n     * @var string\n     */\n    protected $driver;\n\n    /**\n     * Driver instance.\n     *\n     * @var object\n     */\n    protected $driverInstance;\n    \n\t/**\n     * Resolver name.\n     *\n     * @var string\n     */\n    protected $resolver;\n\n    /**\n     * Resolver instance.\n     *\n     * @var object\n     */\n    protected $resolverInstance;\n\n    /**\n     * Request instance.\n     *\n     * @var Request\n     */\n    protected $request;\n\n    /**\n     * Visitor (user) instance.\n     *\n     * @var Model|null\n     */\n    protected $visitor;\n\n    /**\n     * Visitor constructor.\n     *\n     * @param $config\n     *\n     * @throws \\Exception\n     */\n    public function __construct(Request $request, $config)\n    {\n        $this->request = $request;\n        $this->config = $config;\n        $this->except = $config['except'];\n        $this->via($this->config['default'], $this->config['resolver']);\n        $this->setVisitor($request->user());\n    }\n\n    /**\n     * Change the driver and the resolver on the fly.\n     *\n     * @param $driver\n\t * @param $resolver\n     *\n     * @return $this\n     *\n     * @throws \\Exception\n     */\n    public function via($driver, $resolver)\n    {\n        $this->driver = $driver;\n        $this->validateDriver();\n\n\t\t$this->resolver = $resolver;\n\t\t$this->validateResolver();\n\n        return $this;\n    }\n\n    /**\n     * Retrieve request's data\n     *\n     * @return array\n     */\n    public function request() : array\n    {\n        return $this->request->all();\n    }\n\n    /**\n     * Retrieve user's ip.\n     *\n     * @return string|null\n     */\n    public  function ip() : ?string\n    {\n        return $this->request->ip();\n    }\n\n    /**\n     * Retrieve request's url\n     *\n     * @return string\n     */\n    public function url() : string\n    {\n        return $this->request->fullUrl();\n    }\n\n    /**\n     * Retrieve request's referer\n     *\n     * @return string|null\n     */\n    public function referer() : ?string\n    {\n        return $_SERVER['HTTP_REFERER'] ?? null;\n    }\n\n    /**\n     * Retrieve request's method.\n     *\n     * @return string\n     */\n    public function method() : string\n    {\n        return $this->request->getMethod();\n    }\n\n    /**\n     * Retrieve http headers.\n     *\n     * @return array\n     */\n    public function httpHeaders() : array\n    {\n        return $this->request->headers->all();\n    }\n\n    /**\n     * Retrieve agent.\n     *\n     * @return string\n     */\n    public function userAgent() : string\n    {\n        return $this->request->userAgent() ?? '';\n    }\n\n    /**\n     * Retrieve device's name.\n     *\n     * @return string\n     *\n     * @throws \\Exception\n     */\n    public function device() : string\n    {\n        return $this->getDriverInstance()->device();\n    }\n\n    /**\n     * Retrieve platform's name.\n     *\n     * @return string\n     *\n     * @throws \\Exception\n     */\n    public function platform() : string\n    {\n        return $this->getDriverInstance()->platform();\n    }\n\n    /**\n     * Retrieve browser's name.\n     *\n     * @return string\n     *\n     * @throws \\Exception\n     */\n    public function browser() : string\n    {\n        return $this->getDriverInstance()->browser();\n    }\n\n    /**\n     * Retrieve languages.\n     *\n     * @return array\n     *\n     * @throws \\Exception\n     */\n    public function languages() : array\n    {\n        return $this->getDriverInstance()->languages();\n    }\n\n\t/**\n\t* \n\t*/\n\tpublic function resolve(string $ip): ?array\n\t{\n\t\tif(!($this->config['geoip'] ?? false)){\n\t\t\treturn null;\n\t\t}\n\t\treturn $this->getResolverInstance()->resolve($ip);\n\t}\n\n\n\t/**\n\t*\n\t*/\n\tpublic function geolocation(): ?array\n\t{\n\t\t$ip = $this->ip();\n\t\treturn $ip ? $this->resolve($ip) : null;\n\t}\n\n    /**\n     * Set visitor (user)\n     *\n     * @param Model|null $user\n     *\n     * @return $this\n     */\n    public function setVisitor(?Model $user)\n    {\n        $this->visitor = $user;\n\n        return $this;\n    }\n\n    /**\n     * Retrieve visitor (user)\n     *\n     * @return Model|null\n     */\n    public function getVisitor() : ?Model\n    {\n        return $this->visitor;\n    }\n\n    /**\n     * Create a visit log.\n     *\n     * @param Model $model|null\n     */\n    public function visit(?Model $model = null)\n    {\n        foreach ($this->except as $path) {\n            if ($this->request->is($path)) {\n                return;\n            }\n        }\n\n\n        $data = $this->prepareLog();\n\n        if (null !== $model && method_exists($model, 'visitLogs')) {\n            $visit = $model->visitLogs()->create($data);\n        } else {\n            $visit = Visit::create($data);\n        }\n\n        return $visit;\n    }\n\n    /**\n     * Retrieve online visitors.\n     *\n     * @param string $model\n     * @param int $seconds\n     */\n    public function onlineVisitors(string $model, $seconds = 180)\n    {\n        return app($model)->online()->get();\n    }\n\n    /**\n     * Determine if given visitor or current one is online.\n     *\n     * @param Model|null $visitor\n     * @param int $seconds\n     *\n     * @return bool\n     */\n    public function isOnline(?Model $visitor = null, $seconds = 180)\n    {\n        $time = now()->subSeconds($seconds);\n\n        $visitor = $visitor ?? $this->getVisitor();\n\n        if (empty($visitor)) {\n            return false;\n        }\n\n        return Visit::whereHasMorph('visitor', get_class($visitor), function ($query) use ($visitor, $time) {\n            $query->where('visitor_id', $visitor->id);\n        })->whereDate('created_at', '>=', $time)->count() > 0;\n    }\n\n    /**\n     * Prepare log's data.\n     *\n     * @return array\n     *\n     * @throws \\Exception\n     */\n    protected function prepareLog() : array\n    {\n        $log =  [\n            'method' => $this->method(),\n            'request' => $this->request(),\n            'url' => $this->url(),\n            'referer' => $this->referer(),\n            'languages' => $this->languages(),\n            'useragent' => $this->userAgent(),\n            'headers' => $this->httpHeaders(),\n            'device' => $this->device(),\n            'platform' => $this->platform(),\n            'browser' => $this->browser(),\n            'ip' => $this->ip(),\n            'visitor_id' => $this->getVisitor()?->id,\n            'visitor_type' => $this->getVisitor()?->getMorphClass()\n        ];\n\t\t\n\t\tif(!empty($this->config['geoip'])) {\n\t\t\t$log['geo_raw'] = $this->geolocation();\n\t\t}\n\t\t\n\t\treturn $log;\n    }\n\n    /**\n     * Retrieve current driver instance or generate new one.\n     *\n     * @return mixed|object\n     *\n     * @throws \\Exception\n     */\n    protected function getDriverInstance()\n    {\n        if (!empty($this->driverInstance)) {\n            return $this->driverInstance;\n        }\n\n        return $this->getFreshDriverInstance();\n    }\n\n    /**\n     * Get new driver instance\n     *\n     * @return Driver\n     *\n     * @throws \\Exception\n     */\n    protected function getFreshDriverInstance()\n    {\n        $this->validateDriver();\n\n        $driverClass = $this->config['drivers'][$this->driver];\n\n        return app($driverClass);\n    }\n\n    /**\n     * Validate driver.\n     *\n     * @throws \\Exception\n     */\n    protected function validateDriver()\n    {\n        if (empty($this->driver)) {\n            throw new DriverNotFoundException('Driver not selected or default driver does not exist.');\n        }\n\n        $driverClass = $this->config['drivers'][$this->driver];\n\n        if (empty($driverClass) || !class_exists($driverClass)) {\n            throw new DriverNotFoundException('Driver not found in config file. Try updating the package.');\n        }\n\n        $reflect = new \\ReflectionClass($driverClass);\n\n        if (!$reflect->implementsInterface(UserAgentParser::class)) {\n            throw new \\Exception(\"Driver must be an instance of Contracts\\Driver.\");\n        }\n    }\n\n    /**\n     * Retrieve current resolver instance or generate new one.\n     *\n     * @return mixed|object\n     *\n     * @throws \\Exception\n     */\n    protected function getResolverInstance()\n    {\n        if (!empty($this->resolverInstance)) {\n            return $this->resolverInstance;\n        }\n\n        return $this->getFreshResolverInstance();\n    }\n\n    /**\n     * Get new resolver instance\n     *\n     * @return Resolver\n     *\n     * @throws \\Exception\n     */\n    protected function getFreshResolverInstance()\n    {\n        $this->validateResolver();\n\n        $resolverClass = $this->config['resolvers'][$this->resolver];\n\n        return app($resolverClass);\n    }\n\n    /**\n     * Validate resolver.\n     *\n     * @throws \\Exception\n     */\n    protected function validateResolver()\n    {\n        if (empty($this->resolver)) {\n            throw new ResolverNotFoundException('Resolver not selected or default resolver does not exist.');\n        }\n\n        $resolverClass = $this->config['resolvers'][$this->resolver];\n\n        if (empty($resolverClass) || !class_exists($resolverClass)) {\n            throw new ResolverNotFoundException('Resolver not found in config file. Try updating the package.');\n        }\n\n        $reflect = new \\ReflectionClass($resolverClass);\n\n        if (!$reflect->implementsInterface(GeoIpResolver::class)) {\n            throw new \\Exception(\"Resolver must be an instance of Contracts\\Resolver.\");\n        }\n    }\n}\n"
  },
  {
    "path": "src/helpers.php",
    "content": "<?php\nif (!function_exists('visitor')) {\n    /**\n     * Access visitor through helper.\n     *\n     * @return \\Shetabit\\Visitor\\Visitor\n     */\n    function visitor()\n    {\n        return app('shetabit-visitor');\n    }\n}\n"
  },
  {
    "path": "tests/TestCase.php",
    "content": "<?php\n\nnamespace Shetabit\\Visitor\\Tests;\n\nuse Orchestra\\Testbench\\TestCase as BaseTestCase;\nuse Shetabit\\Visitor\\Tests\\Mocks\\Drivers\\BarDriver;\n\nclass TestCase extends BaseTestCase\n{\n    protected function getPackageProviders($app)\n    {\n        return ['Shetabit\\Visitor\\Provider\\VisitorServiceProvider'];\n    }\n\n    protected function getPackageAliases($app)\n    {\n        return [\n            'Visitor' => 'Shetabit\\Visitor\\Facade\\Visitor',\n        ];\n    }\n}\n"
  }
]