Merge pull request #4380 from Ombi-app/develop

Develop to Master
pull/4382/head
Jamie 3 years ago committed by GitHub
commit d1d4a7bcf6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -1,118 +0,0 @@
variables:
- template: templates/variables.yml
stages:
- stage: build
jobs:
- job: Build
pool:
vmImage: ${{ variables.vmImage }}
steps:
- template: templates/build-steps.yml
- stage: publish
jobs:
- job:
strategy:
matrix:
win10-x64:
runtime: win10-x64
format: zip
compression: zip
win10-x86:
runtime: win10-x86
format: zip
compression: zip
osx-x64:
runtime: osx-x64
format: tar.gz
compression: tar
linux-x64:
runtime: linux-x64
format: tar.gz
compression: tar
linux-arm:
runtime: linux-arm
format: tar.gz
compression: tar
linux-arm64:
runtime: linux-arm64
format: tar.gz
compression: tar
pool:
vmImage: ${{ variables.vmImage }}
steps:
- template: templates/publish-os-steps.yml
- stage: deploy
jobs:
- job:
condition: and(succeeded(), eq(variables.isMain, true))
steps:
- task: DownloadPipelineArtifact@2
inputs:
buildType: 'current'
targetPath: '$(System.ArtifactsDirectory)'
- task: PowerShell@2
displayName: 'Get Release Notes'
inputs:
targetType: 'inline'
script: |
$response = Invoke-WebRequest -Uri "https://ombireleasenote.azurewebsites.net/api/ReleaseNotesFunction?buildId=$(Build.BuildId)"
Write-Host "##vso[task.setvariable variable=ReleaseNotes;]$response"
- task: GitHubRelease@1
displayName: 'Ombi.Releases Release'
inputs:
gitHubConnection: 'PAT'
repositoryName: 'Ombi-app/Ombi.Releases'
action: 'create'
target: 'c7fcbb77b58aef1076d635a9ef99e4374abc8672'
tagSource: 'userSpecifiedTag'
tag: '$(gitTag)'
releaseNotesSource: 'inline'
releaseNotesInline: '$(ReleaseNotes)'
assets: |
$(System.ArtifactsDirectory)/**/*.zip
$(System.ArtifactsDirectory)/**/*.tar.gz
isPreRelease: true
changeLogCompareToRelease: 'lastNonDraftRelease'
changeLogType: 'commitBased'
- task: GitHubRelease@1
displayName: 'Ombi Release'
inputs:
gitHubConnection: 'PAT'
repositoryName: 'Ombi-app/Ombi'
action: 'create'
target: '$(Build.SourceVersion)'
tagSource: 'userSpecifiedTag'
tag: '$(gitTag)'
releaseNotesSource: 'inline'
releaseNotesInline: '$(ReleaseNotes)'
assets: |
$(System.ArtifactsDirectory)/**/*.zip
$(System.ArtifactsDirectory)/**/*.tar.gz
isPreRelease: true
changeLogCompareToRelease: 'lastNonDraftRelease'
changeLogType: 'commitBased'
- task: PowerShell@2
displayName: "Trigger APT build"
inputs:
targetType: 'inline'
script: |
$body = @{
"ref"="main"
"inputs"= @{"version"= "$(gitTag)"}
} | ConvertTo-Json
$header = @{
"Accept"="application/vnd.github.v3+json"
"Authorization"="Bearer $(APTPAT)"
"User-Agent"="Ombi"
}
Invoke-RestMethod -Uri "https://api.github.com/repos/Ombi-app/Ombi.Apt/actions/workflows/build-deb.yml/dispatches" -Method 'Post' -Body $body -Headers $header

@ -1,34 +0,0 @@
steps:
## This is needed due to https://github.com/microsoft/azure-pipelines-tasks/issues/8429
## For the set version tool...
- task: DotNetCoreInstaller@1
displayName: 'Use .NET Core sdk '
inputs:
packageType: 'sdk'
version: '5.x'
- task: Yarn@3
displayName: 'Install UI Dependancies'
inputs:
projectDirectory: '$(UiLocation)'
arguments: 'install'
- task: Yarn@3
displayName: 'Build and Publish Angular App'
inputs:
projectDirectory: '$(UiLocation)'
arguments: 'run build'
- task: PublishPipelineArtifact@1
inputs:
targetPath: '$(UiLocation)dist'
artifact: 'angular_dist'
publishLocation: 'pipeline'
- task: DotNetCoreCLI@2
displayName: Run Unit Tests
inputs:
command: 'custom'
projects: '$(TestProject)'
custom: 'test'
continueOnError: false

@ -1,57 +0,0 @@
steps:
- task: DotNetCoreInstaller@1
displayName: 'Use .NET Core sdk '
inputs:
packageType: 'sdk'
version: '5.x'
- task: DotNetCoreInstaller@1
displayName: 'Use .NET Core sdk for versioning'
inputs:
packageType: 'sdk'
version: '3.1.x'
- task: PowerShell@2
displayName: 'Set Version'
inputs:
targetType: 'inline'
script: |
dotnet tool install -g dotnet-setversion
setversion -r $(BuildVersion)
- task: DotNetCoreCLI@2
displayName: 'publish $(runtime)'
inputs:
command: 'publish'
publishWebProjects: true
arguments: '-c $(BuildConfiguration) -r "$(runtime)" -o $(Build.ArtifactStagingDirectory)/$(runtime) --self-contained true -p:PublishSingleFile=true'
zipAfterPublish: false
modifyOutputPath: false
- task: DownloadPipelineArtifact@2
inputs:
buildType: 'current'
artifactName: 'angular_dist'
targetPath: '$(Build.ArtifactStagingDirectory)/angular_dist'
- task: CopyFiles@2
displayName: 'Copy Angular App $(runtime)'
inputs:
SourceFolder: '$(Build.ArtifactStagingDirectory)/angular_dist'
Contents: '**'
TargetFolder: '$(Build.ArtifactStagingDirectory)/$(runtime)/ClientApp/dist'
- task: ArchiveFiles@2
displayName: 'Zip $(runtime)'
inputs:
rootFolderOrFile: '$(Build.ArtifactStagingDirectory)/$(runtime)'
includeRootFolder: false
archiveType: $(compression)
archiveFile: '$(Build.ArtifactStagingDirectory)/$(runtime).$(format)'
replaceExistingArchive: true
- task: PublishPipelineArtifact@1
inputs:
targetPath: '$(Build.ArtifactStagingDirectory)/$(runtime).$(format)'
artifact: '$(runtime)'
publishLocation: 'pipeline'

@ -1,30 +0,0 @@
variables:
- name: "BuildConfiguration"
value: "Release"
- name: "vmImage"
value: "ubuntu-latest"
- name: "Solution"
value: "**/*.sln"
- name: "TestProject"
value: "**/*.Tests.csproj"
- name: "NetCoreVersion"
value: "5.0"
- name: "PublishLocation"
value: "$(Build.SourcesDirectory)/src/Ombi/bin/Release/netcoreapp$(NetCoreVersion)"
- name: "GitTag"
value: "v$(buildVersion)"
- name: "UiLocation"
value: "$(Build.SourcesDirectory)/src/Ombi/ClientApp/"
- name: "BuildVersion"
value: "4.0.$(Build.BuildId)"
- name: isMain
value: $[or(eq(variables['Build.SourceBranch'], 'refs/heads/develop'), eq(variables['Build.SourceBranch'], 'refs/heads/master'))]

@ -1,293 +0,0 @@
# -*- coding: utf-8; mode: python -*-
##
## Format
##
## ACTION: [AUDIENCE:] COMMIT_MSG [!TAG ...]
##
## Description
##
## ACTION is one of 'chg', 'fix', 'new'
##
## Is WHAT the change is about.
##
## 'chg' is for refactor, small improvement, cosmetic changes...
## 'fix' is for bug fixes
## 'new' is for new features, big improvement
##
## AUDIENCE is optional and one of 'dev', 'usr', 'pkg', 'test', 'doc'
##
## Is WHO is concerned by the change.
##
## 'dev' is for developpers (API changes, refactors...)
## 'usr' is for final users (UI changes)
## 'pkg' is for packagers (packaging changes)
## 'test' is for testers (test only related changes)
## 'doc' is for doc guys (doc only changes)
##
## COMMIT_MSG is ... well ... the commit message itself.
##
## TAGs are additionnal adjective as 'refactor' 'minor' 'cosmetic'
##
## They are preceded with a '!' or a '@' (prefer the former, as the
## latter is wrongly interpreted in github.) Commonly used tags are:
##
## 'refactor' is obviously for refactoring code only
## 'minor' is for a very meaningless change (a typo, adding a comment)
## 'cosmetic' is for cosmetic driven change (re-indentation, 80-col...)
## 'wip' is for partial functionality but complete subfunctionality.
##
## Example:
##
## new: usr: support of bazaar implemented
## chg: re-indentend some lines !cosmetic
## new: dev: updated code to be compatible with last version of killer lib.
## fix: pkg: updated year of licence coverage.
## new: test: added a bunch of test around user usability of feature X.
## fix: typo in spelling my name in comment. !minor
##
## Please note that multi-line commit message are supported, and only the
## first line will be considered as the "summary" of the commit message. So
## tags, and other rules only applies to the summary. The body of the commit
## message will be displayed in the changelog without reformatting.
##
## ``ignore_regexps`` is a line of regexps
##
## Any commit having its full commit message matching any regexp listed here
## will be ignored and won't be reported in the changelog.
##
ignore_regexps = [
r'@minor', r'!minor',
r'@cosmetic', r'!cosmetic',
r'@refactor', r'!refactor',
r'@wip', r'!wip',
r'^([cC]hg|[fF]ix|[nN]ew)\s*:\s*[p|P]kg:',
r'^([cC]hg|[fF]ix|[nN]ew)\s*:\s*[d|D]ev:',
r'^(.{3,3}\s*:)?\s*[fF]irst commit.?\s*$',
r'^$', ## ignore commits with empty messages
]
## ``section_regexps`` is a list of 2-tuples associating a string label and a
## list of regexp
##
## Commit messages will be classified in sections thanks to this. Section
## titles are the label, and a commit is classified under this section if any
## of the regexps associated is matching.
##
## Please note that ``section_regexps`` will only classify commits and won't
## make any changes to the contents. So you'll probably want to go check
## ``subject_process`` (or ``body_process``) to do some changes to the subject,
## whenever you are tweaking this variable.
##
section_regexps = [
('**New Features**', [
r'^[aA]dded?\s*:?\s*((dev|use?r|pkg|test|doc)\s*:\s*)?([^\n]*)$',
r'^[uU]pdated?\s*:?\s*((dev|use?r|pkg|test|doc)\s*:\s*)?([^\n]*)$',
r'^[cC]hanged?\s*:?\s*((dev|use?r|pkg|test|doc)\s*:\s*)?([^\n]*)$',
]),
('**Fixes**', [
r'^(?![mM]erge\s*)'
]
),
]
## ``body_process`` is a callable
##
## This callable will be given the original body and result will
## be used in the changelog.
##
## Available constructs are:
##
## - any python callable that take one txt argument and return txt argument.
##
## - ReSub(pattern, replacement): will apply regexp substitution.
##
## - Indent(chars=" "): will indent the text with the prefix
## Please remember that template engines gets also to modify the text and
## will usually indent themselves the text if needed.
##
## - Wrap(regexp=r"\n\n"): re-wrap text in separate paragraph to fill 80-Columns
##
## - noop: do nothing
##
## - ucfirst: ensure the first letter is uppercase.
## (usually used in the ``subject_process`` pipeline)
##
## - final_dot: ensure text finishes with a dot
## (usually used in the ``subject_process`` pipeline)
##
## - strip: remove any spaces before or after the content of the string
##
## - SetIfEmpty(msg="No commit message."): will set the text to
## whatever given ``msg`` if the current text is empty.
##
## Additionally, you can `pipe` the provided filters, for instance:
#body_process = Wrap(regexp=r'\n(?=\w+\s*:)') | Indent(chars=" ")
#body_process = Wrap(regexp=r'\n(?=\w+\s*:)')
#body_process = noop
body_process = ReSub(r'((^|\n)[A-Z]\w+(-\w+)*: .*(\n\s+.*)*)+$', r'') | strip
## ``subject_process`` is a callable
##
## This callable will be given the original subject and result will
## be used in the changelog.
##
## Available constructs are those listed in ``body_process`` doc.
subject_process = (strip |
ReSub(r'^([cC]hanged|[fF]ixed|[aA]dded|[uU]pdated)\s*:\s*((dev|use?r|pkg|test|doc)\s*:\s*)?([^\n@]*)(@[a-z]+\s+)*$', r'\4') |
SetIfEmpty("No commit message.") | ucfirst | final_dot)
## ``tag_filter_regexp`` is a regexp
##
## Tags that will be used for the changelog must match this regexp.
##
tag_filter_regexp = r'^v[0-9]+\.[0-9]+(\.[0-9]+)?$'
## ``unreleased_version_label`` is a string or a callable that outputs a string
##
## This label will be used as the changelog Title of the last set of changes
## between last valid tag and HEAD if any.
unreleased_version_label = "(unreleased)"
## ``output_engine`` is a callable
##
## This will change the output format of the generated changelog file
##
## Available choices are:
##
## - rest_py
##
## Legacy pure python engine, outputs ReSTructured text.
## This is the default.
##
## - mustache(<template_name>)
##
## Template name could be any of the available templates in
## ``templates/mustache/*.tpl``.
## Requires python package ``pystache``.
## Examples:
## - mustache("markdown")
## - mustache("restructuredtext")
##
## - makotemplate(<template_name>)
##
## Template name could be any of the available templates in
## ``templates/mako/*.tpl``.
## Requires python package ``mako``.
## Examples:
## - makotemplate("restructuredtext")
##
#output_engine = rest_py
#output_engine = mustache("restructuredtext")
output_engine = mustache("changelog.tpl")
#output_engine = makotemplate("restructuredtext")
## ``include_merge`` is a boolean
##
## This option tells git-log whether to include merge commits in the log.
## The default is to include them.
include_merge = False
## ``log_encoding`` is a string identifier
##
## This option tells gitchangelog what encoding is outputed by ``git log``.
## The default is to be clever about it: it checks ``git config`` for
## ``i18n.logOutputEncoding``, and if not found will default to git's own
## default: ``utf-8``.
#log_encoding = 'utf-8'
## ``publish`` is a callable
##
## Sets what ``gitchangelog`` should do with the output generated by
## the output engine. ``publish`` is a callable taking one argument
## that is an interator on lines from the output engine.
##
## Some helper callable are provided:
##
## Available choices are:
##
## - stdout
##
## Outputs directly to standard output
## (This is the default)
##
## - FileInsertAtFirstRegexMatch(file, pattern, idx=lamda m: m.start())
##
## Creates a callable that will parse given file for the given
## regex pattern and will insert the output in the file.
## ``idx`` is a callable that receive the matching object and
## must return a integer index point where to insert the
## the output in the file. Default is to return the position of
## the start of the matched string.
##
## - FileRegexSubst(file, pattern, replace, flags)
##
## Apply a replace inplace in the given file. Your regex pattern must
## take care of everything and might be more complex. Check the README
## for a complete copy-pastable example.
##
# publish = FileInsertIntoFirstRegexMatch(
# "CHANGELOG.rst",
# r'/(?P<rev>[0-9]+\.[0-9]+(\.[0-9]+)?)\s+\([0-9]+-[0-9]{2}-[0-9]{2}\)\n--+\n/',
# idx=lambda m: m.start(1)
# )
#publish = stdout
def write_to_file(content):
with open("CHANGELOG.md", "w+") as f:
for chunk in content:
f.write(chunk)
publish = write_to_file
## ``revs`` is a list of callable or a list of string
##
## callable will be called to resolve as strings and allow dynamical
## computation of these. The result will be used as revisions for
## gitchangelog (as if directly stated on the command line). This allows
## to filter exaclty which commits will be read by gitchangelog.
##
## To get a full documentation on the format of these strings, please
## refer to the ``git rev-list`` arguments. There are many examples.
##
## Using callables is especially useful, for instance, if you
## are using gitchangelog to generate incrementally your changelog.
##
## Some helpers are provided, you can use them::
##
## - FileFirstRegexMatch(file, pattern): will return a callable that will
## return the first string match for the given pattern in the given file.
## If you use named sub-patterns in your regex pattern, it'll output only
## the string matching the regex pattern named "rev".
##
## - Caret(rev): will return the rev prefixed by a "^", which is a
## way to remove the given revision and all its ancestor.
##
## Please note that if you provide a rev-list on the command line, it'll
## replace this value (which will then be ignored).
##
## If empty, then ``gitchangelog`` will act as it had to generate a full
## changelog.
##
## The default is to use all commits to make the changelog.
#revs = ["^1.0.3", ]
#revs = [
# Caret(
# FileFirstRegexMatch(
# "CHANGELOG.rst",
# r"(?P<rev>[0-9]+\.[0-9]+(\.[0-9]+)?)\s+\([0-9]+-[0-9]{2}-[0-9]{2}\)\n--+\n")),
# "HEAD"
#]
revs = []

@ -3,3 +3,5 @@ automation: tests/**/*
frontend: src/Ombi/ClientApp/**/*
backend: src/**/*.cs
devops: .github/workflows/*

@ -0,0 +1,205 @@
name: CI Build
on:
push:
branches: [ develop, master ]
jobs:
build-ui:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '14'
- name: NodeModules Cache
uses: actions/cache@v2
with:
path: '**/node_modules'
key: node_modules-${{ hashFiles('**/yarn.lock') }}
- name: UI Install
run: yarn --cwd ./src/Ombi/ClientApp install
- name: Build UI
run: yarn --cwd ./src/Ombi/ClientApp run build
- name: Publish UI Artifacts
uses: actions/upload-artifact@v2
with:
name: angular_dist
path: |
./src/Ombi/ClientApp/dist
unit-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-dotnet@v1
with:
dotnet-version: '5.0.x'
- name: Nuget Cache
uses: actions/cache@v2
with:
path: ~/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
restore-keys: |
${{ runner.os }}-nuget
- name: Run Unit Tests
run: |
cd src
dotnet test -c NonUiBuild --logger trx --results-directory "TestResults"
versioning:
runs-on: ubuntu-latest
needs: [ build-ui, unit-test ]
outputs:
changelog: ${{ steps.changelog.outputs.clean_changelog }}
tag: ${{ steps.changelog.outputs.tag }}
version: ${{ steps.changelog.outputs.version }}
steps:
- uses: actions/checkout@v2
- name: Conventional Changelog Action
id: changelog
uses: TriPSs/conventional-changelog-action@v3
with:
version-file: 'version.json'
skip-on-empty: 'false'
git-message: 'chore(release): :rocket: {version}'
- name: Output version
run: |
echo "outputs: ${{ steps.changelog.outputs.tag }}"
echo "Version: ${{ steps.changelog.outputs.version }}"
echo "log: ${{ steps.changelog.outputs.clean_changelog }}"
publish:
runs-on: ubuntu-latest
needs: [ build-ui, versioning ]
strategy:
matrix:
include:
- os: win10-x64
format: zip
compression: zip
- os: win10-x86
format: zip
compression: zip
- os: linux-x64
format: tar.gz
compression: tar
- os: linux-arm
format: tar.gz
compression: tar
- os: linux-arm64
compression: tar
format: tar.gz
- os: osx-x64
compression: tar
format: tar.gz
steps:
- uses: actions/checkout@v2
- name: Nuget Cache
uses: actions/cache@v2
with:
path: ~/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
restore-keys: |
${{ runner.os }}-nuget
- name: Set Backend Version
run: |
dotnet tool install -g dotnet-setversion
setversion -r ${{ needs.versioning.outputs.version }}
working-directory: src
- name: Publish Backend ${{ matrix.os }}
run: dotnet publish -c Release -r ${{ matrix.os }} -o "${{ matrix.os }}" --self-contained true -p:PublishSingleFile=true
working-directory: src/Ombi
- name: Download Angular
uses: actions/download-artifact@v2
with:
name: angular_dist
path: ~/src/Ombi/dist
- name: Copy Dist to Artifacts
run: |
cd ${{ matrix.os }}
sudo mkdir -p ClientApp/dist
echo "mkdir /ClientApp"
echo "list os (ClientApp should be here)"
ls
cd ..
echo "Copy dist to /ClientApp"
sudo mv ~/src/Ombi/dist/* ${{ matrix.os }}/ClientApp/dist
working-directory: src/Ombi
- name: Archive Release
uses: thedoctor0/zip-release@master
with:
type: '${{ matrix.compression }}'
filename: '../${{ matrix.os }}.${{ matrix.format }}'
path: '.'
directory: 'src/Ombi/${{ matrix.os }}'
- name: Publish Release
uses: actions/upload-artifact@v2
with:
name: ${{ matrix.os }}
path: |
./src/Ombi/${{ matrix.os }}.${{ matrix.format }}
release:
needs: [ publish, unit-test, versioning ]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Download Artifacts
id: download
uses: actions/download-artifact@v2
with:
path: artifacts
- name: Publish to GitHub Master
uses: softprops/action-gh-release@v1
if: contains(github.ref, 'master')
with:
body: ${{ needs.versioning.outputs.changelog }}
name: ${{ needs.versioning.outputs.tag }}
tag_name: ${{ needs.versioning.outputs.tag }}
files: |
artifacts/**/*.tar.gz
artifacts/**/*.zip
- name: Publish to GitHub Develop
uses: softprops/action-gh-release@v1
if: contains(github.ref, 'develop')
with:
prerelease: true
body: ${{ needs.versioning.outputs.changelog }}
name: ${{ needs.versioning.outputs.tag }}
tag_name: ${{ needs.versioning.outputs.tag }}
files: |
artifacts/**/*.tar.gz
artifacts/**/*.zip
update-apt:
needs: [ release, versioning ]
runs-on: ubuntu-latest
steps:
- name: Trigger APT Build
uses: fjogeleit/http-request-action@master
with:
url: 'https://api.github.com/repos/Ombi-app/Ombi.Apt/actions/workflows/build-deb.yml/dispatches'
method: 'POST'
contentType: 'application/json'
data: '{ "ref":"main", "inputs": { "version": "${{ needs.versioning.outputs.tag }}"} }'
customHeaders: '{"Accept":"application/vnd.github.v3+json", "Authorization":"Bearer ${{secrets.APT_PAT}}", "User-Agent":"Ombi"}'

@ -17,8 +17,6 @@ on:
pull_request:
# The branches below must be a subset of the branches above
branches: [ develop ]
schedule:
- cron: '40 3 * * 4'
jobs:
analyze:

@ -0,0 +1,20 @@
name: Contributors
on:
push:
branches: [ develop ]
workflow_dispatch:
jobs:
update-contributors:
runs-on: ubuntu-latest
steps:
- name: Contribute List
uses: akhilmhdh/contributors-readme-action@v2.2.1
with:
commit_message: "chore: :busts_in_silhouette: Updated Contributors [skip ci]"
image_size: 50
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

@ -0,0 +1,35 @@
name: 'Issue Check'
on:
issues:
types: [opened]
jobs:
issueCheck:
runs-on: ubuntu-latest
steps:
- name: Output version
run: |
echo "log: ${{ github.event.issue.body }}"
- if: startsWith(github.event.issue.body , '**Describe the bug**') == false
name: Close Issue
uses: peter-evans/close-issue@v1
with:
comment: |
Hello, Please use the Github template to report an issue. If this is a feature request, please take a look at the readme. <br/> Thanks, <br/> Ombi Bot
- if: startsWith(github.event.issue.body , '**Describe the bug**') == true
name: Create comment
uses: peter-evans/create-or-update-comment@v1
with:
issue-number: ${{ github.event.issue.number }}
body: |
Hi!
<br/>Thanks for the issue report. Before a real human comes by, please make sure you used our bug report format.
<br/>Have you looked at the wiki yet? https://docs.ombi.app/
<br/>Before posting make sure you also read our [FAQ](https://docs.ombi.app/info/faq/).
<br/> Make the title describe your issue. Having 'not working' or 'I get this bug' for 100 issues, isn't really helpful.
<br/> If we need more information or there is some progress we tag the issue or update the tag and keep you updated.
<br/> Thanks!
<br/> Ombi Bot.

@ -0,0 +1,106 @@
name: PR Build
on:
pull_request:
types: [opened, synchronize, reopened]
jobs:
build-ui:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: '14'
- name: NodeModules Cache
uses: actions/cache@v2
with:
path: '**/node_modules'
key: node_modules-${{ hashFiles('**/yarn.lock') }}
- name: UI Install
run: yarn --cwd ./src/Ombi/ClientApp install
- name: Build UI
run: yarn --cwd ./src/Ombi/ClientApp run build
unit-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-dotnet@v1
with:
dotnet-version: '5.0.x'
- name: Nuget Cache
uses: actions/cache@v2
with:
path: ~/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
restore-keys: |
${{ runner.os }}-nuget
- name: Run Unit Tests
run: |
cd src
dotnet test --logger trx --results-directory "TestResults"
analysis:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
# Disabling shallow clone is recommended for improving relevancy of reporting
fetch-depth: 0
- name: SonarCloud Scan
uses: sonarsource/sonarcloud-github-action@master
with:
args: >
-Dsonar.organization=ombi-app
-Dsonar.projectKey=Ombi-app_Ombi
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
publish:
runs-on: ubuntu-latest
needs: [ unit-test ]
strategy:
matrix:
include:
- os: win10-x64
format: zip
compression: zip
- os: win10-x86
format: zip
compression: zip
- os: linux-x64
format: tar.gz
compression: tar
- os: linux-arm
format: tar.gz
compression: tar
- os: linux-arm64
compression: tar
format: tar.gz
- os: osx-x64
compression: tar
format: tar.gz
steps:
- uses: actions/checkout@v2
- name: Nuget Cache
uses: actions/cache@v2
with:
path: ~/.nuget/packages
key: ${{ runner.os }}-nuget-${{ hashFiles('**/packages.lock.json') }}
restore-keys: |
${{ runner.os }}-nuget
- name: Publish Backend ${{ matrix.os }}
run: dotnet publish -c Release -r ${{ matrix.os }} -o "${{ matrix.os }}" --self-contained true -p:PublishSingleFile=true
working-directory: src/Ombi

@ -0,0 +1,50 @@
name: Sonar Scanner
on:
workflow_dispatch:
jobs:
sonarcloud:
name: SonarCloud
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
with:
# Shallow clones should be disabled for a better relevancy of analysis
fetch-depth: 0
# Speed-up analysis by caching the scanner workspace
- name: Cache SonarCloud workspace
uses: actions/cache@v1
with:
path: ~\.sonar\cache
key: ${{ runner.os }}-sonar-cache
restore-keys: ${{ runner.os }}-sonar-cache
# Speed-up analysis by caching the scanner installation
- name: Cache SonarCloud scanner
id: cache-sonar-scanner
uses: actions/cache@v1
with:
path: .\.sonar\scanner
key: ${{ runner.os }}-sonar-scanner
restore-keys: ${{ runner.os }}-sonar-scanner
- name: Install SonarCloud scanner
if: steps.cache-sonar-scanner.outputs.cache-hit != 'true'
shell: powershell
# The --version argument is optional. If it is omitted the latest version will be installed.
run: |
New-Item -Path .\.sonar\scanner -ItemType Directory
dotnet tool update dotnet-sonarscanner --tool-path .\.sonar\scanner --version 4.8.0
- name: Build
shell: powershell
env:
# Needed to get some information about the pull request, if any
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# The secret referenced in the command-line by SONAR_TOKEN should be generated
# from https://sonarcloud.io/account/security/
# The organization and project arguments (see /o and /k) are displayed
# on the project dashboard in SonarCloud.
run: |
.\.sonar\scanner\dotnet-sonarscanner begin /k:"Ombi-app_Ombi" /o:"ombi-app" /d:sonar.login="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io"
dotnet build src/Ombi.sln -c NonUiBuild
.\.sonar\scanner\dotnet-sonarscanner end /d:sonar.login="${{ secrets.SONAR_TOKEN }}"

1
.gitignore vendored

@ -20,6 +20,7 @@ x86/
bld/
[Bb]in/
[Oo]bj/
.sonarqube/
# Visual Studio 2015 cache/options directory
.vs/

File diff suppressed because it is too large Load Diff

@ -2,45 +2,127 @@
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
Examples of behavior that contributes to a positive environment for our
community include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior by participants include:
Examples of unacceptable behavior include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
## Enforcement Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at tidusjar@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
tidusjar@gmail.com.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

@ -1 +0,0 @@
next-version: 3.0.0

@ -18,8 +18,8 @@ Don't worry, it's grandma friendly, and more importantly; has wife approval cert
| Service | Stable | Develop
|----------|:---------------------------:|:----------------------------:|
| Build Status | [![Build status](https://ci.appveyor.com/api/projects/status/hgj8j6lcea7j0yhn/branch/master?svg=true)](https://ci.appveyor.com/project/tidusjar/requestplex/branch/master) | [![Build Status](https://dev.azure.com/tidusjar/Ombi/_apis/build/status/Ombi%20CI?repoName=Ombi-app%2FOmbi&branchName=develop)](https://dev.azure.com/tidusjar/Ombi/_build/latest?definitionId=18&repoName=Ombi-app%2FOmbi&branchName=develop) | [![Build Status](https://dev.azure.com/tidusjar/Ombi/_apis/build/status/Ombi%20CI?branchName=feature%2Fv4)](https://dev.azure.com/tidusjar/Ombi/_build/latest?definitionId=18&branchName=feature%2Fv4)
| Download |[![Download](http://i.imgur.com/odToka3.png)](https://github.com/Ombi-app/Ombi/releases) | [![Download](http://i.imgur.com/odToka3.png)](https://ci.appveyor.com/project/tidusjar/requestplex/branch/develop/artifacts) | [![Download](http://i.imgur.com/odToka3.png)](https://github.com/ombi-app/ombi/releases) |
| Build Status | [![CI Build](https://github.com/Ombi-app/Ombi/actions/workflows/build.yml/badge.svg?branch=master)](https://github.com/Ombi-app/Ombi/actions/workflows/build.yml) | [![CI Build](https://github.com/Ombi-app/Ombi/actions/workflows/build.yml/badge.svg)](https://github.com/Ombi-app/Ombi/actions/workflows/build.yml) | [![Build Status](https://dev.azure.com/tidusjar/Ombi/_apis/build/status/Ombi%20CI?branchName=feature%2Fv4)](https://dev.azure.com/tidusjar/Ombi/_build/latest?definitionId=18&branchName=feature%2Fv4)
| Download |[![Download](https://img.shields.io/badge/-Download-blue)](https://github.com/Ombi-app/Ombi/releases) | [![Download](https://img.shields.io/badge/-Download-blue)](https://ci.appveyor.com/project/tidusjar/requestplex/branch/develop/artifacts) | [![Download](https://img.shields.io/badge/-Download-blue)](https://github.com/ombi-app/ombi/releases) |
# Feature Requests
Feature requests are handled on Feature Upvote.
@ -68,9 +68,706 @@ Here are some of the features Ombi has:
# Contributors
We are looking for any contributions to the project! Just pick up a task, if you have any questions ask and i'll get straight on it!
Please feel free to submit a pull request!
<!-- readme: collaborators,contributors -start -->
<table>
<tr>
<td align="center">
<a href="https://github.com/tidusjar">
<img src="https://avatars.githubusercontent.com/u/6642220?v=4" width="50;" alt="tidusjar"/>
<br />
<sub><b>Jamie</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Roxedus">
<img src="https://avatars.githubusercontent.com/u/7110194?v=4" width="50;" alt="Roxedus"/>
<br />
<sub><b>Roxedus</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/twanariens">
<img src="https://avatars.githubusercontent.com/u/34845004?v=4" width="50;" alt="twanariens"/>
<br />
<sub><b>Twan Ariens</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Drewster727">
<img src="https://avatars.githubusercontent.com/u/4528753?v=4" width="50;" alt="Drewster727"/>
<br />
<sub><b>Drew</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/anojht">
<img src="https://avatars.githubusercontent.com/u/21053678?v=4" width="50;" alt="anojht"/>
<br />
<sub><b>Anojh Thayaparan</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Magikarplvl4">
<img src="https://avatars.githubusercontent.com/u/2944704?v=4" width="50;" alt="Magikarplvl4"/>
<br />
<sub><b>Magikarp Lvl 4</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/MrTopCat">
<img src="https://avatars.githubusercontent.com/u/774415?v=4" width="50;" alt="MrTopCat"/>
<br />
<sub><b>James Carty</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/smcpeck">
<img src="https://avatars.githubusercontent.com/u/8724583?v=4" width="50;" alt="smcpeck"/>
<br />
<sub><b>Shaun McPeck</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/MattJeanes">
<img src="https://avatars.githubusercontent.com/u/2363642?v=4" width="50;" alt="MattJeanes"/>
<br />
<sub><b>Matt Jeanes</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/bernarden">
<img src="https://avatars.githubusercontent.com/u/12289537?v=4" width="50;" alt="bernarden"/>
<br />
<sub><b>Victor Usoltsev</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/dhruvb14">
<img src="https://avatars.githubusercontent.com/u/4459649?v=4" width="50;" alt="dhruvb14"/>
<br />
<sub><b>Dhruv Bhavsar</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/joshuaboniface">
<img src="https://avatars.githubusercontent.com/u/4031396?v=4" width="50;" alt="joshuaboniface"/>
<br />
<sub><b>Joshua M. Boniface</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/bruvv">
<img src="https://avatars.githubusercontent.com/u/3063928?v=4" width="50;" alt="bruvv"/>
<br />
<sub><b>Bruvv</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/sephrat">
<img src="https://avatars.githubusercontent.com/u/34862846?v=4" width="50;" alt="sephrat"/>
<br />
<sub><b>Sephrat</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/louis-lau">
<img src="https://avatars.githubusercontent.com/u/1346804?v=4" width="50;" alt="louis-lau"/>
<br />
<sub><b>Louis Laureys</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Berserkir-Wolf">
<img src="https://avatars.githubusercontent.com/u/15743201?v=4" width="50;" alt="Berserkir-Wolf"/>
<br />
<sub><b>Dyson Parkes</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/goldenpipes">
<img src="https://avatars.githubusercontent.com/u/6140137?v=4" width="50;" alt="goldenpipes"/>
<br />
<sub><b>Goldenpipes</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Namaneo">
<img src="https://avatars.githubusercontent.com/u/6706489?v=4" width="50;" alt="Namaneo"/>
<br />
<sub><b>Julien Loir</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/ProtoJazz">
<img src="https://avatars.githubusercontent.com/u/1490293?v=4" width="50;" alt="ProtoJazz"/>
<br />
<sub><b>Jim MacKenize</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Unimatrix0">
<img src="https://avatars.githubusercontent.com/u/357984?v=4" width="50;" alt="Unimatrix0"/>
<br />
<sub><b>Avi</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/kitzin">
<img src="https://avatars.githubusercontent.com/u/3277321?v=4" width="50;" alt="kitzin"/>
<br />
<sub><b>Emil Kitti</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/stefangross">
<img src="https://avatars.githubusercontent.com/u/8499989?v=4" width="50;" alt="stefangross"/>
<br />
<sub><b>Stefangross</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/shiitake">
<img src="https://avatars.githubusercontent.com/u/161589?v=4" width="50;" alt="shiitake"/>
<br />
<sub><b>Shannon Barrett</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/gtbuchanan">
<img src="https://avatars.githubusercontent.com/u/715687?v=4" width="50;" alt="gtbuchanan"/>
<br />
<sub><b>Taylor Buchanan</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/Patricol">
<img src="https://avatars.githubusercontent.com/u/13428020?v=4" width="50;" alt="Patricol"/>
<br />
<sub><b>Patrick Collins</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/chriscpritchard">
<img src="https://avatars.githubusercontent.com/u/1839074?v=4" width="50;" alt="chriscpritchard"/>
<br />
<sub><b>Chris Pritchard</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/deepwather">
<img src="https://avatars.githubusercontent.com/u/12274612?v=4" width="50;" alt="deepwather"/>
<br />
<sub><b>Michael Reber</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/stpanzer">
<img src="https://avatars.githubusercontent.com/u/4676271?v=4" width="50;" alt="stpanzer"/>
<br />
<sub><b>Stephen Panzer</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/aptalca">
<img src="https://avatars.githubusercontent.com/u/541623?v=4" width="50;" alt="aptalca"/>
<br />
<sub><b>Aptalca</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/mhann">
<img src="https://avatars.githubusercontent.com/u/17162399?v=4" width="50;" alt="mhann"/>
<br />
<sub><b>Mhann</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/ombi-bot">
<img src="https://avatars.githubusercontent.com/u/51722903?v=4" width="50;" alt="ombi-bot"/>
<br />
<sub><b>Ombi-bot</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/snyk-bot">
<img src="https://avatars.githubusercontent.com/u/19733683?v=4" width="50;" alt="snyk-bot"/>
<br />
<sub><b>Snyk Bot</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/andrewjmetzger">
<img src="https://avatars.githubusercontent.com/u/590246?v=4" width="50;" alt="andrewjmetzger"/>
<br />
<sub><b>Andrew Metzger</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/au5ton">
<img src="https://avatars.githubusercontent.com/u/4109551?v=4" width="50;" alt="au5ton"/>
<br />
<sub><b>Austin Jackson</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/D34DC3N73R">
<img src="https://avatars.githubusercontent.com/u/9123670?v=4" width="50;" alt="D34DC3N73R"/>
<br />
<sub><b>D34DC3N73R</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/pooley182">
<img src="https://avatars.githubusercontent.com/u/5040011?v=4" width="50;" alt="pooley182"/>
<br />
<sub><b>David Pooley</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/Fredrik81">
<img src="https://avatars.githubusercontent.com/u/21292774?v=4" width="50;" alt="Fredrik81"/>
<br />
<sub><b>Fredrik81</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Aerion">
<img src="https://avatars.githubusercontent.com/u/9089317?v=4" width="50;" alt="Aerion"/>
<br />
<sub><b>Guillaume Taquet Gasperini</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/jackodsteel">
<img src="https://avatars.githubusercontent.com/u/9209504?v=4" width="50;" alt="jackodsteel"/>
<br />
<sub><b>Jack Steel</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/jpeters">
<img src="https://avatars.githubusercontent.com/u/167401?v=4" width="50;" alt="jpeters"/>
<br />
<sub><b>Jeffrey Peters</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/MariusSchiffer">
<img src="https://avatars.githubusercontent.com/u/183124?v=4" width="50;" alt="MariusSchiffer"/>
<br />
<sub><b>Marius Schiffer</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Qstick">
<img src="https://avatars.githubusercontent.com/u/376117?v=4" width="50;" alt="Qstick"/>
<br />
<sub><b>Qstick</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/Vbgf">
<img src="https://avatars.githubusercontent.com/u/5571734?v=4" width="50;" alt="Vbgf"/>
<br />
<sub><b>Vbgf</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/sorano">
<img src="https://avatars.githubusercontent.com/u/6185109?v=4" width="50;" alt="sorano"/>
<br />
<sub><b>Sorano</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/vsc55">
<img src="https://avatars.githubusercontent.com/u/13438676?v=4" width="50;" alt="vsc55"/>
<br />
<sub><b>Javier Pastor</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/AbeKline">
<img src="https://avatars.githubusercontent.com/u/8125653?v=4" width="50;" alt="AbeKline"/>
<br />
<sub><b>Abe Kline</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/XanderStrike">
<img src="https://avatars.githubusercontent.com/u/1565303?v=4" width="50;" alt="XanderStrike"/>
<br />
<sub><b>Alexander Standke</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Alasano">
<img src="https://avatars.githubusercontent.com/u/14372930?v=4" width="50;" alt="Alasano"/>
<br />
<sub><b>Aljosa Asanovic</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/Ashyni">
<img src="https://avatars.githubusercontent.com/u/18462848?v=4" width="50;" alt="Ashyni"/>
<br />
<sub><b>Ashyni</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Majawat">
<img src="https://avatars.githubusercontent.com/u/12058855?v=4" width="50;" alt="Majawat"/>
<br />
<sub><b>Majawat</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/CalvinWalzel">
<img src="https://avatars.githubusercontent.com/u/6446452?v=4" width="50;" alt="CalvinWalzel"/>
<br />
<sub><b>Calvin</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/origamirobot">
<img src="https://avatars.githubusercontent.com/u/1346803?v=4" width="50;" alt="origamirobot"/>
<br />
<sub><b>Chris Lees</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/cdemi">
<img src="https://avatars.githubusercontent.com/u/8025435?v=4" width="50;" alt="cdemi"/>
<br />
<sub><b>Christopher Demicoli</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Codehhh">
<img src="https://avatars.githubusercontent.com/u/12055335?v=4" width="50;" alt="Codehhh"/>
<br />
<sub><b>Codehhh</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/danopia">
<img src="https://avatars.githubusercontent.com/u/40628?v=4" width="50;" alt="danopia"/>
<br />
<sub><b>Daniel Lamando</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/hmnd">
<img src="https://avatars.githubusercontent.com/u/12853597?v=4" width="50;" alt="hmnd"/>
<br />
<sub><b>David</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/davidtorosyan">
<img src="https://avatars.githubusercontent.com/u/46736285?v=4" width="50;" alt="davidtorosyan"/>
<br />
<sub><b>David Torosyan</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/onedr0p">
<img src="https://avatars.githubusercontent.com/u/213795?v=4" width="50;" alt="onedr0p"/>
<br />
<sub><b>Devin Buhl</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/elisspace">
<img src="https://avatars.githubusercontent.com/u/18365129?v=4" width="50;" alt="elisspace"/>
<br />
<sub><b>Eli</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Fish2">
<img src="https://avatars.githubusercontent.com/u/2311734?v=4" width="50;" alt="Fish2"/>
<br />
<sub><b>Fish2</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/hariesramdhani">
<img src="https://avatars.githubusercontent.com/u/24251244?v=4" width="50;" alt="hariesramdhani"/>
<br />
<sub><b>Haries Ramdhani</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/ImgBotApp">
<img src="https://avatars.githubusercontent.com/u/31427850?v=4" width="50;" alt="ImgBotApp"/>
<br />
<sub><b>Imgbot</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/JPyke3">
<img src="https://avatars.githubusercontent.com/u/13283054?v=4" width="50;" alt="JPyke3"/>
<br />
<sub><b>Jacob Pyke</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/jamesmacwhite">
<img src="https://avatars.githubusercontent.com/u/8067792?v=4" width="50;" alt="jamesmacwhite"/>
<br />
<sub><b>James White</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/frebib">
<img src="https://avatars.githubusercontent.com/u/775104?v=4" width="50;" alt="frebib"/>
<br />
<sub><b>Joe Groocock</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/errorhandler">
<img src="https://avatars.githubusercontent.com/u/17112958?v=4" width="50;" alt="errorhandler"/>
<br />
<sub><b>Joe Harvey</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/jonbloom">
<img src="https://avatars.githubusercontent.com/u/492819?v=4" width="50;" alt="jonbloom"/>
<br />
<sub><b>Jon Bloom</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/jonocairns">
<img src="https://avatars.githubusercontent.com/u/182836?v=4" width="50;" alt="jonocairns"/>
<br />
<sub><b>Jono Cairns</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/krisklosterman">
<img src="https://avatars.githubusercontent.com/u/7139579?v=4" width="50;" alt="krisklosterman"/>
<br />
<sub><b>Kris Klosterman</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/kmlucy">
<img src="https://avatars.githubusercontent.com/u/13952475?v=4" width="50;" alt="kmlucy"/>
<br />
<sub><b>Kyle Lucy</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Lixumos">
<img src="https://avatars.githubusercontent.com/u/29160577?v=4" width="50;" alt="Lixumos"/>
<br />
<sub><b>Lightkeeper</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/devbymadde">
<img src="https://avatars.githubusercontent.com/u/6094593?v=4" width="50;" alt="devbymadde"/>
<br />
<sub><b>Madeleine Schönemann</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/mattmattmatt">
<img src="https://avatars.githubusercontent.com/u/927830?v=4" width="50;" alt="mattmattmatt"/>
<br />
<sub><b>Matt</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/AliMickey">
<img src="https://avatars.githubusercontent.com/u/60691199?v=4" width="50;" alt="AliMickey"/>
<br />
<sub><b>Micky</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/beast3334">
<img src="https://avatars.githubusercontent.com/u/20631046?v=4" width="50;" alt="beast3334"/>
<br />
<sub><b>Nathan Miller</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/randallbruder">
<img src="https://avatars.githubusercontent.com/u/6447487?v=4" width="50;" alt="randallbruder"/>
<br />
<sub><b>Randall Bruder</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/rob1998">
<img src="https://avatars.githubusercontent.com/u/1560707?v=4" width="50;" alt="rob1998"/>
<br />
<sub><b>Rob Gökemeijer</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/sambartik">
<img src="https://avatars.githubusercontent.com/u/63553146?v=4" width="50;" alt="sambartik"/>
<br />
<sub><b>Samuel Bartík</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/seancallinan">
<img src="https://avatars.githubusercontent.com/u/1139665?v=4" width="50;" alt="seancallinan"/>
<br />
<sub><b>Sean Callinan</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/shoghicp">
<img src="https://avatars.githubusercontent.com/u/516482?v=4" width="50;" alt="shoghicp"/>
<br />
<sub><b>Shoghi</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/thomasvt1">
<img src="https://avatars.githubusercontent.com/u/2271011?v=4" width="50;" alt="thomasvt1"/>
<br />
<sub><b>Thomas Van Tilburg</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Tim-Trott">
<img src="https://avatars.githubusercontent.com/u/8249434?v=4" width="50;" alt="Tim-Trott"/>
<br />
<sub><b>Tim Trott</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/tombomb">
<img src="https://avatars.githubusercontent.com/u/544509?v=4" width="50;" alt="tombomb"/>
<br />
<sub><b>Tom McClellan</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Torkiliuz">
<img src="https://avatars.githubusercontent.com/u/460764?v=4" width="50;" alt="Torkiliuz"/>
<br />
<sub><b>Torkil</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/bybeet">
<img src="https://avatars.githubusercontent.com/u/1662279?v=4" width="50;" alt="bybeet"/>
<br />
<sub><b>Travis Bybee</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/Xirg">
<img src="https://avatars.githubusercontent.com/u/6020502?v=4" width="50;" alt="Xirg"/>
<br />
<sub><b>Xirg</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/bazhip">
<img src="https://avatars.githubusercontent.com/u/10350445?v=4" width="50;" alt="bazhip"/>
<br />
<sub><b>Tim OBrien</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/x-limitless-x">
<img src="https://avatars.githubusercontent.com/u/17127926?v=4" width="50;" alt="x-limitless-x"/>
<br />
<sub><b>Blake Drumm</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/camjac251">
<img src="https://avatars.githubusercontent.com/u/6313132?v=4" width="50;" alt="camjac251"/>
<br />
<sub><b>Camjac251</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/distaula">
<img src="https://avatars.githubusercontent.com/u/33949?v=4" width="50;" alt="distaula"/>
<br />
<sub><b>Michael DiStaula</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/baikunz">
<img src="https://avatars.githubusercontent.com/u/984911?v=4" width="50;" alt="baikunz"/>
<br />
<sub><b>Dorian ALKOUM</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/m4tta">
<img src="https://avatars.githubusercontent.com/u/427218?v=4" width="50;" alt="m4tta"/>
<br />
<sub><b>M4tta</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/masterhuck">
<img src="https://avatars.githubusercontent.com/u/4671442?v=4" width="50;" alt="masterhuck"/>
<br />
<sub><b>Patrick Weber</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/sir-marv">
<img src="https://avatars.githubusercontent.com/u/3598205?v=4" width="50;" alt="sir-marv"/>
<br />
<sub><b>Sirmarv</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/tdorsey">
<img src="https://avatars.githubusercontent.com/u/1218404?v=4" width="50;" alt="tdorsey"/>
<br />
<sub><b>Tdorsey</b></sub>
</a>
</td>
<td align="center">
<a href="https://github.com/thegame3202">
<img src="https://avatars.githubusercontent.com/u/22148848?v=4" width="50;" alt="thegame3202"/>
<br />
<sub><b>Mike</b></sub>
</a>
</td></tr>
<tr>
<td align="center">
<a href="https://github.com/zobe123">
<img src="https://avatars.githubusercontent.com/u/13840542?v=4" width="50;" alt="zobe123"/>
<br />
<sub><b>Zobe123</b></sub>
</a>
</td></tr>
</table>
<!-- readme: collaborators,contributors -end -->
# Donation
If you feel like donating you can donate with the below buttons!

@ -1,15 +0,0 @@
# Changelog
{{#versions}}
## {{{label}}}
{{#sections}}
### {{{label}}}
{{#commits}}
- {{{subject}}} [{{{author}}}]
{{/commits}}
{{/sections}}
{{/versions}}

@ -1,3 +1,10 @@
commit_message: "fix(translations): 🌐 New translations from Crowdin [skip ci]"
append_commit_message: false
pull_request_title: "🌐 Translations Update"
pull_request_labels:
- translations
files:
- source: /src/Ombi/wwwroot/translations/en.json
translation: /src/Ombi/wwwroot/translations/%two_letters_code%.json

@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -6,10 +6,6 @@ namespace Ombi.Api.Plex.Models
{
public int size { get; set; }
public int totalSize { get; set; }
public bool allowSync { get; set; }
public string identifier { get; set; }
public string mediaTagPrefix { get; set; }
public int mediaTagVersion { get; set; }
public string title1 { get; set; }
public List<Directory> Directory { get; set; }
public string art { get; set; }

@ -1,3 +1,5 @@
using System.Collections.Generic;
namespace Ombi.Api.Plex.Models
{
public class Metadata
@ -44,7 +46,7 @@ namespace Ombi.Api.Plex.Models
public string grandparentTheme { get; set; }
public string chapterSource { get; set; }
public Medium[] Media { get; set; }
public PlexGuids[] Guid { get; set; }
public List<PlexGuids> Guid { get; set; } = new List<PlexGuids>();
// public Director[] Director { get; set; }
// public Writer[] Writer { get; set; }
}

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -123,6 +123,7 @@ namespace Ombi.Api.Plex
public async Task<PlexContainer> GetLibrary(string authToken, string plexFullHost, string libraryId)
{
var request = new Request($"library/sections/{libraryId}/all", plexFullHost, HttpMethod.Get);
request.AddQueryString("includeGuids","1");
await AddHeaders(request, authToken);
return await Api.Request<PlexContainer>(request);
}
@ -234,7 +235,7 @@ namespace Ombi.Api.Plex
public async Task<Uri> GetOAuthUrl(string code, string applicationUrl)
{
var request = new Request("auth#", "https://app.plex.tv", HttpMethod.Get);
var request = new Request("auth/#", "https://app.plex.tv", HttpMethod.Get);
await AddHeaders(request);
request.AddQueryString("code", code);

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -9,6 +9,7 @@
<AssemblyName>Ombi.Api.Service</AssemblyName>
<RootNamespace>Ombi.Api.Service</RootNamespace>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -6,6 +6,7 @@
<FileVersion>3.0.0.0</FileVersion>
<Version></Version>
<PackageVersion></PackageVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -0,0 +1,527 @@
using MockQueryable.Moq;
using Moq;
using Moq.AutoMock;
using NUnit.Framework;
using Ombi.Core.Authentication;
using Ombi.Core.Engine;
using Ombi.Core.Models;
using Ombi.Core.Services;
using Ombi.Helpers;
using Ombi.Store.Entities;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
namespace Ombi.Core.Tests.Engine
{
[TestFixture]
public class MovieRequestLimitsTests
{
private AutoMocker _mocker;
private RequestLimitService _subject;
[SetUp]
public void SetUp()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
_mocker = new AutoMocker();
var principleMock = new Mock<IPrincipal>();
var identityMock = new Mock<IIdentity>();
identityMock.SetupGet(x => x.Name).Returns("Test");
principleMock.SetupGet(x => x.Identity).Returns(identityMock.Object);
_mocker.Use(principleMock.Object);
_subject = _mocker.CreateInstance<RequestLimitService>();
}
[Test]
public async Task User_No_MovieLimit_Set()
{
var user = new OmbiUser();
var result = await _subject.GetRemainingMovieRequests(user);
Assert.That(result.HasLimit, Is.False);
}
[Test]
public async Task No_UserPassedIn_UsernotExist_No_MovieLimit_Set()
{
var user = new OmbiUser();
var um = _mocker.GetMock<OmbiUserManager>();
um.SetupGet(x => x.Users).Returns(new List<OmbiUser> { user }.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(null);
Assert.That(result, Is.Null);
}
[Test]
public async Task No_UserPassedIn_No_MovieLimit_Set()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST"
};
var um = _mocker.GetMock<OmbiUserManager>();
um.SetupGet(x => x.Users).Returns(new List<OmbiUser> { user }.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(null);
Assert.That(result.HasLimit, Is.False);
}
[Test]
public async Task UserPassedIn_MovieLimit_Set_No_Requests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MovieRequestLimit = 1
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(new List<RequestLog>().AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
);
}
[Test]
public async Task UserPassedIn_MovieLimit_Set_Limit()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MovieRequestLimit = 2,
Id = "id1"
};
var yesterday = DateTime.Now.AddDays(-1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = yesterday, // Yesterday
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(yesterday.AddDays(7))
);
}
[Test]
[Ignore("Failing on CI")]
public async Task UserPassedIn_MovieLimit_Set_Limit_MultipleRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MovieRequestLimit = 2,
Id = "id1"
};
var yesterday = new DateTime(2020, 09, 05).AddDays(-1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = yesterday,
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = yesterday.AddDays(-2),
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate =yesterday.AddDays(-3), // Yesterday
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate =yesterday.AddDays(-4), // Yesterday
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate =yesterday.AddDays(-5), // Yesterday
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate =yesterday.AddDays(-6), // Yesterday
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate =yesterday.AddDays(-7), // Yesterday
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = yesterday.AddDays(-8), // Yesterday
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(0)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(yesterday.AddDays(1))
);
}
[Test]
public async Task UserPassedIn_MovieLimit_Set_Limit_Daily_NoRequestsToday()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MovieRequestLimit = 2,
MovieRequestLimitType = RequestLimitType.Day,
Id = "id1"
};
var yesterday = new DateTime(2020, 09, 05).AddDays(-1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = yesterday,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(2)
);
}
[Test]
public async Task UserPassedIn_MovieLimit_Set_Limit_Daily_OneRequestsToday()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MovieRequestLimit = 2,
MovieRequestLimitType = RequestLimitType.Day,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = today.AddHours(-1),
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.AddDays(1).Date)
);
}
[Test]
public async Task UserPassedIn_MovieLimit_Set_Limit_Daily_AllRequestsToday()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MovieRequestLimit = 2,
MovieRequestLimitType = RequestLimitType.Day,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = today.AddHours(-1),
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = today.AddHours(-2),
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(0)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.AddDays(1).Date)
);
}
[Test]
public async Task UserPassedIn_MovieLimit_Set_Limit_Weekly_NoRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MovieRequestLimit = 2,
MovieRequestLimitType = RequestLimitType.Week,
Id = "id1"
};
var lastWeek = new DateTime(2020, 09, 05).FirstDateInWeek().AddDays(-1); // Day before reset
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = lastWeek,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(2)
);
}
[Test]
public async Task UserPassedIn_MovieLimit_Set_Limit_Weekly_OneRequestsWeek()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MovieRequestLimit = 2,
MovieRequestLimitType = RequestLimitType.Week,
Id = "id1"
};
var today = new DateTime(2021,10,05);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = today,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(user, today);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.FirstDateInWeek().AddDays(7).Date)
);
}
[Test]
public async Task UserPassedIn_MovieLimit_Set_Limit_Weekly_AllRequestsWeek()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MovieRequestLimit = 2,
MovieRequestLimitType = RequestLimitType.Week,
Id = "id1"
};
var today = new DateTime(2021,10,05);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = today,
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = today,
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(user, today);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(0)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.FirstDateInWeek().AddDays(7).Date)
);
}
[Test]
public async Task UserPassedIn_MovieLimit_Set_Limit_Monthly_NoRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MovieRequestLimit = 2,
MovieRequestLimitType = RequestLimitType.Month,
Id = "id1"
};
var lastWeek = new DateTime(2020, 09, 05).AddMonths(-1).AddDays(-1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = lastWeek,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(2)
);
}
[Test]
public async Task UserPassedIn_MovieLimit_Set_Limit_Monthly_OneRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MovieRequestLimit = 2,
MovieRequestLimitType = RequestLimitType.Month,
Id = "id1"
};
var today = DateTime.UtcNow;
var firstDayOfMonth = new DateTime(today.Year, today.Month, 1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = today,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(firstDayOfMonth.AddMonths(1).Date)
);
}
[Test]
public async Task UserPassedIn_MovieLimit_Set_Limit_Monthly_AllRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MovieRequestLimit = 2,
MovieRequestLimitType = RequestLimitType.Month,
Id = "id1"
};
var today = DateTime.UtcNow;
var firstDayOfMonth = new DateTime(today.Year, today.Month, 1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = today.AddDays(-1),
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Movie,
RequestDate = today,
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMovieRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(0)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(firstDayOfMonth.AddMonths(1).Date)
);
}
}
}

@ -0,0 +1,527 @@
using MockQueryable.Moq;
using Moq;
using Moq.AutoMock;
using NUnit.Framework;
using Ombi.Core.Authentication;
using Ombi.Core.Engine;
using Ombi.Core.Models;
using Ombi.Core.Services;
using Ombi.Helpers;
using Ombi.Store.Entities;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
namespace Ombi.Core.Tests.Engine
{
[TestFixture]
public class MusicRequestLimitTests
{
private AutoMocker _mocker;
private RequestLimitService _subject;
[SetUp]
public void SetUp()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
_mocker = new AutoMocker();
var principleMock = new Mock<IPrincipal>();
var identityMock = new Mock<IIdentity>();
identityMock.SetupGet(x => x.Name).Returns("Test");
principleMock.SetupGet(x => x.Identity).Returns(identityMock.Object);
_mocker.Use(principleMock.Object);
_subject = _mocker.CreateInstance<RequestLimitService>();
}
[Test]
public async Task User_No_MusicLimit_Set()
{
var user = new OmbiUser();
var result = await _subject.GetRemainingMusicRequests(user);
Assert.That(result.HasLimit, Is.False);
}
[Test]
public async Task No_UserPassedIn_UsernotExist_No_MusicLimit_Set()
{
var user = new OmbiUser();
var um = _mocker.GetMock<OmbiUserManager>();
um.SetupGet(x => x.Users).Returns(new List<OmbiUser> { user }.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(null);
Assert.That(result, Is.Null);
}
[Test]
public async Task No_UserPassedIn_No_MusicLimit_Set()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST"
};
var um = _mocker.GetMock<OmbiUserManager>();
um.SetupGet(x => x.Users).Returns(new List<OmbiUser> { user }.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(null);
Assert.That(result.HasLimit, Is.False);
}
[Test]
public async Task UserPassedIn_MusicLimit_Set_No_Requests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MusicRequestLimit = 1
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(new List<RequestLog>().AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
);
}
[Test]
public async Task UserPassedIn_MusicLimit_Set_Limit()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MusicRequestLimit = 2,
Id = "id1"
};
var yesterday = DateTime.UtcNow.AddDays(-1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = yesterday, // Yesterday
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(yesterday.AddDays(7))
);
}
[Test]
[Ignore("Failing on CI")]
public async Task UserPassedIn_MusicLimit_Set_Limit_MultipleRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MusicRequestLimit = 2,
Id = "id1"
};
var yesterday = new DateTime(2020, 09, 05).AddDays(-1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = yesterday,
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = yesterday.AddDays(-2),
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate =yesterday.AddDays(-3), // Yesterday
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate =yesterday.AddDays(-4), // Yesterday
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate =yesterday.AddDays(-5), // Yesterday
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate =yesterday.AddDays(-6), // Yesterday
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate =yesterday.AddDays(-7), // Yesterday
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = yesterday.AddDays(-8), // Yesterday
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(0)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(yesterday.AddDays(1))
);
}
[Test]
public async Task UserPassedIn_MusicLimit_Set_Limit_Daily_NoRequestsToday()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MusicRequestLimit = 2,
MusicRequestLimitType = RequestLimitType.Day,
Id = "id1"
};
var yesterday = new DateTime(2020, 09, 05).AddDays(-1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = yesterday,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(2)
);
}
[Test]
public async Task UserPassedIn_MusicLimit_Set_Limit_Daily_OneRequestsToday()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MusicRequestLimit = 2,
MusicRequestLimitType = RequestLimitType.Day,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = today.AddHours(-1),
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.AddDays(1).Date)
);
}
[Test]
public async Task UserPassedIn_MusicLimit_Set_Limit_Daily_AllRequestsToday()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MusicRequestLimit = 2,
MusicRequestLimitType = RequestLimitType.Day,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = today.AddHours(-1),
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = today.AddHours(-2),
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(0)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.AddDays(1).Date)
);
}
[Test]
public async Task UserPassedIn_MusicLimit_Set_Limit_Weekly_NoRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MusicRequestLimit = 2,
MusicRequestLimitType = RequestLimitType.Week,
Id = "id1"
};
var lastWeek = new DateTime(2020, 09, 05).FirstDateInWeek().AddDays(-1); // Day before reset
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = lastWeek,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(2)
);
}
[Test]
public async Task UserPassedIn_MusicLimit_Set_Limit_Weekly_OneRequestsWeek()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MusicRequestLimit = 2,
MusicRequestLimitType = RequestLimitType.Week,
Id = "id1"
};
var today = new DateTime(2021, 10, 05);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = today,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(user, today);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.FirstDateInWeek().AddDays(7).Date)
);
}
[Test]
public async Task UserPassedIn_MusicLimit_Set_Limit_Weekly_AllRequestsWeek()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MusicRequestLimit = 2,
MusicRequestLimitType = RequestLimitType.Week,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = today.AddMinutes(-2),
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = today.AddMinutes(-1),
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(0)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.FirstDateInWeek().AddDays(7).Date)
);
}
[Test]
public async Task UserPassedIn_MusicLimit_Set_Limit_Monthly_NoRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MusicRequestLimit = 2,
MusicRequestLimitType = RequestLimitType.Month,
Id = "id1"
};
var lastWeek = new DateTime(2020, 09, 05).AddMonths(-1).AddDays(-1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = lastWeek,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(2)
);
}
[Test]
public async Task UserPassedIn_MusicLimit_Set_Limit_Monthly_OneRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MusicRequestLimit = 2,
MusicRequestLimitType = RequestLimitType.Month,
Id = "id1"
};
var today = DateTime.UtcNow;
var firstDayOfMonth = new DateTime(today.Year, today.Month, 1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = today,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(firstDayOfMonth.AddMonths(1).Date)
);
}
[Test]
public async Task UserPassedIn_MusicLimit_Set_Limit_Monthly_AllRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
MusicRequestLimit = 2,
MusicRequestLimitType = RequestLimitType.Month,
Id = "id1"
};
var today = DateTime.UtcNow;
var firstDayOfMonth = new DateTime(today.Year, today.Month, 1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = today.AddDays(-1),
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.Album,
RequestDate = today,
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingMusicRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(0)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(firstDayOfMonth.AddMonths(1).Date)
);
}
}
}

@ -0,0 +1,666 @@
using MockQueryable.Moq;
using Moq;
using Moq.AutoMock;
using NUnit.Framework;
using Ombi.Core.Authentication;
using Ombi.Core.Engine;
using Ombi.Core.Models;
using Ombi.Core.Services;
using Ombi.Helpers;
using Ombi.Store.Entities;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
namespace Ombi.Core.Tests.Engine
{
[TestFixture]
public class TvRequestLimitsTests
{
private AutoMocker _mocker;
private RequestLimitService _subject;
[SetUp]
public void SetUp()
{
_mocker = new AutoMocker();
var principleMock = new Mock<IPrincipal>();
var identityMock = new Mock<IIdentity>();
identityMock.SetupGet(x => x.Name).Returns("Test");
principleMock.SetupGet(x => x.Identity).Returns(identityMock.Object);
_mocker.Use(principleMock.Object);
_subject = _mocker.CreateInstance<RequestLimitService>();
}
[Test]
public async Task User_No_TvLimit_Set()
{
var user = new OmbiUser();
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result.HasLimit, Is.False);
}
[Test]
public async Task No_UserPassedIn_UsernotExist_No_TvLimit_Set()
{
var user = new OmbiUser();
var um = _mocker.GetMock<OmbiUserManager>();
um.SetupGet(x => x.Users).Returns(new List<OmbiUser> { user }.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(null);
Assert.That(result, Is.Null);
}
[Test]
public async Task No_UserPassedIn_No_TvLimit_Set()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST"
};
var um = _mocker.GetMock<OmbiUserManager>();
um.SetupGet(x => x.Users).Returns(new List<OmbiUser> { user }.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(null);
Assert.That(result.HasLimit, Is.False);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_No_Requests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 1
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(new List<RequestLog>().AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 2,
Id = "id1"
};
var yesterday = DateTime.UtcNow.AddDays(-1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
RequestDate = yesterday, // Yesterday
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(yesterday.AddDays(7).Date)
);
}
[Test]
[Ignore("Failing on CI")]
public async Task UserPassedIn_TvLimit_Set_Limit_MultipleRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 2,
Id = "id1"
};
var yesterday = new DateTime(2020, 09, 05).AddDays(-1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
EpisodeCount = 1,
RequestType = RequestType.TvShow,
RequestDate = yesterday,
},
new RequestLog
{
UserId = "id1",
EpisodeCount = 1,
RequestType = RequestType.TvShow,
RequestDate = yesterday.AddDays(-2),
},
new RequestLog
{
UserId = "id1",
EpisodeCount = 1,
RequestType = RequestType.TvShow,
RequestDate =yesterday.AddDays(-3),
},
new RequestLog
{
EpisodeCount = 1,
UserId = "id1",
RequestType = RequestType.TvShow,
RequestDate =yesterday.AddDays(-4),
},
new RequestLog
{
UserId = "id1",
EpisodeCount = 1,
RequestType = RequestType.TvShow,
RequestDate =yesterday.AddDays(-5),
},
new RequestLog
{
UserId = "id1",
EpisodeCount = 1,
RequestType = RequestType.TvShow,
RequestDate =yesterday.AddDays(-6),
},
new RequestLog
{
UserId = "id1",
EpisodeCount = 1,
RequestType = RequestType.TvShow,
RequestDate =yesterday.AddDays(-7),
},
new RequestLog
{
UserId = "id1",
EpisodeCount = 1,
RequestType = RequestType.TvShow,
RequestDate = yesterday.AddDays(-8),
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(0)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(yesterday.AddDays(1).Date)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit_Daily_NoRequestsToday()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 2,
EpisodeRequestLimitType = RequestLimitType.Day,
Id = "id1"
};
var yesterday = new DateTime(2020, 09, 05).AddDays(-1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
EpisodeCount = 1,
RequestDate = yesterday,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(2)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit_Daily_OneRequestsToday()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 2,
EpisodeRequestLimitType = RequestLimitType.Day,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
EpisodeCount = 1,
RequestType = RequestType.TvShow,
RequestDate = today.AddHours(-1),
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.AddDays(1).Date)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit_Daily_AllRequestsToday()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 2,
EpisodeRequestLimitType = RequestLimitType.Day,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
RequestDate = today.AddHours(-1),
EpisodeCount = 1,
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
EpisodeCount = 1,
RequestDate = today.AddHours(-2),
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(0)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.AddDays(1).Date)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit_Daily_MultipleEpisodeRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 10,
EpisodeRequestLimitType = RequestLimitType.Day,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
RequestDate = today.AddHours(-1),
EpisodeCount = 5,
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
EpisodeCount = 4,
RequestDate = today.AddHours(-2),
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(10)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.AddDays(1).Date)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit_Weekly_NoRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 2,
EpisodeRequestLimitType = RequestLimitType.Week,
Id = "id1"
};
var lastWeek = DateTime.Now.AddDays(-8);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
EpisodeCount = 1,
RequestDate = lastWeek,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(2)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit_Weekly_OneRequestsWeek()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 2,
EpisodeRequestLimitType = RequestLimitType.Week,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
EpisodeCount = 1,
RequestType = RequestType.TvShow,
RequestDate = today,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.FirstDateInWeek().AddDays(7).Date)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit_Weekly_AllRequestsWeek()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 2,
EpisodeRequestLimitType = RequestLimitType.Week,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
EpisodeCount = 1,
RequestDate = today.AddDays(-1),
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
RequestDate = today,
EpisodeCount = 1,
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(0)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.FirstDateInWeek().AddDays(7).Date)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit_Weekly_MultipleEpisodeRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 10,
EpisodeRequestLimitType = RequestLimitType.Week,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
EpisodeCount = 5,
RequestDate = today.AddDays(-1),
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
RequestDate = today,
EpisodeCount = 4,
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(10)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(today.FirstDateInWeek().AddDays(7).Date)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit_Monthly_NoRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 2,
EpisodeRequestLimitType = RequestLimitType.Month,
Id = "id1"
};
var lastWeek = new DateTime(2020, 09, 05).AddMonths(-1).AddDays(-1);
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
EpisodeCount = 1,
RequestDate = lastWeek,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(2)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit_Monthly_OneRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 2,
EpisodeRequestLimitType = RequestLimitType.Month,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
EpisodeCount = 1,
RequestType = RequestType.TvShow,
RequestDate = today,
}
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(new DateTime(today.Year, today.Month, 1).AddMonths(1).Date)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit_Monthly_AllRequests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 2,
EpisodeRequestLimitType = RequestLimitType.Month,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
EpisodeCount = 1,
RequestDate = today.AddDays(-1),
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
EpisodeCount = 1,
RequestDate = today,
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(2)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(0)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(new DateTime(today.Year, today.Month, 1).AddMonths(1).Date)
);
}
[Test]
public async Task UserPassedIn_TvLimit_Set_Limit_Monthly_MultipleEpisodeReuests()
{
var user = new OmbiUser
{
NormalizedUserName = "TEST",
EpisodeRequestLimit = 10,
EpisodeRequestLimitType = RequestLimitType.Month,
Id = "id1"
};
var today = DateTime.UtcNow;
var log = new List<RequestLog>
{
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
EpisodeCount =5,
RequestDate = today.AddDays(-1),
},
new RequestLog
{
UserId = "id1",
RequestType = RequestType.TvShow,
EpisodeCount = 4,
RequestDate = today,
},
};
var repoMock = _mocker.GetMock<IRepository<RequestLog>>();
repoMock.Setup(x => x.GetAll()).Returns(log.AsQueryable().BuildMock().Object);
var result = await _subject.GetRemainingTvRequests(user);
Assert.That(result, Is.InstanceOf<RequestQuotaCountModel>()
.With.Property(nameof(RequestQuotaCountModel.HasLimit)).EqualTo(true)
.And.Property(nameof(RequestQuotaCountModel.Limit)).EqualTo(10)
.And.Property(nameof(RequestQuotaCountModel.Remaining)).EqualTo(1)
.And.Property(nameof(RequestQuotaCountModel.NextRequest)).EqualTo(new DateTime(today.Year, today.Month, 1).AddMonths(1).Date)
);
}
}
}

@ -4,12 +4,14 @@
<TargetFramework>net5.0</TargetFramework>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoFixture" Version="4.11.0" />
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="5.0.0" />
<PackageReference Include="Moq" Version="4.14.1" />
<PackageReference Include="Moq" Version="4.15.1" />
<PackageReference Include="Moq.AutoMock" Version="3.0.0" />
<PackageReference Include="Nunit" Version="3.12.0" />
<PackageReference Include="NUnit.ConsoleRunner" Version="3.11.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.16.1">

@ -0,0 +1,258 @@
using Moq;
using Moq.AutoMock;
using NUnit.Framework;
using Ombi.Core.Rule;
using Ombi.Core.Rule.Rules.Request;
using Ombi.Core.Services;
using Ombi.Store.Entities;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository.Requests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ombi.Core.Tests.Rule.Request
{
[TestFixture]
public class RequestLimitRuleTests
{
private AutoMocker _mocker;
private RequestLimitRule _subject;
[SetUp]
public void SetUp()
{
_mocker = new AutoMocker();
_subject = _mocker.CreateInstance<RequestLimitRule>();
}
[Test]
public async Task MovieRule_No_Limit()
{
var limitService = _mocker.GetMock<IRequestLimitService>();
limitService.Setup(x => x.GetRemainingMovieRequests(It.IsAny<OmbiUser>(), It.IsAny<DateTime>())).ReturnsAsync(new Models.RequestQuotaCountModel
{
HasLimit = false
});
var result = await _subject.Execute(new Store.Entities.Requests.BaseRequest
{
RequestType = RequestType.Movie
});
Assert.That(result, Is.InstanceOf<RuleResult>().With.Property(nameof(RuleResult.Success)).EqualTo(true));
}
[Test]
public async Task MovieRule_Limit_NotReached()
{
var limitService = _mocker.GetMock<IRequestLimitService>();
limitService.Setup(x => x.GetRemainingMovieRequests(It.IsAny<OmbiUser>(), It.IsAny<DateTime>())).ReturnsAsync(new Models.RequestQuotaCountModel
{
HasLimit = true,
Limit = 2,
Remaining = 1
});
var result = await _subject.Execute(new Store.Entities.Requests.BaseRequest
{
RequestType = RequestType.Movie
});
Assert.That(result, Is.InstanceOf<RuleResult>().With.Property(nameof(RuleResult.Success)).EqualTo(true));
}
[Test]
public async Task MovieRule_Limit_Reached()
{
var limitService = _mocker.GetMock<IRequestLimitService>();
limitService.Setup(x => x.GetRemainingMovieRequests(It.IsAny<OmbiUser>(), It.IsAny<DateTime>())).ReturnsAsync(new Models.RequestQuotaCountModel
{
HasLimit = true,
Limit = 1,
Remaining = 0
});
var result = await _subject.Execute(new Store.Entities.Requests.BaseRequest
{
RequestType = RequestType.Movie
});
Assert.That(result, Is.InstanceOf<RuleResult>().With.Property(nameof(RuleResult.Success)).EqualTo(false));
}
[Test]
public async Task MusicRule_No_Limit()
{
var limitService = _mocker.GetMock<IRequestLimitService>();
limitService.Setup(x => x.GetRemainingMusicRequests(It.IsAny<OmbiUser>(), It.IsAny<DateTime>())).ReturnsAsync(new Models.RequestQuotaCountModel
{
HasLimit = false
});
var result = await _subject.Execute(new Store.Entities.Requests.BaseRequest
{
RequestType = RequestType.Album
});
Assert.That(result, Is.InstanceOf<RuleResult>().With.Property(nameof(RuleResult.Success)).EqualTo(true));
}
[Test]
public async Task MusicRule_Limit_NotReached()
{
var limitService = _mocker.GetMock<IRequestLimitService>();
limitService.Setup(x => x.GetRemainingMusicRequests(It.IsAny<OmbiUser>(), It.IsAny<DateTime>())).ReturnsAsync(new Models.RequestQuotaCountModel
{
HasLimit = true,
Limit = 2,
Remaining = 1
});
var result = await _subject.Execute(new Store.Entities.Requests.BaseRequest
{
RequestType = RequestType.Album
});
Assert.That(result, Is.InstanceOf<RuleResult>().With.Property(nameof(RuleResult.Success)).EqualTo(true));
}
[Test]
public async Task MusicRule_Limit_Reached()
{
var limitService = _mocker.GetMock<IRequestLimitService>();
limitService.Setup(x => x.GetRemainingMusicRequests(It.IsAny<OmbiUser>(), It.IsAny<DateTime>())).ReturnsAsync(new Models.RequestQuotaCountModel
{
HasLimit = true,
Limit = 1,
Remaining = 0
});
var result = await _subject.Execute(new Store.Entities.Requests.BaseRequest
{
RequestType = RequestType.Album
});
Assert.That(result, Is.InstanceOf<RuleResult>().With.Property(nameof(RuleResult.Success)).EqualTo(false));
}
[Test]
public async Task TvRule_No_Limit()
{
var limitService = _mocker.GetMock<IRequestLimitService>();
limitService.Setup(x => x.GetRemainingTvRequests(It.IsAny<OmbiUser>(), It.IsAny<DateTime>())).ReturnsAsync(new Models.RequestQuotaCountModel
{
HasLimit = false
});
var result = await _subject.Execute(new Store.Entities.Requests.BaseRequest
{
RequestType = RequestType.TvShow
});
Assert.That(result, Is.InstanceOf<RuleResult>().With.Property(nameof(RuleResult.Success)).EqualTo(true));
}
[Test]
public async Task TvRule_Limit_NotReached()
{
var limitService = _mocker.GetMock<IRequestLimitService>();
limitService.Setup(x => x.GetRemainingTvRequests(It.IsAny<OmbiUser>(), It.IsAny<DateTime>())).ReturnsAsync(new Models.RequestQuotaCountModel
{
HasLimit = true,
Limit = 2,
Remaining = 1
});
var result = await _subject.Execute(new ChildRequests
{
RequestType = RequestType.TvShow,
SeasonRequests = new List<SeasonRequests>
{
new SeasonRequests
{
Episodes = new List<EpisodeRequests>
{
new EpisodeRequests()
}
}
}
});
Assert.That(result, Is.InstanceOf<RuleResult>().With.Property(nameof(RuleResult.Success)).EqualTo(true));
}
[Test]
public async Task TvRule_Limit_Reached()
{
var limitService = _mocker.GetMock<IRequestLimitService>();
limitService.Setup(x => x.GetRemainingTvRequests(It.IsAny<OmbiUser>(), It.IsAny<DateTime>())).ReturnsAsync(new Models.RequestQuotaCountModel
{
HasLimit = true,
Limit = 1,
Remaining = 0
});
var result = await _subject.Execute(new ChildRequests
{
RequestType = RequestType.TvShow,
SeasonRequests = new List<SeasonRequests>
{
new SeasonRequests
{
Episodes = new List<EpisodeRequests>
{
new EpisodeRequests()
}
}
}
});
Assert.That(result, Is.InstanceOf<RuleResult>().With.Property(nameof(RuleResult.Success)).EqualTo(false));
}
[Test]
public async Task TvRule_Limit_Reached_ManyEpisodes()
{
var limitService = _mocker.GetMock<IRequestLimitService>();
limitService.Setup(x => x.GetRemainingTvRequests(It.IsAny<OmbiUser>(), It.IsAny<DateTime>())).ReturnsAsync(new Models.RequestQuotaCountModel
{
HasLimit = true,
Limit = 1,
Remaining = 5
});
var result = await _subject.Execute(new ChildRequests
{
RequestType = RequestType.TvShow,
SeasonRequests = new List<SeasonRequests>
{
new SeasonRequests
{
Episodes = new List<EpisodeRequests>
{
new EpisodeRequests(),
new EpisodeRequests(),
new EpisodeRequests(),
}
},
new SeasonRequests
{
Episodes = new List<EpisodeRequests>
{
new EpisodeRequests(),
new EpisodeRequests(),
new EpisodeRequests(),
}
}
}
});
Assert.That(result, Is.InstanceOf<RuleResult>().With.Property(nameof(RuleResult.Success)).EqualTo(false));
}
}
}

@ -22,7 +22,6 @@ namespace Ombi.Core.Engine
Task<RequestEngineResult> RequestAlbum(MusicAlbumRequestViewModel model);
Task<IEnumerable<AlbumRequest>> SearchAlbumRequest(string search);
Task<bool> UserHasRequest(string userId);
Task<RequestQuotaCountModel> GetRemainingRequests(OmbiUser user = null);
Task<RequestsViewModel<AlbumRequest>> GetRequestsByStatus(int count, int position, string sort, string sortOrder, RequestStatus available);
Task<RequestsViewModel<AlbumRequest>> GetRequests(int count, int position, string sort, string sortOrder);
}

@ -35,7 +35,7 @@ namespace Ombi.Core.Engine.Interfaces
return null;
}
var username = Username.ToUpper();
return _user ?? (_user = await UserManager.Users.FirstOrDefaultAsync(x => x.NormalizedUserName == username));
return _user ??= await UserManager.Users.FirstOrDefaultAsync(x => x.NormalizedUserName == username);
}
protected async Task<string> UserAlias()

@ -24,7 +24,6 @@ namespace Ombi.Core.Engine.Interfaces
Task<int> GetTotal();
Task UnSubscribeRequest(int requestId, RequestType type);
Task SubscribeToRequest(int requestId, RequestType type);
Task<RequestQuotaCountModel> GetRemainingRequests(OmbiUser user = null);
Task<RequestEngineResult> ReProcessRequest(int requestId, CancellationToken cancellationToken);
}
}

@ -120,11 +120,13 @@ namespace Ombi.Core.Engine
?.FirstOrDefault(x => x.Type == ReleaseDateType.Digital)?.ReleaseDate;
var ruleResults = (await RunRequestRules(requestModel)).ToList();
if (ruleResults.Any(x => !x.Success))
var ruleResultInError = ruleResults.Find(x => !x.Success);
if (ruleResultInError != null)
{
return new RequestEngineResult
{
ErrorMessage = ruleResults.FirstOrDefault(x => x.Message.HasValue()).Message
ErrorMessage = ruleResultInError.Message,
ErrorCode = ruleResultInError.ErrorCode
};
}
@ -566,14 +568,15 @@ namespace Ombi.Core.Engine
{
var langCode = await DefaultLanguageCode(null);
var collections = await Cache.GetOrAddAsync($"GetCollection{collectionId}{langCode}",
() => MovieApi.GetCollection(langCode, collectionId, cancellationToken), DateTimeOffset.Now.AddDays(1));
() => MovieApi.GetCollection(langCode, collectionId, cancellationToken), DateTimeOffset.Now.AddDays(1));
var results = new List<RequestEngineResult>();
foreach (var collection in collections.parts)
{
results.Add(await RequestMovie(new MovieRequestViewModel
{
TheMovieDbId = collection.id
TheMovieDbId = collection.id,
LanguageCode = langCode
}));
}
@ -583,7 +586,7 @@ namespace Ombi.Core.Engine
new RequestEngineResult { Result = false, ErrorMessage = $"The whole collection {collections.name} Is already monitored or requested!" };
}
return new RequestEngineResult { Result = true, Message = $"The collection {collections.name} has been successfully added!", RequestId = results.FirstOrDefault().RequestId};
return new RequestEngineResult { Result = true, Message = $"The collection {collections.name} has been successfully added!", RequestId = results.FirstOrDefault().RequestId };
}
private async Task<RequestEngineResult> ProcessSendingMovie(MovieRequests request)
@ -753,49 +756,5 @@ namespace Ombi.Core.Engine
return new RequestEngineResult { Result = true, Message = $"{movieName} has been successfully added!", RequestId = model.Id };
}
public async Task<RequestQuotaCountModel> GetRemainingRequests(OmbiUser user)
{
if (user == null)
{
user = await GetUser();
// If user is still null after attempting to get the logged in user, return null.
if (user == null)
{
return null;
}
}
int limit = user.MovieRequestLimit ?? 0;
if (limit <= 0)
{
return new RequestQuotaCountModel()
{
HasLimit = false,
Limit = 0,
Remaining = 0,
NextRequest = DateTime.Now,
};
}
IQueryable<RequestLog> log = _requestLog.GetAll().Where(x => x.UserId == user.Id && x.RequestType == RequestType.Movie);
int count = limit - await log.CountAsync(x => x.RequestDate >= DateTime.UtcNow.AddDays(-7));
DateTime oldestRequestedAt = await log.Where(x => x.RequestDate >= DateTime.UtcNow.AddDays(-7))
.OrderBy(x => x.RequestDate)
.Select(x => x.RequestDate)
.FirstOrDefaultAsync();
return new RequestQuotaCountModel()
{
HasLimit = true,
Limit = limit,
Remaining = count,
NextRequest = DateTime.SpecifyKind(oldestRequestedAt.AddDays(7), DateTimeKind.Utc),
};
}
}
}

@ -435,49 +435,6 @@ namespace Ombi.Core.Engine
Result = true
};
}
public async Task<RequestQuotaCountModel> GetRemainingRequests(OmbiUser user)
{
if (user == null)
{
user = await GetUser();
// If user is still null after attempting to get the logged in user, return null.
if (user == null)
{
return null;
}
}
int limit = user.MusicRequestLimit ?? 0;
if (limit <= 0)
{
return new RequestQuotaCountModel()
{
HasLimit = false,
Limit = 0,
Remaining = 0,
NextRequest = DateTime.Now,
};
}
IQueryable<RequestLog> log = _requestLog.GetAll().Where(x => x.UserId == user.Id && x.RequestType == RequestType.Album);
int count = limit - await log.CountAsync(x => x.RequestDate >= DateTime.UtcNow.AddDays(-7));
DateTime oldestRequestedAt = await log.Where(x => x.RequestDate >= DateTime.UtcNow.AddDays(-7))
.OrderBy(x => x.RequestDate)
.Select(x => x.RequestDate)
.FirstOrDefaultAsync();
return new RequestQuotaCountModel()
{
HasLimit = true,
Limit = limit,
Remaining = count,
NextRequest = DateTime.SpecifyKind(oldestRequestedAt.AddDays(7), DateTimeKind.Utc),
};
}
public async Task<RequestEngineResult> MarkAvailable(int modelId)
{

@ -1,4 +1,7 @@
namespace Ombi.Core.Engine
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Ombi.Core.Engine
{
public class RequestEngineResult
{
@ -6,6 +9,23 @@
public string Message { get; set; }
public bool IsError => !string.IsNullOrEmpty(ErrorMessage);
public string ErrorMessage { get; set; }
public ErrorCode? ErrorCode { get; set; }
public int RequestId { get; set; }
}
[JsonConverter(typeof(StringEnumConverter))]
public enum ErrorCode {
AlreadyRequested,
EpisodesAlreadyRequested,
NoPermissionsOnBehalf,
NoPermissions,
RequestDoesNotExist,
ChildRequestDoesNotExist,
NoPermissionsRequestMovie,
NoPermissionsRequestTV,
NoPermissionsRequestAlbum,
MovieRequestQuotaExceeded,
TvRequestQuotaExceeded,
AlbumRequestQuotaExceeded,
}
}

@ -144,6 +144,7 @@ namespace Ombi.Core.Engine
return new RequestEngineResult
{
Result = false,
ErrorCode = ErrorCode.AlreadyRequested,
ErrorMessage = "This has already been requested"
};
}
@ -166,6 +167,7 @@ namespace Ombi.Core.Engine
return new RequestEngineResult
{
Result = false,
ErrorCode = ErrorCode.NoPermissionsOnBehalf,
Message = "You do not have the correct permissions to request on behalf of users!",
ErrorMessage = $"You do not have the correct permissions to request on behalf of users!"
};
@ -176,6 +178,7 @@ namespace Ombi.Core.Engine
return new RequestEngineResult
{
Result = false,
ErrorCode = ErrorCode.NoPermissions,
Message = "You do not have the correct permissions!",
ErrorMessage = $"You do not have the correct permissions!"
};
@ -183,7 +186,7 @@ namespace Ombi.Core.Engine
var tvBuilder = new TvShowRequestBuilderV2(MovieDbApi);
(await tvBuilder
.GetShowInfo(tv.TheMovieDbId))
.GetShowInfo(tv.TheMovieDbId, tv.languageCode))
.CreateTvList(tv)
.CreateChild(tv, canRequestOnBehalf ? tv.RequestOnBehalf : user.Id);
@ -250,6 +253,7 @@ namespace Ombi.Core.Engine
return new RequestEngineResult
{
Result = false,
ErrorCode = ErrorCode.AlreadyRequested,
ErrorMessage = "This has already been requested"
};
}
@ -685,6 +689,7 @@ namespace Ombi.Core.Engine
{
return new RequestEngineResult
{
ErrorCode = ErrorCode.ChildRequestDoesNotExist,
ErrorMessage = "Child Request does not exist"
};
}
@ -722,6 +727,7 @@ namespace Ombi.Core.Engine
{
return new RequestEngineResult
{
ErrorCode = ErrorCode.ChildRequestDoesNotExist,
ErrorMessage = "Child Request does not exist"
};
}
@ -781,6 +787,7 @@ namespace Ombi.Core.Engine
{
return new RequestEngineResult
{
ErrorCode = ErrorCode.ChildRequestDoesNotExist,
ErrorMessage = "Child Request does not exist"
};
}
@ -808,6 +815,7 @@ namespace Ombi.Core.Engine
{
return new RequestEngineResult
{
ErrorCode = ErrorCode.ChildRequestDoesNotExist,
ErrorMessage = "Child Request does not exist"
};
}
@ -905,6 +913,7 @@ namespace Ombi.Core.Engine
return new RequestEngineResult
{
Result = false,
ErrorCode = ErrorCode.RequestDoesNotExist,
ErrorMessage = "Request does not exist"
};
}
@ -955,56 +964,7 @@ namespace Ombi.Core.Engine
return new RequestEngineResult { Result = true, RequestId = model.Id };
}
public async Task<RequestQuotaCountModel> GetRemainingRequests(OmbiUser user)
{
if (user == null)
{
user = await GetUser();
// If user is still null after attempting to get the logged in user, return null.
if (user == null)
{
return null;
}
}
int limit = user.EpisodeRequestLimit ?? 0;
if (limit <= 0)
{
return new RequestQuotaCountModel()
{
HasLimit = false,
Limit = 0,
Remaining = 0,
NextRequest = DateTime.Now,
};
}
IQueryable<RequestLog> log = _requestLog.GetAll()
.Where(x => x.UserId == user.Id
&& x.RequestType == RequestType.TvShow
&& x.RequestDate >= DateTime.UtcNow.AddDays(-7));
// Needed, due to a bug which would cause all episode counts to be 0
int zeroEpisodeCount = await log.Where(x => x.EpisodeCount == 0).Select(x => x.EpisodeCount).CountAsync();
int episodeCount = await log.Where(x => x.EpisodeCount != 0).Select(x => x.EpisodeCount).SumAsync();
int count = limit - (zeroEpisodeCount + episodeCount);
DateTime oldestRequestedAt = await log.OrderBy(x => x.RequestDate)
.Select(x => x.RequestDate)
.FirstOrDefaultAsync();
return new RequestQuotaCountModel()
{
HasLimit = true,
Limit = limit,
Remaining = count,
NextRequest = DateTime.SpecifyKind(oldestRequestedAt.AddDays(7), DateTimeKind.Utc),
};
}
public async Task<RequestEngineResult> UpdateAdvancedOptions(MediaAdvancedOptions options)
{
@ -1014,6 +974,7 @@ namespace Ombi.Core.Engine
return new RequestEngineResult
{
Result = false,
ErrorCode = ErrorCode.RequestDoesNotExist,
ErrorMessage = "Request does not exist"
};
}

@ -30,9 +30,9 @@ namespace Ombi.Core.Helpers
public TvRequests NewRequest { get; protected set; }
protected TvInfo TheMovieDbRecord { get; set; }
public async Task<TvShowRequestBuilderV2> GetShowInfo(int id)
public async Task<TvShowRequestBuilderV2> GetShowInfo(int id, string langCode = "en")
{
TheMovieDbRecord = await MovieDbApi.GetTVInfo(id.ToString());
TheMovieDbRecord = await MovieDbApi.GetTVInfo(id.ToString(), langCode);
// Remove 'Specials Season'
var firstSeason = TheMovieDbRecord.seasons.OrderBy(x => x.season_number).FirstOrDefault();

@ -6,5 +6,6 @@ namespace Ombi.Core.Models.Requests
public class TvRequestViewModelV2 : TvRequestViewModelBase
{
public int TheMovieDbId { get; set; }
public string languageCode { get; set; } = "en";
}
}

@ -24,6 +24,9 @@ namespace Ombi.Core.Models.UI
public RequestQuotaCountModel MusicRequestQuota { get; set; }
public int MusicRequestLimit { get; set; }
public UserQualityProfiles UserQualityProfiles { get; set; }
public RequestLimitType MovieRequestLimitType { get; set; }
public RequestLimitType MusicRequestLimitType { get; set; }
public RequestLimitType EpisodeRequestLimitType { get; set; }
}
public class ClaimCheckboxes

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -1,4 +1,5 @@
namespace Ombi.Core.Rule
using Ombi.Core.Engine;
namespace Ombi.Core.Rule
{
public abstract class BaseRequestRule
{
@ -7,9 +8,9 @@
return new RuleResult {Success = true};
}
public RuleResult Fail(string message)
public RuleResult Fail(ErrorCode errorCode, string message = "")
{
return new RuleResult { Message = message };
return new RuleResult { ErrorCode = errorCode, Message = message };
}
}
}

@ -1,8 +1,10 @@
namespace Ombi.Core.Rule
using Ombi.Core.Engine;
namespace Ombi.Core.Rule
{
public class RuleResult
{
public bool Success { get; set; }
public string Message { get; set; }
public ErrorCode ErrorCode { get; set; }
}
}

@ -6,6 +6,7 @@ using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Ombi.Core.Authentication;
using Ombi.Core.Engine;
using Ombi.Core.Rule.Interfaces;
using Ombi.Helpers;
using Ombi.Store.Entities.Requests;
@ -34,7 +35,7 @@ namespace Ombi.Core.Rule.Rules.Request
{
if (await _manager.IsInRoleAsync(user, OmbiRoles.RequestMovie) || await _manager.IsInRoleAsync(user, OmbiRoles.AutoApproveMovie))
return Success();
return Fail("You do not have permissions to Request a Movie");
return Fail(ErrorCode.NoPermissionsRequestMovie, "You do not have permissions to Request a Movie");
}
if (obj.RequestType == RequestType.TvShow)
@ -44,7 +45,7 @@ namespace Ombi.Core.Rule.Rules.Request
return Success();
}
return Fail("You do not have permissions to Request a TV Show");
return Fail(ErrorCode.NoPermissionsRequestTV, "You do not have permissions to Request a TV Show");
}
if (obj.RequestType == RequestType.Album)
@ -54,7 +55,7 @@ namespace Ombi.Core.Rule.Rules.Request
return Success();
}
return Fail("You do not have permissions to Request an Album");
return Fail(ErrorCode.NoPermissionsRequestAlbum, "You do not have permissions to Request an Album");
}
throw new InvalidDataException("Permission check failed: unknown RequestType");

@ -6,6 +6,7 @@ using Ombi.Helpers;
using Ombi.Store.Entities;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository;
using Ombi.Core.Engine;
using Ombi.Store.Repository.Requests;
namespace Ombi.Core.Rule.Rules.Request
@ -49,7 +50,7 @@ namespace Ombi.Core.Rule.Rules.Request
}
if(found)
{
return Fail($"\"{obj.Title}\" has already been requested");
return Fail(ErrorCode.AlreadyRequested, $"\"{obj.Title}\" has already been requested");
}
}
return Success();

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Ombi.Core.Engine;
using Ombi.Core.Rule.Interfaces;
using Ombi.Store.Entities;
using Ombi.Store.Entities.Requests;
@ -87,7 +88,7 @@ namespace Ombi.Core.Rule.Rules.Request
if (!anyEpisodes)
{
return Fail($"We already have episodes requested from series {child.Title}");
return Fail(ErrorCode.EpisodesAlreadyRequested, $"We already have episodes requested from series {child.Title}");
}
return Success();

@ -3,6 +3,7 @@ using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Ombi.Core.Rule.Interfaces;
using Ombi.Core.Engine;
using Ombi.Store.Entities;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository.Requests;
@ -63,7 +64,7 @@ namespace Ombi.Core.Rule.Rules.Request
if (!anyEpisodes)
{
return Fail($"We already have episodes requested from series {tv.Title}");
return Fail(ErrorCode.EpisodesAlreadyRequested, $"We already have episodes requested from series {tv.Title}");
}
}

@ -25,59 +25,47 @@
// ************************************************************************/
#endregion
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Ombi.Core.Authentication;
using Ombi.Core.Rule.Interfaces;
using Ombi.Core.Services;
using Ombi.Store.Entities;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository;
namespace Ombi.Core.Rule.Rules.Request
{
public class RequestLimitRule : BaseRequestRule, IRules<BaseRequest>
{
public RequestLimitRule(IRepository<RequestLog> rl, OmbiUserManager um)
public RequestLimitRule(IRequestLimitService requestLimitService)
{
_requestLog = rl;
_userManager = um;
_requestLimitService = requestLimitService;
}
private readonly IRepository<RequestLog> _requestLog;
private readonly OmbiUserManager _userManager;
private readonly IRequestLimitService _requestLimitService;
public async Task<RuleResult> Execute(BaseRequest obj)
{
var user = await _userManager.Users.FirstOrDefaultAsync(x => x.Id == obj.RequestedUserId);
var movieLimit = user.MovieRequestLimit;
var episodeLimit = user.EpisodeRequestLimit;
var musicLimit = user.MusicRequestLimit;
var requestLog = _requestLog.GetAll().Where(x => x.UserId == obj.RequestedUserId);
if (obj.RequestType == RequestType.Movie)
{
if (movieLimit <= 0)
var remainingLimitsModel = await _requestLimitService.GetRemainingMovieRequests();
if (!remainingLimitsModel.HasLimit)
{
return Success();
var movieLogs = requestLog.Where(x => x.RequestType == RequestType.Movie);
// Count how many requests in the past 7 days
var count = await movieLogs.CountAsync(x => x.RequestDate >= DateTime.UtcNow.AddDays(-7));
count += 1; // Since we are including this request
if (count > movieLimit)
}
if (remainingLimitsModel.Remaining < 1)
{
return Fail("You have exceeded your Movie request quota!");
return Fail(Engine.ErrorCode.MovieRequestQuotaExceeded, "You have exceeded your Movie request quota!");
}
}
else if (obj.RequestType == RequestType.TvShow)
if (obj.RequestType == RequestType.TvShow)
{
if (episodeLimit <= 0)
var remainingLimitsModel = await _requestLimitService.GetRemainingTvRequests();
if (!remainingLimitsModel.HasLimit)
{
return Success();
var child = (ChildRequests) obj;
}
var child = (ChildRequests)obj;
var requestCount = 0;
// Get the count of requests to be made
foreach (var s in child.SeasonRequests)
@ -85,37 +73,25 @@ namespace Ombi.Core.Rule.Rules.Request
requestCount += s.Episodes.Count;
}
var tvLogs = requestLog.Where(x => x.RequestType == RequestType.TvShow);
// Count how many requests in the past 7 days
var tv = tvLogs.Where(x => x.RequestDate >= DateTime.UtcNow.AddDays(-7));
// Needed, due to a bug which would cause all episode counts to be 0
var zeroEpisodeCount = await tv.Where(x => x.EpisodeCount == 0).Select(x => x.EpisodeCount).CountAsync();
var episodeCount = await tv.Where(x => x.EpisodeCount != 0).Select(x => x.EpisodeCount).SumAsync();
var count = requestCount + episodeCount + zeroEpisodeCount; // Add the amount of requests in
if (count > episodeLimit)
if ((remainingLimitsModel.Remaining - requestCount) < 0)
{
return Fail("You have exceeded your Episode request quota!");
return Fail(Engine.ErrorCode.TvRequestQuotaExceeded, "You have exceeded your Episode request quota!");
}
} else if (obj.RequestType == RequestType.Album)
}
if (obj.RequestType == RequestType.Album)
{
if (musicLimit <= 0)
var remainingLimitsModel = await _requestLimitService.GetRemainingMusicRequests();
if (!remainingLimitsModel.HasLimit)
{
return Success();
}
var albumLogs = requestLog.Where(x => x.RequestType == RequestType.Album);
// Count how many requests in the past 7 days
var count = await albumLogs.CountAsync(x => x.RequestDate >= DateTime.UtcNow.AddDays(-7));
count += 1; // Since we are including this request
if (count > musicLimit)
if (remainingLimitsModel.Remaining < 1)
{
return Fail("You have exceeded your Album request quota!");
return Fail(Engine.ErrorCode.AlbumRequestQuotaExceeded, "You have exceeded your Album request quota!");
}
}
return Success();
return Success();
}
}
}

@ -75,6 +75,7 @@ namespace Ombi.Core.Rule.Rules.Search
episodeSearching.Requested = true;
episodeSearching.Available = ep.Available;
episodeSearching.Approved = ep.Season.ChildRequest.Approved;
episodeSearching.Denied = request.Denied;
}
}
}

@ -3,6 +3,8 @@ using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Ombi.Core.Models.Search;
using Ombi.Core.Rule.Interfaces;
using Ombi.Core.Settings;
using Ombi.Core.Settings.Models.External;
using Ombi.Helpers;
using Ombi.Store.Entities;
using Ombi.Store.Repository;
@ -11,10 +13,13 @@ namespace Ombi.Core.Rule.Rules.Search
{
public class PlexAvailabilityRule : BaseSearchRule, IRules<SearchViewModel>
{
public PlexAvailabilityRule(IPlexContentRepository repo, ILogger<PlexAvailabilityRule> log)
private readonly ISettingsService<PlexSettings> _plexSettings;
public PlexAvailabilityRule(IPlexContentRepository repo, ILogger<PlexAvailabilityRule> log, ISettingsService<PlexSettings> plexSettings)
{
PlexContentRepository = repo;
Log = log;
_plexSettings = plexSettings;
}
private IPlexContentRepository PlexContentRepository { get; }
@ -72,13 +77,20 @@ namespace Ombi.Core.Rule.Rules.Search
if (item != null)
{
var settings = await _plexSettings.GetSettingsAsync();
var firstServer = settings.Servers.FirstOrDefault();
var host = string.Empty;
if (firstServer != null)
{
host = firstServer.ServerHostname;
}
if (useId)
{
obj.TheMovieDbId = obj.Id.ToString();
useTheMovieDb = true;
}
obj.Available = true;
obj.PlexUrl = item.Url;
obj.PlexUrl = PlexHelper.BuildPlexMediaUrl(item.Url, host);
obj.Quality = item.Quality;
if (obj.Type == RequestType.TvShow)

@ -2,6 +2,7 @@
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Ombi.Core.Engine;
using Ombi.Core.Models.Search;
using Ombi.Helpers;
using Ombi.Store.Context;
@ -56,7 +57,7 @@ namespace Ombi.Core.Rule.Rules
if (!anyEpisodes)
{
return new RuleResult { Message = $"We already have episodes requested from series {vm.Title}" };
return new RuleResult { ErrorCode = ErrorCode.EpisodesAlreadyRequested, Message = $"We already have episodes requested from series {vm.Title}" };
}
}
}

@ -1,4 +1,5 @@
using Ombi.Core.Rule.Interfaces;
using Ombi.Core.Engine;
using Ombi.Core.Rule.Interfaces;
namespace Ombi.Core.Rule
{
@ -9,9 +10,9 @@ namespace Ombi.Core.Rule
return new RuleResult { Success = true };
}
public RuleResult Fail(string message)
public RuleResult Fail(ErrorCode errorCode, string message = "")
{
return new RuleResult { Message = message };
return new RuleResult { ErrorCode = errorCode, Message = message };
}
public abstract SpecificRules Rule { get; }

@ -0,0 +1,313 @@
using Microsoft.EntityFrameworkCore;
using Ombi.Core.Authentication;
using Ombi.Core.Models;
using Ombi.Helpers;
using Ombi.Store.Entities;
using Ombi.Store.Entities.Requests;
using Ombi.Store.Repository;
using System;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
namespace Ombi.Core.Services
{
public interface IRequestLimitService
{
Task<RequestQuotaCountModel> GetRemainingMovieRequests(OmbiUser user = default, DateTime now = default);
Task<RequestQuotaCountModel> GetRemainingTvRequests(OmbiUser user = default, DateTime now = default);
Task<RequestQuotaCountModel> GetRemainingMusicRequests(OmbiUser user = default, DateTime now = default);
}
public class RequestLimitService : IRequestLimitService
{
private readonly IPrincipal _user;
private readonly OmbiUserManager _userManager;
private readonly IRepository<RequestLog> _requestLog;
public RequestLimitService(IPrincipal user, OmbiUserManager userManager, IRepository<RequestLog> rl)
{
_user = user;
_userManager = userManager;
_requestLog = rl;
}
public async Task<RequestQuotaCountModel> GetRemainingMovieRequests(OmbiUser user, DateTime now = default)
{
if (now == default)
{
now = DateTime.UtcNow;
}
if (user == null)
{
user = await GetUser();
// If user is still null after attempting to get the logged in user, return null.
if (user == null)
{
return null;
}
}
int limit = user.MovieRequestLimit ?? 0;
if (limit <= 0)
{
return new RequestQuotaCountModel()
{
HasLimit = false,
Limit = 0,
Remaining = 0,
NextRequest = DateTime.Now,
};
}
IQueryable<RequestLog> log = _requestLog.GetAll().Where(x => x.UserId == user.Id && x.RequestType == RequestType.Movie);
if (!user.MovieRequestLimitType.HasValue)
{
var count = limit - await log.CountAsync(x => x.RequestDate >= DateTime.UtcNow.AddDays(-7));
var oldestRequestedAt = await log.Where(x => x.RequestDate >= DateTime.UtcNow.AddDays(-7))
.OrderBy(x => x.RequestDate)
.Select(x => x.RequestDate)
.FirstOrDefaultAsync();
return new RequestQuotaCountModel()
{
HasLimit = true,
Limit = limit,
Remaining = count < 0 ? 0 : count,
NextRequest = DateTime.SpecifyKind(oldestRequestedAt.AddDays(7), DateTimeKind.Utc),
};
}
return await CalculateBasicRemaingRequests(user, limit, user.MovieRequestLimitType ?? RequestLimitType.Day, log, now);
}
public async Task<RequestQuotaCountModel> GetRemainingMusicRequests(OmbiUser user, DateTime now = default)
{
if (now == default)
{
now = DateTime.UtcNow;
}
if (user == null)
{
user = await GetUser();
// If user is still null after attempting to get the logged in user, return null.
if (user == null)
{
return null;
}
}
int limit = user.MusicRequestLimit ?? 0;
if (limit <= 0)
{
return new RequestQuotaCountModel()
{
HasLimit = false,
Limit = 0,
Remaining = 0,
NextRequest = DateTime.Now,
};
}
IQueryable<RequestLog> log = _requestLog.GetAll().Where(x => x.UserId == user.Id && x.RequestType == RequestType.Album);
// Hisoric Limits
if (!user.MusicRequestLimitType.HasValue)
{
var oldcount = limit - await log.CountAsync(x => x.RequestDate >= DateTime.UtcNow.AddDays(-7));
var oldestRequestedAtOld = await log.Where(x => x.RequestDate >= DateTime.UtcNow.AddDays(-7))
.OrderBy(x => x.RequestDate)
.Select(x => x.RequestDate)
.FirstOrDefaultAsync();
return new RequestQuotaCountModel()
{
HasLimit = true,
Limit = limit,
Remaining = oldcount < 0 ? 0 : oldcount,
NextRequest = DateTime.SpecifyKind(oldestRequestedAtOld.AddDays(7), DateTimeKind.Utc),
};
}
return await CalculateBasicRemaingRequests(user, limit, user.MusicRequestLimitType ?? RequestLimitType.Day, log, now);
}
private async Task<OmbiUser> GetUser()
{
var username = _user.Identity.Name.ToUpper();
return await _userManager.Users.FirstOrDefaultAsync(x => x.NormalizedUserName == username);
}
private static async Task<RequestQuotaCountModel> CalculateBasicRemaingRequests(OmbiUser user, int limit, RequestLimitType type, IQueryable<RequestLog> log, DateTime now)
{
int count = 0;
DateTime oldestRequestedAt = DateTime.Now;
DateTime nextRequest = DateTime.Now;
switch (type)
{
case RequestLimitType.Day:
count = limit - await log.CountAsync(x => x.RequestDate >= now.Date);
oldestRequestedAt = await log.Where(x => x.RequestDate >= now.Date)
.OrderBy(x => x.RequestDate)
.Select(x => x.RequestDate)
.FirstOrDefaultAsync();
nextRequest = oldestRequestedAt.AddDays(1).Date;
break;
case RequestLimitType.Week:
var fdow = now.FirstDateInWeek().Date;
count = limit - await log.CountAsync(x => x.RequestDate >= fdow);
oldestRequestedAt = await log.Where(x => x.RequestDate >= fdow)
.OrderBy(x => x.RequestDate)
.Select(x => x.RequestDate)
.FirstOrDefaultAsync();
nextRequest = fdow.AddDays(7).Date;
break;
case RequestLimitType.Month:
var firstDayOfMonth = new DateTime(now.Year, now.Month, 1);
count = limit - await log.CountAsync(x => x.RequestDate >= firstDayOfMonth);
oldestRequestedAt = await log.Where(x => x.RequestDate >= firstDayOfMonth)
.OrderBy(x => x.RequestDate)
.Select(x => x.RequestDate)
.FirstOrDefaultAsync();
nextRequest = firstDayOfMonth.AddMonths(1).Date;
break;
}
return new RequestQuotaCountModel()
{
HasLimit = true,
Limit = limit,
Remaining = count < 0 ? 0 : count,
NextRequest = DateTime.SpecifyKind(nextRequest, DateTimeKind.Utc),
};
}
public async Task<RequestQuotaCountModel> GetRemainingTvRequests(OmbiUser user, DateTime now = default)
{
if (now == default)
{
now = DateTime.UtcNow;
}
if (user == null)
{
user = await GetUser();
// If user is still null after attempting to get the logged in user, return null.
if (user == null)
{
return null;
}
}
int limit = user.EpisodeRequestLimit ?? 0;
if (limit <= 0)
{
return new RequestQuotaCountModel()
{
HasLimit = false,
Limit = 0,
Remaining = 0,
NextRequest = DateTime.Now,
};
}
IQueryable<RequestLog> log = _requestLog.GetAll().Where(x => x.UserId == user.Id && x.RequestType == RequestType.TvShow);
int count = 0;
DateTime oldestRequestedAt = DateTime.Now;
DateTime nextRequest = DateTime.Now;
IQueryable<RequestLog> filteredLog;
int zeroEpisodeCount;
int episodeCount;
if (!user.EpisodeRequestLimitType.HasValue)
{
filteredLog = log.Where(x => x.RequestDate >= DateTime.UtcNow.AddDays(-7));
// Needed, due to a bug which would cause all episode counts to be 0
zeroEpisodeCount = await filteredLog.Where(x => x.EpisodeCount == 0).Select(x => x.EpisodeCount).CountAsync();
episodeCount = await filteredLog.Where(x => x.EpisodeCount != 0).Select(x => x.EpisodeCount).SumAsync();
count = limit - (zeroEpisodeCount + episodeCount);
oldestRequestedAt = await log
.Where(x => x.RequestDate >= now.AddDays(-7))
.OrderBy(x => x.RequestDate)
.Select(x => x.RequestDate)
.FirstOrDefaultAsync();
return new RequestQuotaCountModel()
{
HasLimit = true,
Limit = limit,
Remaining = count < 0 ? 0 : count,
NextRequest = DateTime.SpecifyKind(oldestRequestedAt.AddDays(7), DateTimeKind.Utc).Date,
};
}
switch (user.EpisodeRequestLimitType)
{
case RequestLimitType.Day:
filteredLog = log.Where(x => x.RequestDate >= DateTime.UtcNow.Date);
// Needed, due to a bug which would cause all episode counts to be 0
zeroEpisodeCount = await filteredLog.Where(x => x.EpisodeCount == 0).Select(x => x.EpisodeCount).CountAsync();
episodeCount = await filteredLog.Where(x => x.EpisodeCount != 0).Select(x => x.EpisodeCount).SumAsync();
count = limit - (zeroEpisodeCount + episodeCount);
oldestRequestedAt = await log.Where(x => x.RequestDate >= now.Date)
.OrderBy(x => x.RequestDate)
.Select(x => x.RequestDate)
.FirstOrDefaultAsync();
nextRequest = oldestRequestedAt.AddDays(1).Date;
break;
case RequestLimitType.Week:
var fdow = now.FirstDateInWeek().Date;
filteredLog = log.Where(x => x.RequestDate >= now.Date.AddDays(-7));
// Needed, due to a bug which would cause all episode counts to be 0
zeroEpisodeCount = await filteredLog.Where(x => x.EpisodeCount == 0).Select(x => x.EpisodeCount).CountAsync();
episodeCount = await filteredLog.Where(x => x.EpisodeCount != 0).Select(x => x.EpisodeCount).SumAsync();
count = limit - (zeroEpisodeCount + episodeCount);
oldestRequestedAt = await log.Where(x => x.RequestDate >= now.Date.AddDays(-7))
.OrderBy(x => x.RequestDate)
.Select(x => x.RequestDate)
.FirstOrDefaultAsync();
nextRequest = fdow.AddDays(7).Date;
break;
case RequestLimitType.Month:
var firstDayOfMonth = new DateTime(now.Year, now.Month, 1);
filteredLog = log.Where(x => x.RequestDate >= now.Date.AddMonths(-1));
// Needed, due to a bug which would cause all episode counts to be 0
zeroEpisodeCount = await filteredLog.Where(x => x.EpisodeCount == 0).Select(x => x.EpisodeCount).CountAsync();
episodeCount = await filteredLog.Where(x => x.EpisodeCount != 0).Select(x => x.EpisodeCount).SumAsync();
count = limit - (zeroEpisodeCount + episodeCount);
oldestRequestedAt = await log.Where(x => x.RequestDate >= now.Date.AddMonths(-1))
.OrderBy(x => x.RequestDate)
.Select(x => x.RequestDate)
.FirstOrDefaultAsync();
nextRequest = firstDayOfMonth.AddMonths(1).Date;
break;
}
return new RequestQuotaCountModel()
{
HasLimit = true,
Limit = limit,
Remaining = count < 0 ? 0 : count,
NextRequest = DateTime.SpecifyKind(nextRequest, DateTimeKind.Utc),
};
}
}
}

@ -69,6 +69,7 @@ using Ombi.Api.CloudService;
using Ombi.Api.RottenTomatoes;
using System.Net.Http;
using Microsoft.Extensions.Logging;
using Ombi.Core.Services;
namespace Ombi.DependencyInjection
{
@ -80,10 +81,10 @@ namespace Ombi.DependencyInjection
services.RegisterEngines();
services.RegisterEnginesV2();
services.RegisterApi();
services.RegisterHttp();
services.RegisterServices();
services.RegisterStore();
services.RegisterJobs();
services.RegisterHttp();
}
public static void RegisterEngines(this IServiceCollection services)
@ -124,7 +125,7 @@ namespace Ombi.DependencyInjection
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IPrincipal>(sp => sp.GetService<IHttpContextAccessor>().HttpContext.User);
services.AddHttpClient("OmbiClient", client =>
{
{
client.DefaultRequestHeaders.Add("User-Agent", $"Ombi/{runtimeVersion} (https://ombi.io/)");
}).ConfigurePrimaryHttpMessageHandler(() =>
{
@ -174,11 +175,12 @@ namespace Ombi.DependencyInjection
services.AddTransient<IRottenTomatoesApi, RottenTomatoesApi>();
}
public static void RegisterStore(this IServiceCollection services) {
public static void RegisterStore(this IServiceCollection services)
{
//services.AddDbContext<OmbiContext>();
//services.AddDbContext<SettingsContext>();
//services.AddDbContext<ExternalContext>();
//services.AddScoped<OmbiContext, OmbiContext>(); // https://docs.microsoft.com/en-us/aspnet/core/data/entity-framework-6
//services.AddScoped<ISettingsContext, SettingsContext>(); // https://docs.microsoft.com/en-us/aspnet/core/data/entity-framework-6
//services.AddScoped<ExternalContext, ExternalContext>(); // https://docs.microsoft.com/en-us/aspnet/core/data/entity-framework-6
@ -188,7 +190,7 @@ namespace Ombi.DependencyInjection
services.AddScoped<IEmbyContentRepository, EmbyContentRepository>();
services.AddScoped<IJellyfinContentRepository, JellyfinContentRepository>();
services.AddScoped<INotificationTemplatesRepository, NotificationTemplatesRepository>();
services.AddScoped<ITvRequestRepository, TvRequestRepository>();
services.AddScoped<IMovieRequestRepository, MovieRequestRepository>();
services.AddScoped<IMusicRequestRepository, MusicRequestRepository>();
@ -208,6 +210,7 @@ namespace Ombi.DependencyInjection
services.AddSingleton<ICacheService, CacheService>();
services.AddSingleton<IMediaCacheService, MediaCacheService>();
services.AddScoped<IImageService, ImageService>();
services.AddScoped<IRequestLimitService, RequestLimitService>();
services.AddTransient<IDiscordNotification, DiscordNotification>();
services.AddTransient<IEmailNotification, EmailNotification>();

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
using System.Threading;
using NUnit.Framework;
using NUnit.Framework.Internal;
namespace Ombi.Helpers.Tests
{
[TestFixture]
public class DateTimeExtensionsTests
{
[TestCaseSource(nameof(DayOfWeekData))]
public DateTime FirstDateInWeekTests(DateTime input, string culture)
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(culture);
return input.FirstDateInWeek();
}
public static IEnumerable<TestCaseData> DayOfWeekData
{
get
{
yield return new TestCaseData(new DateTime(2021, 09, 20), "en-GB").Returns(new DateTime(2021, 09, 20)).SetName("en-GB Monday, FDOW is Monday");
yield return new TestCaseData(new DateTime(2021, 09, 21), "en-GB").Returns(new DateTime(2021, 09, 20)).SetName("en-GB Tuesday, FDOW is Monday");
yield return new TestCaseData(new DateTime(2021, 09, 22), "en-GB").Returns(new DateTime(2021, 09, 20)).SetName("en-GB Wednesday, FDOW is Monday");
yield return new TestCaseData(new DateTime(2021, 09, 23), "en-GB").Returns(new DateTime(2021, 09, 20)).SetName("en-GB Thursday, FDOW is Monday");
yield return new TestCaseData(new DateTime(2021, 09, 24), "en-GB").Returns(new DateTime(2021, 09, 20)).SetName("en-GB Friday, FDOW is Monday");
yield return new TestCaseData(new DateTime(2021, 09, 25), "en-GB").Returns(new DateTime(2021, 09, 20)).SetName("en-GB Sat, FDOW is Monday");
yield return new TestCaseData(new DateTime(2021, 09, 26), "en-GB").Returns(new DateTime(2021, 09, 20)).SetName("en-GB Sun, FDOW is Monday");
yield return new TestCaseData(new DateTime(2021, 09, 20), "en-US").Returns(new DateTime(2021, 09, 19)).SetName("en-US Monday, FDOW is Sunday");
yield return new TestCaseData(new DateTime(2021, 09, 21), "en-US").Returns(new DateTime(2021, 09, 19)).SetName("en-US Tuesday, FDOW is Sunday");
yield return new TestCaseData(new DateTime(2021, 09, 22), "en-US").Returns(new DateTime(2021, 09, 19)).SetName("en-US Wednesday, FDOW is Sunday");
yield return new TestCaseData(new DateTime(2021, 09, 23), "en-US").Returns(new DateTime(2021, 09, 19)).SetName("en-US Thursday, FDOW is Sunday");
yield return new TestCaseData(new DateTime(2021, 09, 24), "en-US").Returns(new DateTime(2021, 09, 19)).SetName("en-US Friday, FDOW is Sunday");
yield return new TestCaseData(new DateTime(2021, 09, 25), "en-US").Returns(new DateTime(2021, 09, 19)).SetName("en-US Sat, FDOW is Sunday");
yield return new TestCaseData(new DateTime(2021, 09, 26), "en-US").Returns(new DateTime(2021, 09, 26)).SetName("en-US Sun, FDOW is Sunday");
}
}
}
}

@ -4,6 +4,8 @@
<TargetFramework>net5.0</TargetFramework>
<IsPackable>false</IsPackable>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -76,6 +76,29 @@ namespace Ombi.Helpers.Tests
}
}
[TestCaseSource(nameof(PlexBuildUrlData))]
public string BuildPlexMediaUrlTest(string saved, string hostname)
{
return PlexHelper.BuildPlexMediaUrl(saved, hostname);
}
public static IEnumerable<TestCaseData> PlexBuildUrlData
{
get
{
yield return new TestCaseData("web/#!/server/df5", "https://myhost.com/").Returns("https://myhost.com/web/#!/server/df5");
yield return new TestCaseData("web/#!/server/df5", "").Returns("https://app.plex.tv/web/#!/server/df5");
yield return new TestCaseData("web/#!/server/df5", "https://myhost.com").Returns("https://myhost.com/web/#!/server/df5");
yield return new TestCaseData("web/#!/server/df5", "http://myhost.com").Returns("http://myhost.com/web/#!/server/df5");
yield return new TestCaseData("web/#!/server/df5", "http://www.myhost.com").Returns("http://www.myhost.com/web/#!/server/df5");
yield return new TestCaseData("web/#!/server/df5", "http://www.myhost.com:3456").Returns("http://www.myhost.com:3456/web/#!/server/df5").SetName("PortTest");
yield return new TestCaseData("https://app.plex.tv/web/#!/server/df5", "http://www.myhost.com:3456").Returns("http://www.myhost.com:3456/web/#!/server/df5");
yield return new TestCaseData("https://app.plex.tv/web/#!/server/df5", "https://tidusjar.com:3456").Returns("https://tidusjar.com:3456/web/#!/server/df5");
yield return new TestCaseData("https://app.plex.tv/web/#!/server/df5", "").Returns("https://app.plex.tv/web/#!/server/df5").SetName("OldUrl_BlankHost");
}
}
public enum ProviderIdType
{
Imdb,

@ -0,0 +1,18 @@
using System;
using System.Threading;
namespace Ombi.Helpers
{
public static class DateTimeExtensions
{
public static DateTime FirstDateInWeek(this DateTime dt)
{
while (dt.DayOfWeek != Thread.CurrentThread.CurrentCulture.DateTimeFormat.FirstDayOfWeek)
{
dt = dt.AddDays(-1);
}
return dt;
}
}
}

@ -32,7 +32,7 @@ namespace Ombi.Helpers
}
// Not in the cache, so add this Key into our MediaServiceCache
await UpdateLocalCache(cacheKey);
UpdateLocalCache(cacheKey);
return await _memoryCache.GetOrCreateAsync<T>(cacheKey, entry =>
{
@ -41,7 +41,7 @@ namespace Ombi.Helpers
});
}
private async Task UpdateLocalCache(string cacheKey)
private void UpdateLocalCache(string cacheKey)
{
var mediaServiceCache = _memoryCache.Get<List<string>>(CacheKey);
if (mediaServiceCache == null)

@ -14,5 +14,6 @@
IssueResolved = 9,
IssueComment = 10,
Newsletter = 11,
PartiallyAvailable = 12
}
}

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -107,10 +107,40 @@ namespace Ombi.Helpers
public static string GetPlexMediaUrl(string machineId, int mediaId)
{
var url =
$"https://app.plex.tv/web/app#!/server/{machineId}/details?key=%2flibrary%2Fmetadata%2F{mediaId}";
$"web/#!/server/{machineId}/details?key=%2flibrary%2Fmetadata%2F{mediaId}";
return url;
}
public static string BuildPlexMediaUrl(string savedUrl, string plexHost)
{
if (savedUrl.Contains("app.plex.tv"))
{
var split = savedUrl.Split("https://app.plex.tv/", StringSplitOptions.RemoveEmptyEntries);
if (split.Length == 1)
{
savedUrl = split[0];
}
else
{
throw new ArgumentException($"Attempt to parse url {savedUrl} and could not");
}
}
if (!plexHost.HasValue())
{
plexHost = "https://app.plex.tv/";
}
else
{
if (plexHost[plexHost.Length - 1] != '/')
{
plexHost += '/';
}
}
return $"{plexHost}{savedUrl}";
}
public static ProviderId GetProviderIdsFromMetadata(params string[] guids)
{
var providerIds = new ProviderId();

@ -3,6 +3,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -71,7 +71,7 @@ namespace Ombi.Mapping.Profiles
.ForMember(x => x.ReleaseDate, o => o.MapFrom(s => s.release_dates))
.ForMember(x => x.IsoCode, o => o.MapFrom(s => s.iso_3166_1));
CreateMap<ReleaseDate, ReleaseDateDto>()
.ForMember(x => x.ReleaseDate, o => o.MapFrom(s => s.release_date))
.ForMember(x => x.ReleaseDate, o => o.MapFrom(s => s.ReleaseDateTime))
.ForMember(x => x.Type, o => o.MapFrom(s => s.Type));
CreateMap<TheMovieDbApi.Models.Genre, GenreDto>();

@ -7,6 +7,7 @@
<Version></Version>
<PackageVersion></PackageVersion>
<LangVersion>8.0</LangVersion>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -213,7 +213,51 @@ namespace Ombi.Notifications.Tests
[Test]
public void TvNotificationTests()
{
var notificationOptions = new NotificationOptions();
var notificationOptions = new NotificationOptions
{
NotificationType = Helpers.NotificationType.PartiallyAvailable
};
var req = F.Build<ChildRequests>()
.With(x => x.RequestType, RequestType.TvShow)
.With(x => x.Available, true)
.Create();
var customization = new CustomizationSettings
{
ApplicationUrl = "url",
ApplicationName = "name"
};
var userPrefs = new UserNotificationPreferences();
sut.Setup(notificationOptions, req, customization, userPrefs);
Assert.That(req.Id.ToString(), Is.EqualTo(sut.RequestId));
Assert.That(req.ParentRequest.ExternalProviderId.ToString(), Is.EqualTo(sut.ProviderId));
Assert.That(req.ParentRequest.Title.ToString(), Is.EqualTo(sut.Title));
Assert.That(req.RequestedUser.UserName, Is.EqualTo(sut.RequestedUser));
Assert.That(req.RequestedUser.Alias, Is.EqualTo(sut.Alias));
Assert.That(req.RequestedDate.ToString("D"), Is.EqualTo(sut.RequestedDate));
Assert.That("TV Show", Is.EqualTo(sut.Type));
Assert.That(req.ParentRequest.Overview, Is.EqualTo(sut.Overview));
Assert.That(req.ParentRequest.ReleaseDate.Year.ToString(), Is.EqualTo(sut.Year));
Assert.That(req.DeniedReason, Is.EqualTo(sut.DenyReason));
Assert.That(req.MarkedAsAvailable?.ToString("D"), Is.EqualTo(sut.AvailableDate));
Assert.That("https://image.tmdb.org/t/p/w300/" + req.ParentRequest.PosterPath, Is.EqualTo(sut.PosterImage));
Assert.That(req.DeniedReason, Is.EqualTo(sut.DenyReason));
Assert.That(req.RequestedUser.Alias, Is.EqualTo(sut.UserPreference));
Assert.That(null, Is.EqualTo(sut.AdditionalInformation));
Assert.That("Available", Is.EqualTo(sut.RequestStatus));
Assert.That("url", Is.EqualTo(sut.ApplicationUrl));
Assert.That("name", Is.EqualTo(sut.ApplicationName));
}
[Test]
public void TvNotificationPartialAvailablilityTests()
{
var notificationOptions = new NotificationOptions {
NotificationType = Helpers.NotificationType.PartiallyAvailable
};
notificationOptions.Substitutes.Add("Season", "1");
notificationOptions.Substitutes.Add("Episodes", "1, 2");
var req = F.Build<ChildRequests>()
.With(x => x.RequestType, RequestType.TvShow)
.With(x => x.Available, true)
@ -244,6 +288,8 @@ namespace Ombi.Notifications.Tests
Assert.That("Available", Is.EqualTo(sut.RequestStatus));
Assert.That("url", Is.EqualTo(sut.ApplicationUrl));
Assert.That("name", Is.EqualTo(sut.ApplicationName));
Assert.That(sut.PartiallyAvailableEpisodeNumbers, Is.EqualTo("1, 2"));
Assert.That(sut.PartiallyAvailableSeasonNumber, Is.EqualTo("1"));
}
[Test]

@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<Configurations>Debug;Release;NonUiBuild</Configurations>
</PropertyGroup>
<ItemGroup>

@ -94,6 +94,10 @@ namespace Ombi.Notifications.Agents
{
await Run(model, settings, NotificationType.RequestAvailable);
}
protected override async Task PartiallyAvailable(NotificationOptions model, DiscordNotificationSettings settings)
{
await Run(model, settings, NotificationType.PartiallyAvailable);
}
protected override async Task Send(NotificationMessage model, DiscordNotificationSettings settings)
{
@ -166,8 +170,6 @@ namespace Ombi.Notifications.Agents
author.name = appName;
}
var embed = new DiscordEmbeds
{
fields = fields,

@ -219,6 +219,25 @@ namespace Ombi.Notifications.Agents
}
protected override async Task PartiallyAvailable(NotificationOptions model, EmailNotificationSettings settings)
{
var message = await LoadTemplate(NotificationType.PartiallyAvailable, model, settings);
if (message == null)
{
return;
}
var plaintext = await LoadPlainTextMessage(NotificationType.PartiallyAvailable, model, settings);
message.Other.Add("PlainTextBody", plaintext);
await SendToSubscribers(settings, message);
message.To = model.RequestType == RequestType.Movie
? MovieRequest.RequestedUser.Email
: TvRequest.RequestedUser.Email;
await Send(message, settings);
}
protected override async Task RequestApproved(NotificationOptions model, EmailNotificationSettings settings)
{
var message = await LoadTemplate(NotificationType.RequestApproved, model, settings);

@ -112,5 +112,10 @@ namespace Ombi.Notifications.Agents
await Send(notification, settings);
}
protected override async Task PartiallyAvailable(NotificationOptions model, GotifySettings settings)
{
await Run(model, settings, NotificationType.PartiallyAvailable);
}
}
}

@ -316,5 +316,25 @@ namespace Ombi.Notifications.Agents
}
}
}
protected override async Task PartiallyAvailable(NotificationOptions model, MobileNotificationSettings settings)
{
var parsed = await LoadTemplate(NotificationAgent.Mobile, NotificationType.PartiallyAvailable, model);
if (parsed.Disabled)
{
_logger.LogInformation($"Template {NotificationType.PartiallyAvailable} is disabled for {NotificationAgent.Mobile}");
return;
}
var notification = new NotificationMessage
{
Message = parsed.Message,
};
// Send to user
var playerIds = GetUsers(model, NotificationType.PartiallyAvailable);
await AddSubscribedUsers(playerIds);
await Send(playerIds, notification, settings, model);
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save