Repository: Liu233w/acm-statistics
Branch: master
Commit: 850666df36ce
Files: 529
Total size: 4.7 MB
Directory structure:
gitextract_va1v6f6n/
├── .all-contributorsrc
├── .editorconfig
├── .gitattributes
├── .github/
│ ├── .vscode/
│ │ └── settings.json
│ ├── mergify.yml
│ └── workflows/
│ ├── auto-cancellation.yml
│ ├── deploy.yml
│ ├── e2e-test-pr.yml
│ ├── e2e-test-push.yml
│ ├── html-test.yml
│ ├── sonar-cloud.yml
│ ├── unit-test.yml
│ ├── update-e2e-snapshot.yml
│ └── update-html-snapshot.yml
├── .gitignore
├── .imgbotconfig
├── .renovaterc.json
├── LICENSE
├── Makefile
├── README.md
├── README_zh-hans.md
├── backend/
│ ├── .config/
│ │ └── dotnet-tools.json
│ ├── .dockerignore
│ ├── .gitattributes
│ ├── .gitignore
│ ├── AcmStatisticsBackend.sln
│ ├── AcmStatisticsBackend.sln.DotSettings
│ ├── Directory.Build.props
│ ├── Makefile
│ ├── README.md
│ ├── StyleCop.ruleset
│ ├── dev.Dockerfile
│ ├── global.json
│ ├── src/
│ │ ├── AcmStatisticsBackend.Application/
│ │ │ ├── Accounts/
│ │ │ │ ├── AccountAppService.cs
│ │ │ │ ├── Dto/
│ │ │ │ │ ├── ChangePasswordInput.cs
│ │ │ │ │ ├── RegisterInput.cs
│ │ │ │ │ └── RegisterOutput.cs
│ │ │ │ └── IAccountAppService.cs
│ │ │ ├── AcmStatisticsBackend.Application.csproj
│ │ │ ├── AcmStatisticsBackendAppServiceBase.cs
│ │ │ ├── AcmStatisticsBackendApplicationModule.cs
│ │ │ ├── Authorization/
│ │ │ │ └── AbpLoginResultTypeHelper.cs
│ │ │ ├── Crawlers/
│ │ │ │ ├── DefaultQueryAppService.cs
│ │ │ │ ├── Dto/
│ │ │ │ │ ├── DefaultQueryDto.cs
│ │ │ │ │ ├── DeleteQueryHistoryInput.cs
│ │ │ │ │ ├── GetAcWorkerHistoryInput.cs
│ │ │ │ │ ├── GetQueryHistoryAndSummaryOutput.cs
│ │ │ │ │ ├── GetQueryHistoryOutput.cs
│ │ │ │ │ ├── GetQuerySummaryInput.cs
│ │ │ │ │ ├── QueryCrawlerSummaryDto.cs
│ │ │ │ │ ├── QuerySummaryDto.cs
│ │ │ │ │ ├── QueryWorkerHistoryDto.cs
│ │ │ │ │ ├── SaveOrReplaceQueryHistoryInput.cs
│ │ │ │ │ ├── SaveOrReplaceQueryHistoryOutput.cs
│ │ │ │ │ └── UsernameInCrawlerDto.cs
│ │ │ │ ├── IDefaultQueryAppService.cs
│ │ │ │ ├── IQueryHistoryAppService.cs
│ │ │ │ └── QueryHistoryAppService.cs
│ │ │ ├── Net/
│ │ │ │ └── MimeTypes/
│ │ │ │ └── MimeTypeNames.cs
│ │ │ ├── Properties/
│ │ │ │ └── AssemblyInfo.cs
│ │ │ ├── Sessions/
│ │ │ │ ├── Dto/
│ │ │ │ │ ├── ApplicationInfoDto.cs
│ │ │ │ │ ├── GetCurrentLoginInformationsOutput.cs
│ │ │ │ │ ├── TenantLoginInfoDto.cs
│ │ │ │ │ └── UserLoginInfoDto.cs
│ │ │ │ ├── ISessionAppService.cs
│ │ │ │ └── SessionAppService.cs
│ │ │ └── Settings/
│ │ │ ├── Dto/
│ │ │ │ ├── UpdateAutoSaveHistoryInput.cs
│ │ │ │ ├── UserSettingsConfigDto.cs
│ │ │ │ └── UserTimeZoneDto.cs
│ │ │ ├── IUserConfigAppService.cs
│ │ │ └── UserConfigAppService.cs
│ │ ├── AcmStatisticsBackend.Core/
│ │ │ ├── AcmStatisticsBackend.Core.csproj
│ │ │ ├── AcmStatisticsBackendConsts.cs
│ │ │ ├── AcmStatisticsBackendCoreModule.cs
│ │ │ ├── AcmStatisticsBackendExtensions.cs
│ │ │ ├── AppVersionHelper.cs
│ │ │ ├── Authorization/
│ │ │ │ ├── AcmStatisticsBackendAuthorizationProvider.cs
│ │ │ │ ├── LoginManager.cs
│ │ │ │ ├── PermissionChecker.cs
│ │ │ │ ├── PermissionNames.cs
│ │ │ │ ├── Roles/
│ │ │ │ │ ├── AppRoleConfig.cs
│ │ │ │ │ ├── Role.cs
│ │ │ │ │ ├── RoleManager.cs
│ │ │ │ │ ├── RoleStore.cs
│ │ │ │ │ └── StaticRoleNames.cs
│ │ │ │ └── Users/
│ │ │ │ ├── User.cs
│ │ │ │ ├── UserClaimsPrincipalFactory.cs
│ │ │ │ ├── UserDeletingEventHandler.cs
│ │ │ │ ├── UserManager.cs
│ │ │ │ ├── UserRegistrationManager.cs
│ │ │ │ └── UserStore.cs
│ │ │ ├── Configuration/
│ │ │ │ ├── AppConfigurations.cs
│ │ │ │ ├── AppEnvironmentVariables.cs
│ │ │ │ ├── AppSettingNames.cs
│ │ │ │ └── AppSettingProvider.cs
│ │ │ ├── Crawlers/
│ │ │ │ ├── DefaultQuery.cs
│ │ │ │ ├── QueryCrawlerSummary.cs
│ │ │ │ ├── QueryHistory.cs
│ │ │ │ ├── QuerySummary.cs
│ │ │ │ ├── QueryWorkerHistory.cs
│ │ │ │ ├── SummaryGenerator.cs
│ │ │ │ ├── SummaryWarning.cs
│ │ │ │ └── UsernameInCrawler.cs
│ │ │ ├── Editions/
│ │ │ │ └── EditionManager.cs
│ │ │ ├── Features/
│ │ │ │ └── FeatureValueStore.cs
│ │ │ ├── Identity/
│ │ │ │ ├── IdentityRegistrar.cs
│ │ │ │ ├── SecurityStampValidator.cs
│ │ │ │ └── SignInManager.cs
│ │ │ ├── Localization/
│ │ │ │ ├── AcmStatisticsBackendLocalizationConfigurer.cs
│ │ │ │ └── SourceFiles/
│ │ │ │ ├── AcmStatisticsBackend-es.xml
│ │ │ │ ├── AcmStatisticsBackend-fr.xml
│ │ │ │ ├── AcmStatisticsBackend-it.xml
│ │ │ │ ├── AcmStatisticsBackend-ja.xml
│ │ │ │ ├── AcmStatisticsBackend-lt.xml
│ │ │ │ ├── AcmStatisticsBackend-nl.xml
│ │ │ │ ├── AcmStatisticsBackend-pt-BR.xml
│ │ │ │ ├── AcmStatisticsBackend-tr.xml
│ │ │ │ ├── AcmStatisticsBackend-zh-Hans.xml
│ │ │ │ └── AcmStatisticsBackend.xml
│ │ │ ├── MultiTenancy/
│ │ │ │ ├── Tenant.cs
│ │ │ │ └── TenantManager.cs
│ │ │ ├── Properties/
│ │ │ │ └── AssemblyInfo.cs
│ │ │ ├── ServiceClients/
│ │ │ │ ├── CaptchaServiceClient.cs
│ │ │ │ ├── CaptchaServiceValidateResult.cs
│ │ │ │ ├── CrawlerApiBackendClient.cs
│ │ │ │ ├── CrawlerMetaItem.cs
│ │ │ │ ├── ICaptchaServiceClient.cs
│ │ │ │ └── ICrawlerApiBackendClient.cs
│ │ │ ├── Settings/
│ │ │ │ └── UserSettingAttribute.cs
│ │ │ ├── Timing/
│ │ │ │ └── AppTimes.cs
│ │ │ ├── Validation/
│ │ │ │ └── ValidationHelper.cs
│ │ │ └── Web/
│ │ │ └── WebContentFolderHelper.cs
│ │ ├── AcmStatisticsBackend.EntityFrameworkCore/
│ │ │ ├── AcmStatisticsBackend.EntityFrameworkCore.csproj
│ │ │ ├── EntityFrameworkCore/
│ │ │ │ ├── AbpZeroDbMigrator.cs
│ │ │ │ ├── AcmStatisticsBackendDbContext.cs
│ │ │ │ ├── AcmStatisticsBackendDbContextConfigurer.cs
│ │ │ │ ├── AcmStatisticsBackendDbContextFactory.cs
│ │ │ │ ├── AcmStatisticsBackendEntityFrameworkModule.cs
│ │ │ │ ├── Repositories/
│ │ │ │ │ └── AcmStatisticsBackendRepositoryBase.cs
│ │ │ │ └── Seed/
│ │ │ │ ├── Host/
│ │ │ │ │ ├── DefaultEditionCreator.cs
│ │ │ │ │ ├── DefaultLanguagesCreator.cs
│ │ │ │ │ ├── DefaultSettingsCreator.cs
│ │ │ │ │ ├── HostRoleAndUserCreator.cs
│ │ │ │ │ └── InitialHostDbBuilder.cs
│ │ │ │ ├── SeedHelper.cs
│ │ │ │ └── Tenants/
│ │ │ │ ├── DefaultTenantBuilder.cs
│ │ │ │ └── TenantRoleAndUserBuilder.cs
│ │ │ └── Migrations/
│ │ │ ├── 20200325035348_Init.Designer.cs
│ │ │ ├── 20200325035348_Init.cs
│ │ │ ├── 20200410093107_AddDefaultQuery.Designer.cs
│ │ │ ├── 20200410093107_AddDefaultQuery.cs
│ │ │ ├── 20200414102908_AddAcHistory.Designer.cs
│ │ │ ├── 20200414102908_AddAcHistory.cs
│ │ │ ├── 20200419031052_UseQueryHistory.Designer.cs
│ │ │ ├── 20200419031052_UseQueryHistory.cs
│ │ │ ├── 20200522145416_AddSettings.Designer.cs
│ │ │ ├── 20200522145416_AddSettings.cs
│ │ │ ├── 20200604111842_AddSummary.Designer.cs
│ │ │ ├── 20200604111842_AddSummary.cs
│ │ │ ├── 20210429095008_UpgradeAbp.Designer.cs
│ │ │ ├── 20210429095008_UpgradeAbp.cs
│ │ │ ├── 20210627092246_RemoveRoleDescription.Designer.cs
│ │ │ ├── 20210627092246_RemoveRoleDescription.cs
│ │ │ ├── 20210627092411_UpgradeDriver.Designer.cs
│ │ │ ├── 20210627092411_UpgradeDriver.cs
│ │ │ ├── 20250813025256_UpgradeAbp840.Designer.cs
│ │ │ ├── 20250813025256_UpgradeAbp840.cs
│ │ │ └── AcmStatisticsBackendDbContextModelSnapshot.cs
│ │ ├── AcmStatisticsBackend.Web.Core/
│ │ │ ├── AcmStatisticsBackend.Web.Core.csproj
│ │ │ ├── AcmStatisticsBackendWebCoreModule.cs
│ │ │ ├── Authentication/
│ │ │ │ └── JwtBearer/
│ │ │ │ ├── JwtTokenMiddleware.cs
│ │ │ │ └── TokenAuthConfiguration.cs
│ │ │ ├── Configuration/
│ │ │ │ └── HostingEnvironmentExtensions.cs
│ │ │ ├── Controllers/
│ │ │ │ ├── AcmStatisticsBackendControllerBase.cs
│ │ │ │ └── TokenAuthController.cs
│ │ │ ├── Middleware/
│ │ │ │ └── CookieAuthMiddleware.cs
│ │ │ ├── Models/
│ │ │ │ └── TokenAuth/
│ │ │ │ ├── AuthenticateModel.cs
│ │ │ │ └── AuthenticateResultModel.cs
│ │ │ └── Properties/
│ │ │ └── AssemblyInfo.cs
│ │ └── AcmStatisticsBackend.Web.Host/
│ │ ├── AcmStatisticsBackend.Web.Host.csproj
│ │ ├── Controllers/
│ │ │ └── AntiForgeryController.cs
│ │ ├── Dockerfile
│ │ ├── Properties/
│ │ │ └── launchSettings.json
│ │ ├── Startup/
│ │ │ ├── AcmStatisticsBackendWebHostModule.cs
│ │ │ ├── AuthConfigurer.cs
│ │ │ ├── Program.cs
│ │ │ └── Startup.cs
│ │ ├── app.config
│ │ ├── appsettings.Staging.json
│ │ ├── appsettings.json
│ │ ├── log4net.config
│ │ └── web.config
│ ├── stylecop.json
│ └── test/
│ └── AcmStatisticsBackend.Tests/
│ ├── Accounts/
│ │ ├── AccountAppService_Tests.cs
│ │ └── FakeCaptchaServiceClient.cs
│ ├── AcmStatisticsBackend.Tests.csproj
│ ├── AcmStatisticsBackendTestBase.cs
│ ├── AcmStatisticsBackendTestModule.cs
│ ├── Crawlers/
│ │ ├── DefaultQueryAppService_Tests.cs
│ │ ├── QueryHistoryAppService_Tests.cs
│ │ ├── QuerySummary_ModelTests.cs
│ │ └── SummaryGenerator_Tests.cs
│ ├── DependencyInjection/
│ │ ├── ServiceCollectionRegistrar.cs
│ │ ├── TestClockProvider.cs
│ │ └── TestCrawlerApiBackendClient.cs
│ ├── MultiTenantFactAttribute.cs
│ ├── Properties/
│ │ └── AssemblyInfo.cs
│ ├── ServiceClients/
│ │ ├── CaptchaServiceClient_Tests.cs
│ │ └── CrawlerApiBackendClient_Tests.cs
│ ├── Sessions/
│ │ └── SessionAppService_Tests.cs
│ ├── Settings/
│ │ └── UserConfigAppService_TimeZone_Tests.cs
│ └── TestExtensions.cs
├── build/
│ ├── .dockerignore
│ ├── .gitignore
│ ├── commitlint.Dockerfile
│ ├── commitlint.mk
│ ├── docker-compose.dcproj
│ ├── docker-compose.dev-backend.yml
│ ├── docker-compose.dev-frontend.yml
│ ├── docker-compose.e2e.yml
│ ├── docker-compose.mk
│ ├── docker-compose.yml
│ ├── node-base.Dockerfile
│ ├── node-base.mk
│ ├── share.mk
│ ├── shell.Dockerfile
│ ├── shell.mk
│ └── template.env
├── captcha-service/
│ ├── .dockerignore
│ ├── .eslintrc.js
│ ├── .gitignore
│ ├── Makefile
│ ├── README.md
│ ├── __mocks__/
│ │ └── svg-captcha.js
│ ├── __test__/
│ │ ├── app.spec.js
│ │ └── interface.test.js
│ ├── base.Dockerfile
│ ├── package.json
│ ├── release.Dockerfile
│ └── src/
│ ├── app.js
│ ├── index.js
│ └── restHelper.js
├── codecov.yml
├── commitlint.config.js
├── crawler/
│ ├── .dockerignore
│ ├── .eslintrc.js
│ ├── .gitignore
│ ├── .vscode/
│ │ └── launch.json
│ ├── Makefile
│ ├── README.md
│ ├── __mocks__/
│ │ └── fs.js
│ ├── __test__/
│ │ ├── __snapshots__/
│ │ │ └── crawlers.test.js.snap
│ │ ├── configReader.test.js
│ │ ├── crawlers.test.js
│ │ └── functionGenerator.test.js
│ ├── base.Dockerfile
│ ├── config.yml
│ ├── crawlers/
│ │ ├── .eslintrc.js
│ │ ├── LICENSE
│ │ ├── aizu.js
│ │ ├── atcoder.js
│ │ ├── bnu.js
│ │ ├── codechef.js
│ │ ├── codeforces.js
│ │ ├── codewars.js
│ │ ├── csu.js
│ │ ├── dashiye.js
│ │ ├── dmoj.js
│ │ ├── eljudge.js
│ │ ├── fzu.js
│ │ ├── hdu.js
│ │ ├── leetcode_cn.js
│ │ ├── loj.js
│ │ ├── luogu.js
│ │ ├── nbut.js
│ │ ├── nit.js
│ │ ├── nod.js
│ │ ├── nowcoder.js
│ │ ├── poj.js
│ │ ├── sdutoj.js
│ │ ├── spoj.js
│ │ ├── timus.js
│ │ ├── uestc.js
│ │ ├── uoj.js
│ │ ├── uva.js
│ │ ├── uvalive.js
│ │ ├── vjudge.js
│ │ └── zoj.js
│ ├── index.js
│ ├── lib/
│ │ ├── __mocks__/
│ │ │ └── configReader.js
│ │ ├── configReader.js
│ │ ├── functionGenerator.js
│ │ └── globalProxy.js
│ ├── package.json
│ └── release.Dockerfile
├── crawler-api-backend/
│ ├── .dockerignore
│ ├── .eslintrc.js
│ ├── .gitignore
│ ├── Makefile
│ ├── README.md
│ ├── __mocks__/
│ │ └── crawler.js
│ ├── __test__/
│ │ ├── __snapshots__/
│ │ │ └── apiRouter.test.js.snap
│ │ └── apiRouter.test.js
│ ├── apiRouter.js
│ ├── app.js
│ ├── base.Dockerfile
│ ├── config/
│ │ └── log.js
│ ├── index.js
│ ├── package.json
│ ├── release.Dockerfile
│ ├── swagger.json
│ └── utils/
│ ├── logUtil.js
│ ├── rateLimit.js
│ └── restHelper.js
├── e2e/
│ ├── .dockerignore
│ ├── .eslintignore
│ ├── .eslintrc.js
│ ├── .gitignore
│ ├── .npmrc
│ ├── Dockerfile
│ ├── Makefile
│ ├── README.md
│ ├── __test__/
│ │ └── pages/
│ │ ├── __snapshots__/
│ │ │ └── pages_snapshot.test.js.snap
│ │ └── pages_snapshot.test.js
│ ├── cypress/
│ │ ├── fixtures/
│ │ │ ├── example.json
│ │ │ ├── history_list-max5.json
│ │ │ ├── history_list-skip10.json
│ │ │ ├── history_list.json
│ │ │ ├── poj_notExist.txt
│ │ │ ├── poj_ok.txt
│ │ │ ├── summary_hdu.txt
│ │ │ ├── summary_leetcode.txt
│ │ │ └── summary_vjudge.txt
│ │ ├── integration/
│ │ │ ├── application/
│ │ │ │ ├── auth-redirect.spec.js
│ │ │ │ ├── auto-save-history.spec.js
│ │ │ │ ├── default-query.spec.js
│ │ │ │ ├── login-and-register.spec.js
│ │ │ │ └── swagger.spec.js
│ │ │ └── frontend/
│ │ │ ├── about.spec.js
│ │ │ ├── history.spec.js
│ │ │ ├── index.spec.js
│ │ │ ├── login-register.spec.js
│ │ │ ├── settings.spec.js
│ │ │ ├── side-bar.spec.js
│ │ │ └── statistics.spec.js
│ │ └── support/
│ │ ├── commands.js
│ │ └── e2e.js
│ ├── cypress.config.js
│ ├── http-mocks/
│ │ ├── .dockerignore
│ │ ├── .gitignore
│ │ ├── Dockerfile
│ │ ├── package.json
│ │ └── src/
│ │ ├── index.js
│ │ ├── lib/
│ │ │ ├── mock.js
│ │ │ └── restClient.js
│ │ ├── mocks/
│ │ │ ├── busuanzi.js
│ │ │ ├── googleAds.js
│ │ │ ├── googleAnalysis.js
│ │ │ ├── history-snapshot.js
│ │ │ ├── oj.js
│ │ │ ├── reset.js
│ │ │ └── tajs.js
│ │ └── preActivation.js
│ ├── jsconfig.json
│ └── package.json
├── frontend/
│ ├── .dockerignore
│ ├── .editorconfig
│ ├── .eslintignore
│ ├── .eslintrc.js
│ ├── .gitignore
│ ├── .npmrc
│ ├── .nuxtignore
│ ├── Makefile
│ ├── README.md
│ ├── __test__/
│ │ ├── StoreContextSimulator.js
│ │ ├── components/
│ │ │ ├── MessagePanel.test.js
│ │ │ ├── WorkerCard.test.js
│ │ │ ├── __snapshots__/
│ │ │ │ ├── MessagePanel.test.js.snap
│ │ │ │ └── WorkerCard.test.js.snap
│ │ │ ├── statisticsLayoutBuilder.test.js
│ │ │ └── statisticsUtils.test.js
│ │ ├── e2eMocks/
│ │ │ └── crawler.js
│ │ └── store/
│ │ └── statistics.test.js
│ ├── app.html
│ ├── assets/
│ │ ├── README.md
│ │ └── style/
│ │ └── app.scss
│ ├── babel.config.js
│ ├── base.Dockerfile
│ ├── components/
│ │ ├── GithubButton.vue
│ │ ├── MessagePanel.vue
│ │ ├── README.md
│ │ ├── ResultOverlay.vue
│ │ ├── UserStatus.vue
│ │ ├── WorkerCard.vue
│ │ ├── consts.js
│ │ ├── rulesMixin.js
│ │ ├── statisticsLayoutBuilder.js
│ │ ├── statisticsUtils.js
│ │ └── utils.js
│ ├── configs/
│ │ └── sensitive-url-router.js
│ ├── layouts/
│ │ ├── README.md
│ │ ├── default.vue
│ │ ├── error.vue
│ │ ├── login.vue
│ │ └── none.vue
│ ├── middleware/
│ │ ├── README.md
│ │ └── auth.js
│ ├── modules/
│ │ └── crawlerLoader/
│ │ ├── README.md
│ │ ├── cors.js
│ │ └── index.js
│ ├── nuxt.config.js
│ ├── package.json
│ ├── pages/
│ │ ├── README.md
│ │ ├── about.vue
│ │ ├── history/
│ │ │ ├── _id/
│ │ │ │ ├── -GoHistoryPage.vue
│ │ │ │ ├── -HistoryToolbar.vue
│ │ │ │ └── index.vue
│ │ │ └── index.vue
│ │ ├── index.vue
│ │ ├── jojo.vue
│ │ ├── login.vue
│ │ ├── register.vue
│ │ ├── settings.vue
│ │ └── statistics.vue
│ ├── plugins/
│ │ ├── README.md
│ │ ├── chartjs.js
│ │ ├── debug.js
│ │ └── font.js
│ ├── release.Dockerfile
│ ├── static/
│ │ ├── google90cac42981c276fb.html
│ │ └── swagger/
│ │ ├── abp.js
│ │ ├── abp.swagger.js
│ │ ├── index.html
│ │ ├── oauth2-redirect.html
│ │ ├── swagger-ui-bundle.js
│ │ ├── swagger-ui-standalone-preset.js
│ │ ├── swagger-ui.css
│ │ └── swagger-ui.js
│ ├── store/
│ │ ├── -dynamic/
│ │ │ └── statistics.js
│ │ ├── README.md
│ │ ├── index.js
│ │ ├── message.js
│ │ └── session.js
│ └── vuetify.options.js
├── ohunt/
│ ├── .config/
│ │ └── dotnet-tools.json
│ ├── .dockerignore
│ ├── .gitignore
│ ├── Makefile
│ ├── OHunt.Tests/
│ │ ├── Crawlers/
│ │ │ ├── BnuMappingCrawlerTests.cs
│ │ │ ├── NitMappingCrawlerTests.cs
│ │ │ ├── UvaMappingCrawlersTests.cs
│ │ │ ├── ZojSubmissionCrawlerTests.cs
│ │ │ └── __snapshots__/
│ │ │ └── ZojSubmissionCrawlerTests.It_ShouldGetCorrectResult.snap
│ │ ├── Dataflow/
│ │ │ ├── CrawlerPropagatorTests.cs
│ │ │ ├── DatabaseInserterTests.cs
│ │ │ └── SubmissionCrawlerCoordinatorTests.cs
│ │ ├── Dependency/
│ │ │ ├── NullDbBuilder.cs
│ │ │ ├── OHuntTestBase.cs
│ │ │ └── TestWebApplicationFactory.cs
│ │ ├── OHunt.Tests.csproj
│ │ ├── Services/
│ │ │ └── ProblemLabelManagerTests.cs
│ │ ├── TestExtensions.cs
│ │ ├── Utils.cs
│ │ └── Web/
│ │ ├── ProblemControllerTests.cs
│ │ ├── StartupTests.cs
│ │ ├── SubmissionControllerTests.cs
│ │ ├── SwaggerTests.cs
│ │ └── __snapshots__/
│ │ └── SwaggerTests.It_ShouldOutputDocument.snap
│ ├── OHunt.Web/
│ │ ├── Controllers/
│ │ │ ├── Dto/
│ │ │ │ ├── ResolveLabelInput.cs
│ │ │ │ └── ResolveLabelOutput.cs
│ │ │ ├── HomeController.cs
│ │ │ ├── ProblemController.cs
│ │ │ └── SubmissionsController.cs
│ │ ├── Crawlers/
│ │ │ ├── BnuMappingCrawler.cs
│ │ │ ├── CrawlerBase.cs
│ │ │ ├── CrawlerMessage.cs
│ │ │ ├── IMappingCrawler.cs
│ │ │ ├── ISubmissionCrawler.cs
│ │ │ ├── NitMappingCrawler.cs
│ │ │ ├── UvaCrawlers.cs
│ │ │ └── ZojSubmissionCrawler.cs
│ │ ├── Database/
│ │ │ ├── IDbBuilder.cs
│ │ │ ├── OHuntDbBuilder.cs
│ │ │ └── OHuntDbContext.cs
│ │ ├── Dataflow/
│ │ │ ├── CrawlerPropagator.cs
│ │ │ ├── DatabaseInserter.cs
│ │ │ ├── DatabaseInserterFactory.cs
│ │ │ ├── DatabaseInserterMessage.cs
│ │ │ └── SubmissionCrawlerCoordinator.cs
│ │ ├── Dockerfile
│ │ ├── GlobalConfigurer.cs
│ │ ├── Migrations/
│ │ │ ├── 20200701054200_Init.Designer.cs
│ │ │ ├── 20200701054200_Init.cs
│ │ │ ├── 20200701112402_AddSubmission.Designer.cs
│ │ │ ├── 20200701112402_AddSubmission.cs
│ │ │ ├── 20200702060356_AddIndex.Designer.cs
│ │ │ ├── 20200702060356_AddIndex.cs
│ │ │ ├── 20200702142254_AddCrawlerError.Designer.cs
│ │ │ ├── 20200702142254_AddCrawlerError.cs
│ │ │ ├── 20200802072749_AddProblemLabelMapping.Designer.cs
│ │ │ ├── 20200802072749_AddProblemLabelMapping.cs
│ │ │ ├── 20210627092639_UpgradeDriver.Designer.cs
│ │ │ ├── 20210627092639_UpgradeDriver.cs
│ │ │ └── OHuntWebContextModelSnapshot.cs
│ │ ├── Models/
│ │ │ ├── CrawlerError.cs
│ │ │ ├── MappingOnlineJudge.cs
│ │ │ ├── OnlineJudge.cs
│ │ │ ├── ProblemLabelMapping.cs
│ │ │ ├── RunResult.cs
│ │ │ └── Submission.cs
│ │ ├── OHunt.Web.csproj
│ │ ├── Options/
│ │ │ └── DatabaseInserterOptions.cs
│ │ ├── Program.cs
│ │ ├── Properties/
│ │ │ └── launchSettings.json
│ │ ├── Services/
│ │ │ ├── ProblemLabelManager.cs
│ │ │ └── ScheduleCrawlerService.cs
│ │ ├── Startup.cs
│ │ ├── Utils/
│ │ │ ├── Extensions.cs
│ │ │ └── QueryParameterFilter.cs
│ │ ├── appsettings.Development.json
│ │ └── appsettings.json
│ ├── README.md
│ ├── dev.Dockerfile
│ ├── global.json
│ └── ohunt.sln
├── sonar-project.properties
└── tools/
├── acm-statistics.service
├── history-test.sql
└── remote-docker-up.sh
================================================
FILE CONTENTS
================================================
================================================
FILE: .all-contributorsrc
================================================
{
"files": [
"README.md"
],
"imageSize": 100,
"commit": false,
"contributors": [
{
"login": "Liu233w",
"name": "Liu233w",
"avatar_url": "https://avatars2.githubusercontent.com/u/16333687?v=4",
"profile": "https://liu233w.github.io",
"contributions": [
"code",
"ideas",
"infra",
"test"
]
},
{
"login": "kidozh",
"name": "Kido Zhang",
"avatar_url": "https://avatars3.githubusercontent.com/u/11661760?v=4",
"profile": "https://kidozh.com",
"contributions": [
"infra",
"ideas"
]
},
{
"login": "flylai",
"name": "flylai",
"avatar_url": "https://avatars2.githubusercontent.com/u/9880740?v=4",
"profile": "https://github.com/flylai",
"contributions": [
"code",
"bug"
]
},
{
"login": "fzu-h4cky",
"name": "fzu-h4cky",
"avatar_url": "https://avatars3.githubusercontent.com/u/36151020?v=4",
"profile": "https://github.com/fzu-h4cky",
"contributions": [
"bug"
]
},
{
"login": "2512821228",
"name": "Zhao",
"avatar_url": "https://avatars1.githubusercontent.com/u/11994295?v=4",
"profile": "http://zhao.wtf",
"contributions": [
"bug"
]
},
{
"login": "cometeme",
"name": "Adelard Collins",
"avatar_url": "https://avatars0.githubusercontent.com/u/22635759?v=4",
"profile": "https://www.cometeme.tech",
"contributions": [
"bug"
]
},
{
"login": "ctuu",
"name": "ct",
"avatar_url": "https://avatars3.githubusercontent.com/u/22322656?v=4",
"profile": "https://github.com/ctuu",
"contributions": [
"bug"
]
},
{
"login": "Geekxiong",
"name": "Geekxiong",
"avatar_url": "https://avatars3.githubusercontent.com/u/25352156?v=4",
"profile": "https://github.com/Geekxiong",
"contributions": [
"ideas"
]
},
{
"login": "Halorv",
"name": "Halorv",
"avatar_url": "https://avatars2.githubusercontent.com/u/39403985?v=4",
"profile": "https://github.com/settings/profile",
"contributions": [
"ideas"
]
},
{
"login": "bodhisatan",
"name": "Bodhisatan_Yao",
"avatar_url": "https://avatars0.githubusercontent.com/u/35862184?v=4",
"profile": "https://github.com/bodhisatan",
"contributions": [
"bug"
]
},
{
"login": "Meulsama",
"name": "Meulsama",
"avatar_url": "https://avatars1.githubusercontent.com/u/55663936?v=4",
"profile": "https://github.com/Meulsama",
"contributions": [
"ideas"
]
},
{
"login": "UserUnknownX",
"name": "Michael Xiang",
"avatar_url": "https://avatars3.githubusercontent.com/u/50655871?v=4",
"profile": "https://github.com/UserUnknownX",
"contributions": [
"bug"
]
},
{
"login": "zby0327",
"name": "zby",
"avatar_url": "https://avatars2.githubusercontent.com/u/43291744?v=4",
"profile": "https://github.com/zby0327",
"contributions": [
"ideas",
"bug"
]
},
{
"login": "BackSlashDelta",
"name": "BackSlashDelta",
"avatar_url": "https://avatars1.githubusercontent.com/u/64258212?v=4",
"profile": "https://github.com/BackSlashDelta",
"contributions": [
"bug"
]
},
{
"login": "bluebear4",
"name": "bluebear4",
"avatar_url": "https://avatars.githubusercontent.com/u/49401963?v=4",
"profile": "https://github.com/bluebear4",
"contributions": [
"bug"
]
},
{
"login": "wwawwaww",
"name": "wwawwaww",
"avatar_url": "https://avatars.githubusercontent.com/u/42441490?v=4",
"profile": "https://github.com/wwawwaww",
"contributions": [
"bug"
]
},
{
"login": "dreamerblue",
"name": "bLue",
"avatar_url": "https://avatars.githubusercontent.com/u/19774268?v=4",
"profile": "https://dreamer.blue/",
"contributions": [
"code"
]
}
],
"contributorsPerLine": 6,
"contributorTemplate": "\" width=\"<%= options.imageSize %>px;\" alt=\"\"/> \"><%= contributor.name %>\">🔗 <%= contributions %>",
"contributorsSortAlphabetically": true,
"projectName": "acm-statistics",
"projectOwner": "Liu233w",
"repoType": "github",
"repoHost": "https://github.com",
"skipCi": true,
"commitConvention": "none",
"commitType": "docs"
}
================================================
FILE: .editorconfig
================================================
[*.js]
indent_size = 2
================================================
FILE: .gitattributes
================================================
# Auto detect text files and perform LF normalization
* text=auto
# Custom for Visual Studio
*.cs diff=csharp
# Standard to msysgit
*.doc diff=astextplain
*.DOC diff=astextplain
*.docx diff=astextplain
*.DOCX diff=astextplain
*.dot diff=astextplain
*.DOT diff=astextplain
*.pdf diff=astextplain
*.PDF diff=astextplain
*.rtf diff=astextplain
*.RTF diff=astextplain
# 忽略Migration文件
/backend/src/AcmStatisticsBackend.EntityFrameworkCore/Migrations/* linguist-vendored
/ohunt/OHunt.Web/Migrations/* linguist-vendored
================================================
FILE: .github/.vscode/settings.json
================================================
{
"cSpell.words": [
"endgroup"
]
}
================================================
FILE: .github/mergify.yml
================================================
pull_request_rules:
- name: automatic merge on CI success and tag
conditions:
- label=ready-to-be-merged
# checks =====
- check-success=Html Snapshot Test
- check-success=E2E on push
- check-success=E2E on pull request
- check-success=Test Backend
- check-success=Test Crawler
- check-success=Test Crawler Api Backend
- check-success=Test Frontend
- check-success=Test Captcha Service
- check-success=Test OHunt
- check-success=Commitlint
# =============
actions:
merge:
method: rebase
# rebase_fallback: merge
- name: refactored queue action rule
conditions: []
actions:
queue:
queue_rules:
- name: default
queue_conditions:
- label=ready-to-be-merged
- check-success=Html Snapshot Test
- check-success=E2E on push
- check-success=E2E on pull request
- check-success=Test Backend
- check-success=Test Crawler
- check-success=Test Crawler Api Backend
- check-success=Test Frontend
- check-success=Test Captcha Service
- check-success=Test OHunt
- check-success=Commitlint
merge_conditions:
# Conditions to get out of the queue (= merged)
# checks =====
- check-success=Html Snapshot Test
- check-success=E2E on push
- check-success=E2E on pull request
- check-success=Test Backend
- check-success=Test Crawler
- check-success=Test Crawler Api Backend
- check-success=Test Frontend
- check-success=Test Captcha Service
- check-success=Test OHunt
- check-success=Commitlint
# =============
merge_method: rebase
================================================
FILE: .github/workflows/auto-cancellation.yml
================================================
name: Cancelling Duplicates
on:
workflow_run:
workflows: ['Test E2E']
types: ['requested']
jobs:
cancel-duplicate-workflow-runs:
name: "Cancel duplicate workflow runs"
runs-on: ubuntu-latest
steps:
- uses: potiuk/cancel-workflow-runs@master
name: "Cancel duplicate workflow runs"
with:
cancelMode: allDuplicates
token: ${{ secrets.GITHUB_TOKEN }}
sourceRunId: ${{ github.event.workflow_run.id }}
================================================
FILE: .github/workflows/deploy.yml
================================================
name: auto deploy on master
on:
push:
branches:
- master
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: 'Checkout'
uses: actions/checkout@v3
- name: Wait for status checks
id: check
uses: WyriHaximus/github-action-wait-for-status@v1.8
with:
ignoreActions: codecov/project,codecov/patch,deploy,E2E on pull request,update-snapshot,Update HTML Snapshot when comment on pr,Update E2E Snapshot when comment on pr,crawler-check,检查爬虫可用性(不准确)
checkInterval: 60
env:
GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}"
- name: Deploy
if: steps.check.outputs.status == 'success'
run: |
echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin
make tag-and-push
- name: Failed
if: steps.check.outputs.status != 'success'
run: |
echo deploy check status "${{ steps.check.outputs.status }}"
exit 1
================================================
FILE: .github/workflows/e2e-test-pr.yml
================================================
name: Test E2E on pull request
on: pull_request
jobs:
e2e-pr:
name: E2E on pull request
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- run: |
cd e2e
echo ::group::build
make server compose-args="--detach"
make wait-server
echo ::endgroup::build
make ci-no-record
make run run-cmd="npm run lint" make-args="no-interactive no-tty"
- uses: actions/upload-artifact@v4
if: failure()
with:
name: e2e-screenshots
path: e2e/cypress/screenshots
- uses: actions/upload-artifact@v4
if: failure()
with:
name: e2e-snapshots
path: e2e/cypress/snapshots
- uses: actions/upload-artifact@v4
if: failure()
with:
name: e2e-videos
path: e2e/cypress/videos
================================================
FILE: .github/workflows/e2e-test-push.yml
================================================
name: Test E2E on push
on: push
jobs:
e2e-push:
name: E2E on push
runs-on: ubuntu-latest
env:
CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
steps:
- uses: actions/checkout@master
- run: |
cd e2e
echo ::group::build
make server compose-args="--detach"
make wait-server
echo ::endgroup::build
make ci
make run run-cmd="npm run lint" make-args="no-interactive no-tty"
- run: |
cd build
docker compose -f docker-compose.yml -f docker-compose.e2e.yml logs --no-color > e2e.log
if: failure()
- uses: actions/upload-artifact@v4
if: failure()
with:
name: server-logs
path: build/e2e.log
================================================
FILE: .github/workflows/html-test.yml
================================================
name: Html Snapshot Tests
on: [push, pull_request]
jobs:
html-snapshot-test:
name: Html Snapshot Test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- run: |
cd e2e
echo ::group::build
make server compose-args="--detach"
make wait-server
echo ::endgroup::build
make test-html-ci
================================================
FILE: .github/workflows/sonar-cloud.yml
================================================
name: Sonar Cloud Analysis
on:
push:
branches:
- '**'
jobs:
sonarCloudTrigger:
name: SonarCloud Trigger
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: SonarCloud Scan
uses: sonarsource/sonarcloud-github-action@master
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
================================================
FILE: .github/workflows/unit-test.yml
================================================
name: Unit Tests
on: [push, pull_request]
jobs:
backend:
name: Test Backend
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- run: |
cd backend
# smoke test and lint
make run run-cmd="dotnet build" make-args="no-interactive no-tty"
make test-ci
crawler:
name: Test Crawler
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- run: |
cd crawler
make run run-cmd="npm run lint" make-args="no-interactive no-tty"
make test-ci
crawler-api-backend:
name: Test Crawler Api Backend
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- run: |
cd crawler-api-backend
make run run-cmd="npm run lint" make-args="no-interactive no-tty"
make test-ci
frontend:
name: Test Frontend
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- run: |
cd frontend
make run run-cmd="npm run lint" make-args="no-interactive no-tty"
make test-ci
captcha-service:
name: Test Captcha Service
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- run: |
cd captcha-service
make run run-cmd="npm run lint" make-args="no-interactive no-tty"
make test-ci
ohunt:
name: Test OHunt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- run: |
cd ohunt
# smoke test and lint
make run run-cmd="dotnet build" make-args="no-interactive no-tty"
make test-ci
commitlint:
name: Commitlint
runs-on: ubuntu-latest
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
steps:
- uses: actions/checkout@master
with:
fetch-depth: 0
- uses: wagoid/commitlint-github-action@9763196e10f27aef304c9b8b660d31d97fce0f99 # v5
================================================
FILE: .github/workflows/update-e2e-snapshot.yml
================================================
name: Update E2E Snapshot when comment on pr
on:
issue_comment:
types: [created]
jobs:
update-snapshot:
# The type of runner that the job will run on
runs-on: ubuntu-latest
if: contains(github.event.comment.html_url, '/pull/') && contains(github.event.comment.body, '/update-e2e-snapshot')
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
- name: listen for PR Comments
uses: machine-learning-apps/actions-chatops@master
with:
TRIGGER_PHRASE: "/update-e2e-snapshot"
env: # you must supply GITHUB_TOKEN
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
id: prcomm
# This step clones the branch of the PR associated with the triggering phrase, but only if it is triggered.
- name: clone branch of PR
if: steps.prcomm.outputs.BOOL_TRIGGERED == 'true'
uses: actions/checkout@master
with:
ref: ${{ steps.prcomm.outputs.BRANCH_NAME }}
- name: Show current running workflows' id
if: steps.prcomm.outputs.BOOL_TRIGGERED == 'true'
uses: peter-evans/create-or-update-comment@23ff15729ef2fc348714a3bb66d2f655ca9066f2 # v3
with:
token: ${{ secrets.GITHUB_TOKEN }}
issue-number: ${{ github.event.issue.number }}
body: |
Update E2E Snapshot Triggered!
Address: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
- name: Try update snapshot
if: steps.prcomm.outputs.BOOL_TRIGGERED == 'true'
run: |
cd e2e
echo ::group::build
make server compose-args="--detach"
make wait-server
echo ::endgroup::build
make update-snapshot
make test # ensure test pass after update
- name: Commit result
if: steps.prcomm.outputs.BOOL_TRIGGERED == 'true'
run: |
git pull
git config --global user.name ${{ github.event.comment.user.login }}
git config --global user.email ${{ github.event.comment.user.login }}@github.fake
git add .
git commit -am 'test(e2e): update snapshot'
- name: Push changes
if: steps.prcomm.outputs.BOOL_TRIGGERED == 'true'
uses: ad-m/github-push-action@master
with:
# use my own token instead of GITHUB_TOKEN to trigger future workflows
github_token: ${{ secrets.WORKFLOW_TOKEN }}
branch: ${{ steps.prcomm.outputs.BRANCH_NAME }}
- name: Upload artifact if failed
uses: actions/upload-artifact@v4
if: failure() && steps.prcomm.outputs.BOOL_TRIGGERED == 'true'
with:
name: e2e-snapshots
path: e2e/cypress/snapshots
- name: Upload artifact if failed
uses: actions/upload-artifact@v4
if: failure() && steps.prcomm.outputs.BOOL_TRIGGERED == 'true'
with:
name: e2e-videos
path: e2e/cypress/videos
================================================
FILE: .github/workflows/update-html-snapshot.yml
================================================
name: Update HTML Snapshot when comment on pr
on:
issue_comment:
types: [created]
jobs:
update-snapshot:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
- name: listen for PR Comments
uses: machine-learning-apps/actions-chatops@master
with:
TRIGGER_PHRASE: "/update-html-snapshot"
env: # you must supply GITHUB_TOKEN
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
id: prcomm
# This step clones the branch of the PR associated with the triggering phrase, but only if it is triggered.
- name: clone branch of PR
if: steps.prcomm.outputs.BOOL_TRIGGERED == 'true'
uses: actions/checkout@master
with:
ref: ${{ steps.prcomm.outputs.BRANCH_NAME }}
- name: Show current running workflows' id
if: steps.prcomm.outputs.BOOL_TRIGGERED == 'true'
uses: peter-evans/create-or-update-comment@23ff15729ef2fc348714a3bb66d2f655ca9066f2 # v3
with:
token: ${{ secrets.GITHUB_TOKEN }}
issue-number: ${{ github.event.issue.number }}
body: |
Update HTML Snapshot Triggered!
Address: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
- name: Try update snapshot
if: steps.prcomm.outputs.BOOL_TRIGGERED == 'true'
run: |
cd e2e
echo ::group::build
make server compose-args="--detach"
make wait-server
echo ::endgroup::build
make update-html-snapshot
make test-html-ci # ensure test pass after update
- name: Commit result
if: steps.prcomm.outputs.BOOL_TRIGGERED == 'true'
run: |
git pull
git config --global user.name ${{ github.event.comment.user.login }}
git config --global user.email ${{ github.event.comment.user.login }}@github.fake
git add .
git commit -am 'test(e2e): update html snapshot'
- name: Push changes
if: steps.prcomm.outputs.BOOL_TRIGGERED == 'true'
uses: ad-m/github-push-action@master
with:
# use my own token instead of GITHUB_TOKEN to trigger future workflows
github_token: ${{ secrets.WORKFLOW_TOKEN }}
branch: ${{ steps.prcomm.outputs.BRANCH_NAME }}
================================================
FILE: .gitignore
================================================
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff:
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
# Gradle:
.idea/**/gradle.xml
.idea/**/libraries
# CMake
cmake-build-debug/
cmake-build-release/
# Mongo Explorer plugin:
.idea/**/mongoSettings.xml
## File-based project format:
*.iws
## Plugin-specific files:
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Created by https://www.gitignore.io/api/visualstudiocode
# Edit at https://www.gitignore.io/?templates=visualstudiocode
### VisualStudioCode ###
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
### VisualStudioCode Patch ###
# Ignore all local history of files
.history
# End of https://www.gitignore.io/api/visualstudiocode
# ionide of vscode
.ionide
# macOS
.DS_Store
# idea in root
/.idea
================================================
FILE: .imgbotconfig
================================================
{
"ignoredFiles": [
"e2e/*",
]
}
================================================
FILE: .renovaterc.json
================================================
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base",
"docker:enableMajor",
"monorepo:dotnet"
],
"packageRules": [
{
"groupName": "aspnetboilerplate",
"packagePatterns": ["^Abp\\.|^Abp$"]
},
{
"groupName": "chartjs",
"matchPackageNames": [
"vue-chartjs",
"chart.js"
]
}
],
"ignorePresets": [
":ignoreModulesAndTests"
],
"commitMessagePrefix": "chore(*):",
"labels": ["dependencies", "ready-to-be-merged"],
"automerge": false,
"dockerfile": {
"fileMatch": ["(^|/|\\.)Dockerfile$"]
}
}
================================================
FILE: LICENSE
================================================
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C) {{ year }} {{ organization }}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
================================================
FILE: Makefile
================================================
## root makefile
include ./build/share.mk
.PHONY: default
default: .short-help ;
# == common suffix ==
# use command like `make target=crawler test clean` to invoke `make -C crawler test clean`
# support command like `make target="crawler frontend" build`
TargetList = crawler frontend crawler-api-backend backend captcha-service e2e ohunt
AllTarget := $(if $(target),$(target),$(TargetList))
test:
@echo testing target: $(AllTarget)
for dir in $(AllTarget); do \
$(MAKE) -C $$dir test; \
done
build:
@echo building target: $(AllTarget)
for dir in $(AllTarget); do \
$(MAKE) -C $$dir build; \
done
run:
@echo running target: $(AllTarget)
for dir in $(AllTarget); do \
$(MAKE) -C $$dir run; \
done
clean:
# remove all stopped containers
docker rm $(shell docker ps -a -q); true
for dir in $(AllTarget); do \
$(MAKE) -C $$dir clean; \
done
ifeq ($(target),)
cd ./build && $(MAKE) -f node-base.mk clean
cd ./build && $(MAKE) -f commitlint.mk clean
cd ./build && $(MAKE) -f shell.mk clean
@echo cleaned all target
@echo running docker system prune
docker system prune -f
else
@echo cleaned $(target)
endif
test-ci:
@echo testing ci on target: $(AllTarget)
for dir in $(AllTarget); do \
$(MAKE) -C $$dir test-ci; \
done
# === commitlint ===
.PHONY: test-commit
test-commit:
cd ./build && $(MAKE) -f commitlint.mk test-commit
# === publish image ===
.PHONY: tag-and-push
tag-and-push:
cd ./build && $(MAKE) -f docker-compose.mk push
# === run all ===
.PHONY: up
up:
cd ./build && $(MAKE) -f docker-compose.mk up
# === util command ==
.PHONY: show-image-size shell
# 输出项目中 latest 标签标记的镜像的大小
show-image-size:
docker images --format "table {{.Repository}}:{{.Tag}}\t{{.Size}}" --filter=reference='acm-statistics*:latest'
shell:
cd build && $(MAKE) -f shell.mk shell
# === help ===
.PHONY: help
define HELP_MESSAGE
Makefile of acm-statistics
Available goals:
test build run clean test-ci test-commit commitlint-travis tag-and-push up view-image-size shell help
You can use `target` variable to set target module when using test, build, run, clean,
and test-ci commands. E.g. `make test target="frontend crawler"` means running test only
in frontend and crawler module. If target is not specified, run the command on all modules.
Besides, the dependency is automatically resolved by makefile. So you do not need to run
build before test.
Documents of available goals:
test
Running all tests
build
build the project or certain modules.
If argument `build-args` is specified, it is attached to all `docker build` commands
run
Run shell command in modules.
E.g. `make run run-cmd="pnpm run lint"` runs `npm run lint` in all modules.
Available parameters:
run-cmd: The command to be run.
run-args: The extra arguments sent to docker. E.g. run following commands in fontend directory to send argument -v '...' to docker:
>> make run run-cmd="pnpm test -- --update-snapshot" run-args="-v './__test__:/var/project/__test__'"
make-args: run-args will automatically send following switches to docker: --rm, --interactive, --tty, which can be turned off by following switches: `r`/`no-rm`, `i`/`no-interactive`, `t`/`no-tty`.
E.g. the following command turns `run-args` into `--tty` (`--rm` and `--interactive` are disabled):
>> make run make-args="r i"
Noticed that commands should be separated even they are single letters.
clean
Clean images that are built
test-ci
Run tests in CI environment. It behaves differently than normal tests. E.g. Specifying `--ci` to jest and disabling tests that require network.
test-commit
Lint commits from master branch to HEAD by commitlint.
tag-and-push
Tag the built images and publish. By default, it uses `liu233w` as namespace.
You may refer to `./build/docker-compose.mk` to change this behaviour.
up
Run the project using docker-compose. It automatically creates config file `./build/.env`.
It is recommended to modify the file based on the comments inside.
If you run it on windows, it is recommended to use msys2 shell after configure it to accept the path of windows
show-image-size
Show the size of all images built by the project. It does not create new images.
shell
Spawn a shell inside docker container and mount the whole project into it. So you can run commands and modify the project in Linux environment.
help
Show this doc.
Most of the sub-directory supports make commands like the root directory. View the `Makefile` for more information.
endef
.short-help:
@echo run \"make help\" to get help
export HELP_MESSAGE
help:
@echo "$$HELP_MESSAGE" | more
================================================
FILE: README.md
================================================
# This Project will be deprecated. Please use [OJHunt Lite](https://github.com/Liu233w/ojhunt-lite) instead.
# This repo contains the source code of OJ Analyzer
简体中文版:[README_zh-hans.md](./README_zh-hans.md)
[](https://app.zenhub.com/workspace/o/liu233w/acm-statistics/boards?repos=125616473)
[](https://sonarcloud.io/dashboard?id=acm-statistics)
[](https://codecov.io/gh/Liu233w/acm-statistics)
[](https://dashboard.cypress.io/#/projects/4s32o7/runs)
[](https://app.renovatebot.com/dashboard#github/Liu233w/acm-statistics)
[](https://mergify.io)
[](#contributors-)
#### Build status


#### Features
- Querying ac/submissions of oj
- Storing querying history
#### Under development
- Email support
- Ranks
- ……
## Directory structure
- frontend: The front end
- crawler: Crawlers to query OJs. Being used by both frontend and backend
- crawler-api-backend: A microservice that provides querying api
- e2e: E2E tests
- backend: The back end, a monoservice
- captcha-service: A microservice that provides captcha support
- ohunt: A stateful, standalone crawler microservice used to support certain OJs such as ZOJ.
- build: Codes to build and deploy the project. Tool chain: docker, docker-compose, GNU make.
- tools: Utility scripts and config files in operation
See the README file in each module for specific documents.
## Developing and deploying in docker
- The project needs docker and docker-compose to function correctly.
### Development
- This project uses makefile to manage dependency between modules. Execute `make help` in repository root to view document.
- GNU make is required.
### Deploy
There are two ways to deploy this project in a server.
#### One-liner
Execute following code in shell to deploy the project to port 3000.
`curl -s https://raw.githubusercontent.com/Liu233w/acm-statistics/master/tools/remote-docker-up.sh | bash`
Vjudge crawler is not available in this way.
#### Config file version
In this way you are able to customise the configuration, enabling all features.
```bash
# Create a folder to store config files
mkdir -p ~/www/acm-statistics
cd ~/www/acm-statistics
# Download runner script and add permissions
curl https://raw.githubusercontent.com/Liu233w/acm-statistics/master/tools/remote-docker-up.sh -o run.sh
chmod +x run.sh
# Run the script once to generate configuration file. It will exit after the line `.env file created, remember to edit it` is shown.
./run.sh
# Edit the config file following the description in it.
vim .env
# Now we can run the project by the script
./run.sh
```
Then you can use tools such as systemd to run `./run.sh`.
[./tools/acm-statistics.service](./tools/acm-statistics.service) is a template config file of systemd.
`run.sh` checks updates when it is starting. If there are updates to `template.env`, `run.sh` will exit and ask you to compare these two files. **The script compares the line count of the two files to check update, please make sure they are identical when editing.**
## Management
- Set the url of adminer in `.env` file. It is `/adminer` by default.
- You can view and edit database via adminer.
- The name of the database is `acm_statistics`. Username is `root`. You can set password in `.env`
- Backups are created automatically in 3:00am each day, stored in `db-backup` folder, which is in the folder that contains config files.
## License
- All source code except the code in `crawler/crawlers` are under AGPL-3.0 license
- The code in `crawler/crawlers` are under BSD 2-Clause license.
## Contribution
- All contribution especially crawlers are welcomed.
- Please follow [Commit Message Conventions](https://gist.github.com/stephenparish/9941e89d80e2bc58a153) when writing git commit messages.
- You may use [cz-cli](https://github.com/commitizen/cz-cli) to help writing commit messages.
## Contributors ✨
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
================================================
FILE: README_zh-hans.md
================================================
新版 NWPU-ACM 查询系统
===
中文版文档可能有不准确之处,请以英文版文档为准。
[](https://app.zenhub.com/workspace/o/liu233w/acm-statistics/boards?repos=125616473)
[](https://sonarcloud.io/dashboard?id=acm-statistics)
[](https://codecov.io/gh/Liu233w/acm-statistics)
[](https://dashboard.cypress.io/#/projects/4s32o7/runs)
[](https://app.renovatebot.com/dashboard#github/Liu233w/acm-statistics)
[](https://mergify.io)
[](#contributors-)
#### 构建状态


#### 功能
- 题量查询
#### 开发中
- 历史记录
- 题量追踪
- 邮件提醒
- 排行榜
- 查重
- ……
## 目录结构
- frontend: 前端
- crawler: 题量查询爬虫,可以同时被前端和后端使用
- crawler-api-backend: 题量查询后端,提供了查询API
- e2e: 关于 e2e 测试相关的代码。
- backend: 后端代码
- captcha-service: 验证码微服务
- ohunt: 有状态爬虫微服务。负责一些需要用数据库储存状态的爬虫。
- build: 存储了 docker 和 make 相关的代码和配置文件,用于构建和部署
- tools: 存储了部分脚本,各种用途都有
每个模块的具体内容请参考模块内的 README
## docker 方式部署、开发
- 目前的跨模块调用已经改成了基于docker的代码,因此有些功能(比如调用 crawler-api-backend)必须使用 docker 来启动
- 要使用这个功能,必须安装 docker 和 docker-compose
### 开发
- 本项目使用了 makefile 来管理模块间的依赖,请在根目录执行 `make help` 来查看说明。
- 要使用此方式进行开发,开发机还必须安装有 GNU make
### 部署
docker 方式简化了部署难度,这里有两种部署方式。请确保服务器安装了最新版本的 docker 和 docker-compose
#### 一行代码版
在 shell 中执行 `curl -s https://raw.githubusercontent.com/Liu233w/acm-statistics/master/tools/remote-docker-up.sh | bash` 即可将整个项目部署到 3000 端口。
这样做的话将无法使用 vjudge 爬虫,所以还是建议使用下面的配置文件版本。
#### 配置文件版
上面的一行代码版无法更改配置,建议用下面的这个配置文件版,按下面的步骤进行部署:
```bash
# 建立一个存放脚本和配置文件的文件夹,这里可以随便挑你喜欢的路径
mkdir -p ~/www/acm-statistics
cd ~/www/acm-statistics
# 下载脚本、添加权限
curl https://raw.githubusercontent.com/Liu233w/acm-statistics/master/tools/remote-docker-up.sh -o run.sh
chmod +x run.sh
# 试运行脚本以生成配置文件,在显示 `.env file created, remember to edit it` 之后会自动退出脚本
./run.sh
# 编辑配置文件,按照上面的说明进行修改即可
vim .env
# 现在即可正常运行脚本
./run.sh
```
设置成功之后即可使用单独的 `./run.sh` 来运行脚本,使用 systemd 或者其他工具均可。
`./tools/acm-statistics.service` 里是一个 systemd 配置文件的参考。
如果默认的 `template.env` 有更新,`run.sh` 会自动退出并提示您更新 `.env`。**脚本通过比较两个文件的行数来判断是否有更新,在编辑文件时请确保行数一致**
## 管理
- 在 .env 文件中设定 adminer 的url,默认为 `/adminer`
- 可以查看并修改数据库
- 数据库名称为 acm_statistics,用户名为 root,密码在 .env 中设定
- 数据库会在每天3:00am自动进行备份,保存在 `/db-backup` 中
## 开源协议
- 如无特殊声明,均为 AGPL-3.0 协议
- crawler 模块中的 `crawlers` 目录中的文件为 BSD 2-Clause 协议
## 贡献代码
- 欢迎任何人贡献代码(尤其是爬虫部分)。
- git 的提交格式遵循 [Git Commit Angular 规范](https://gist.github.com/stephenparish/9941e89d80e2bc58a153)
([中文版](http://www.ruanyifeng.com/blog/2016/01/commit_message_change_log.html))
- 您可以使用 [cz-cli](https://github.com/commitizen/cz-cli) 来辅助提交 commit
================================================
FILE: backend/.config/dotnet-tools.json
================================================
{
"version": 1,
"isRoot": true,
"tools": {
"dotnet-ef": {
"version": "7.0.20",
"commands": [
"dotnet-ef"
]
}
}
}
================================================
FILE: backend/.dockerignore
================================================
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
**/App_Data
# coverage file
coverage.cobertura.xml
================================================
FILE: backend/.gitattributes
================================================
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
================================================
FILE: backend/.gitignore
================================================
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# DNX
project.lock.json
artifacts/
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# TODO: Comment the next line if you want to checkin your web deploy settings
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/packages/*
# except build/, which is used as an MSBuild target.
!**/packages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/packages/repositories.config
# NuGet v3's project.json files produces more ignoreable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
orleans.codegen.cs
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# App_Data
/src/AcmStatisticsBackend.Web.Host/App_Data/*
# coverage file
coverage.cobertura.xml
================================================
FILE: backend/AcmStatisticsBackend.sln
================================================
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29911.84
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{AFAA0841-BD93-466F-B8F4-FB4EEC86F1FC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{F10AA149-2626-486E-85BB-9CD5365F3016}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AcmStatisticsBackend.Core", "src\AcmStatisticsBackend.Core\AcmStatisticsBackend.Core.csproj", "{0FA75A5B-AB83-4FD0-B545-279774C01E87}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AcmStatisticsBackend.Application", "src\AcmStatisticsBackend.Application\AcmStatisticsBackend.Application.csproj", "{3870C648-4AEA-4B85-BA3F-F2F63B96136A}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AcmStatisticsBackend.Tests", "test\AcmStatisticsBackend.Tests\AcmStatisticsBackend.Tests.csproj", "{0D4C5D00-C144-4213-A007-4B8944113AB1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AcmStatisticsBackend.Web.Host", "src\AcmStatisticsBackend.Web.Host\AcmStatisticsBackend.Web.Host.csproj", "{38E184BD-E874-4633-A947-AED4FDB73F40}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AcmStatisticsBackend.Web.Core", "src\AcmStatisticsBackend.Web.Core\AcmStatisticsBackend.Web.Core.csproj", "{22CFE0D2-8DCA-42D7-AD7D-784C3862493F}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AcmStatisticsBackend.EntityFrameworkCore", "src\AcmStatisticsBackend.EntityFrameworkCore\AcmStatisticsBackend.EntityFrameworkCore.csproj", "{E0580562-F8F2-4EBB-B07A-ABFC6F2C314F}"
EndProject
Project("{E53339B2-1760-4266-BCC7-CA923CBCF16C}") = "docker-compose", "..\build\docker-compose.dcproj", "{5AE26E44-7AFE-4443-AA6E-F3FDF9519BFD}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{1CD24D5F-EC67-4825-B43D-031CD8027031}"
ProjectSection(SolutionItems) = preProject
Directory.Build.props = Directory.Build.props
stylecop.json = stylecop.json
StyleCop.ruleset = StyleCop.ruleset
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{0FA75A5B-AB83-4FD0-B545-279774C01E87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0FA75A5B-AB83-4FD0-B545-279774C01E87}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0FA75A5B-AB83-4FD0-B545-279774C01E87}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0FA75A5B-AB83-4FD0-B545-279774C01E87}.Release|Any CPU.Build.0 = Release|Any CPU
{3870C648-4AEA-4B85-BA3F-F2F63B96136A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3870C648-4AEA-4B85-BA3F-F2F63B96136A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3870C648-4AEA-4B85-BA3F-F2F63B96136A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3870C648-4AEA-4B85-BA3F-F2F63B96136A}.Release|Any CPU.Build.0 = Release|Any CPU
{0D4C5D00-C144-4213-A007-4B8944113AB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0D4C5D00-C144-4213-A007-4B8944113AB1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0D4C5D00-C144-4213-A007-4B8944113AB1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0D4C5D00-C144-4213-A007-4B8944113AB1}.Release|Any CPU.Build.0 = Release|Any CPU
{38E184BD-E874-4633-A947-AED4FDB73F40}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{38E184BD-E874-4633-A947-AED4FDB73F40}.Debug|Any CPU.Build.0 = Debug|Any CPU
{38E184BD-E874-4633-A947-AED4FDB73F40}.Release|Any CPU.ActiveCfg = Release|Any CPU
{38E184BD-E874-4633-A947-AED4FDB73F40}.Release|Any CPU.Build.0 = Release|Any CPU
{22CFE0D2-8DCA-42D7-AD7D-784C3862493F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{22CFE0D2-8DCA-42D7-AD7D-784C3862493F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{22CFE0D2-8DCA-42D7-AD7D-784C3862493F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{22CFE0D2-8DCA-42D7-AD7D-784C3862493F}.Release|Any CPU.Build.0 = Release|Any CPU
{E0580562-F8F2-4EBB-B07A-ABFC6F2C314F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E0580562-F8F2-4EBB-B07A-ABFC6F2C314F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E0580562-F8F2-4EBB-B07A-ABFC6F2C314F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E0580562-F8F2-4EBB-B07A-ABFC6F2C314F}.Release|Any CPU.Build.0 = Release|Any CPU
{5AE26E44-7AFE-4443-AA6E-F3FDF9519BFD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5AE26E44-7AFE-4443-AA6E-F3FDF9519BFD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5AE26E44-7AFE-4443-AA6E-F3FDF9519BFD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5AE26E44-7AFE-4443-AA6E-F3FDF9519BFD}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{0FA75A5B-AB83-4FD0-B545-279774C01E87} = {AFAA0841-BD93-466F-B8F4-FB4EEC86F1FC}
{3870C648-4AEA-4B85-BA3F-F2F63B96136A} = {AFAA0841-BD93-466F-B8F4-FB4EEC86F1FC}
{0D4C5D00-C144-4213-A007-4B8944113AB1} = {F10AA149-2626-486E-85BB-9CD5365F3016}
{38E184BD-E874-4633-A947-AED4FDB73F40} = {AFAA0841-BD93-466F-B8F4-FB4EEC86F1FC}
{22CFE0D2-8DCA-42D7-AD7D-784C3862493F} = {AFAA0841-BD93-466F-B8F4-FB4EEC86F1FC}
{E0580562-F8F2-4EBB-B07A-ABFC6F2C314F} = {AFAA0841-BD93-466F-B8F4-FB4EEC86F1FC}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {8C07C326-4D17-4200-88B1-4DD423C6392C}
EndGlobalSection
EndGlobal
================================================
FILE: backend/AcmStatisticsBackend.sln.DotSettings
================================================
FalseTrueTrueTrueTrueTrueTrue
================================================
FILE: backend/Directory.Build.props
================================================
../../StyleCop.rulesetfalseallruntime; build; native; contentfiles; analyzers; buildtransitive
================================================
FILE: backend/Makefile
================================================
## makefile for backend
include ../build/share.mk
help:
@echo run \"make help\" in root directory to get help
.base:
docker build . \
-f dev.Dockerfile \
-t $(BackendBaseTag) \
$(build-args)
build:
docker build . \
-f src/AcmStatisticsBackend.Web.Host/Dockerfile \
-t $(BackendTag) \
$(build-args)
test: .base
docker run --rm -t $(BackendBaseTag) dotnet test
run: .base
docker run $(run-args) $(BackendBaseTag) $(run-cmd)
clean:
docker image rm $(BackendTag) $(BackendBaseTag); true
test-ci: .base
docker run --rm \
-v "$(CURDIR)/test/AcmStatisticsBackend.Tests/TestResults:/src/test/AcmStatisticsBackend.Tests/TestResults" \
$(BackendBaseTag) \
dotnet test --collect:"XPlat Code Coverage"
================================================
FILE: backend/README.md
================================================
# 后端代码 (abp实现)
## 运行环境
- docker docker-compose
## 开发环境
- docker docker-compose (必要)
- dotnet core 3.1
- Visual Studio 2019 (安装docker支持)
## 运行方式
本项目不能脱离docker运行。
### 仅运行
- 仅运行时不需要装有vs 2019或者dotnet core开发环境
- 与其他项目相同,使用 `make build` 进行构建,`make test`进行测试
### 开发
- 可以直接使用visual studio 2019的container tool进行调试
- 使用vs打开sln文件,将 docker-compose 设为启动项目,然后直接调试即可
- 在进行调试之前,需要先在本目录的上级目录运行 `make build` 来构建其他依赖项
- 在调试状态下,可以从 `localhost:8080` 访问数据库信息
- 在 `../build/.env` 文件中查看和修改默认密码等数据
================================================
FILE: backend/StyleCop.ruleset
================================================
================================================
FILE: backend/dev.Dockerfile
================================================
FROM mcr.microsoft.com/dotnet/sdk:8.0
# needed in sln file
RUN mkdir /build && echo '' > /build/docker-compose.dcproj
WORKDIR /src
COPY ["src/AcmStatisticsBackend.Web.Host/AcmStatisticsBackend.Web.Host.csproj", "src/AcmStatisticsBackend.Web.Host/"]
COPY ["src/AcmStatisticsBackend.Web.Core/AcmStatisticsBackend.Web.Core.csproj", "src/AcmStatisticsBackend.Web.Core/"]
COPY ["src/AcmStatisticsBackend.EntityFrameworkCore/AcmStatisticsBackend.EntityFrameworkCore.csproj", "src/AcmStatisticsBackend.EntityFrameworkCore/"]
COPY ["src/AcmStatisticsBackend.Core/AcmStatisticsBackend.Core.csproj", "src/AcmStatisticsBackend.Core/"]
COPY ["src/AcmStatisticsBackend.Application/AcmStatisticsBackend.Application.csproj", "src/AcmStatisticsBackend.Application/"]
COPY ["test/AcmStatisticsBackend.Tests/AcmStatisticsBackend.Tests.csproj", "test/AcmStatisticsBackend.Tests/"]
RUN dotnet restore "src/AcmStatisticsBackend.Web.Host/AcmStatisticsBackend.Web.Host.csproj"
RUN dotnet restore "test/AcmStatisticsBackend.Tests/AcmStatisticsBackend.Tests.csproj"
COPY . .
================================================
FILE: backend/global.json
================================================
{
"sdk": {
"version": "8.0.418",
"rollForward": "latestMajor",
"allowPrerelease": false
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Accounts/AccountAppService.cs
================================================
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Abp.Authorization;
using Abp.IdentityFramework;
using Abp.Runtime.Session;
using Abp.UI;
using AcmStatisticsBackend.Accounts.Dto;
using AcmStatisticsBackend.Authorization;
using AcmStatisticsBackend.Authorization.Users;
using AcmStatisticsBackend.ServiceClients;
using Microsoft.AspNetCore.Identity;
namespace AcmStatisticsBackend.Accounts
{
public class AccountAppService : AcmStatisticsBackendAppServiceBase, IAccountAppService
{
private readonly UserRegistrationManager _userRegistrationManager;
private readonly ICaptchaServiceClient _captchaServiceClient;
private readonly UserManager _userManager;
private readonly IAbpSession _abpSession;
private readonly LogInManager _logInManager;
private readonly IPasswordHasher _passwordHasher;
public AccountAppService(
UserRegistrationManager userRegistrationManager, ICaptchaServiceClient captchaServiceClient,
UserManager userManager, IAbpSession abpSession, LogInManager logInManager,
IPasswordHasher passwordHasher)
{
_userRegistrationManager = userRegistrationManager;
_captchaServiceClient = captchaServiceClient;
_userManager = userManager;
_abpSession = abpSession;
_logInManager = logInManager;
_passwordHasher = passwordHasher;
}
public async Task Register(RegisterInput input)
{
var captchaResult = await _captchaServiceClient.ValidateAsync(input.CaptchaId, input.CaptchaText);
if (!captchaResult.Correct)
{
throw new UserFriendlyException(captchaResult.ErrorMessage);
}
await _userRegistrationManager.RegisterAsync(
input.UserName,
input.Password);
return new RegisterOutput
{
CanLogin = true,
};
}
///
[AbpAuthorize]
public async Task SelfDelete()
{
var user = await _userManager.GetUserByIdAsync(_abpSession.GetUserId());
var identityResult = await _userManager.DeleteAsync(user);
identityResult.CheckErrors();
}
///
[AbpAuthorize]
public async Task ChangePassword(ChangePasswordInput input)
{
Debug.Assert(_abpSession.UserId != null, "_abpSession.UserId != null");
var userId = _abpSession.UserId.Value;
var user = await _userManager.GetUserByIdAsync(userId);
var loginAsync = await _logInManager.LoginAsync(user.UserName, input.CurrentPassword, shouldLockout: false);
if (loginAsync.Result != AbpLoginResultType.Success)
{
throw new UserFriendlyException(
"Your 'Existing Password' did not match the one on record. Please try again or contact an administrator for assistance in resetting your password.");
}
user.Password = _passwordHasher.HashPassword(user, input.NewPassword);
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Accounts/Dto/ChangePasswordInput.cs
================================================
using System.ComponentModel.DataAnnotations;
namespace AcmStatisticsBackend.Accounts.Dto
{
public class ChangePasswordInput
{
[Required]
public string CurrentPassword { get; set; }
[Required]
public string NewPassword { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Accounts/Dto/RegisterInput.cs
================================================
using System.ComponentModel.DataAnnotations;
using Abp.Auditing;
using Abp.Authorization.Users;
namespace AcmStatisticsBackend.Accounts.Dto
{
public class RegisterInput
{
[Required]
[StringLength(AbpUserBase.MaxUserNameLength)]
public string UserName { get; set; }
[Required]
[StringLength(AbpUserBase.MaxPlainPasswordLength)]
[DisableAuditing]
public string Password { get; set; }
[Required]
public string CaptchaText { get; set; }
[Required]
public string CaptchaId { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Accounts/Dto/RegisterOutput.cs
================================================
namespace AcmStatisticsBackend.Accounts.Dto
{
public class RegisterOutput
{
public bool CanLogin { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Accounts/IAccountAppService.cs
================================================
using System.Threading.Tasks;
using Abp.Application.Services;
using AcmStatisticsBackend.Accounts.Dto;
namespace AcmStatisticsBackend.Accounts
{
public interface IAccountAppService : IApplicationService
{
Task Register(RegisterInput input);
///
/// Delete this account
///
Task SelfDelete();
///
/// Change password of current user
///
Task ChangePassword(ChangePasswordInput input);
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/AcmStatisticsBackend.Application.csproj
================================================
1.0.0.0net8.0AcmStatisticsBackend.ApplicationAcmStatisticsBackend.ApplicationfalsefalsefalseAcmStatisticsBackendbin\AcmStatisticsBackend.Application.xmlbin\AcmStatisticsBackend.Application.xmlallruntime; build; native; contentfiles; analyzers; buildtransitive
================================================
FILE: backend/src/AcmStatisticsBackend.Application/AcmStatisticsBackendAppServiceBase.cs
================================================
using System;
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.IdentityFramework;
using Abp.Runtime.Session;
using AcmStatisticsBackend.Authorization.Users;
using AcmStatisticsBackend.MultiTenancy;
using Microsoft.AspNetCore.Identity;
namespace AcmStatisticsBackend
{
///
/// Derive your application services from this class.
///
public abstract class AcmStatisticsBackendAppServiceBase : ApplicationService
{
public TenantManager TenantManager { get; set; }
public UserManager UserManager { get; set; }
protected AcmStatisticsBackendAppServiceBase()
{
LocalizationSourceName = AcmStatisticsBackendConsts.LocalizationSourceName;
}
protected virtual async Task GetCurrentUserAsync()
{
var user = await UserManager.FindByIdAsync(AbpSession.GetUserId().ToString());
if (user == null)
{
throw new Exception("There is no current user!");
}
return user;
}
protected virtual Task GetCurrentTenantAsync()
{
return TenantManager.GetByIdAsync(AbpSession.GetTenantId());
}
protected virtual void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/AcmStatisticsBackendApplicationModule.cs
================================================
using Abp.AutoMapper;
using Abp.Modules;
using Abp.Reflection.Extensions;
using AcmStatisticsBackend.Authorization;
namespace AcmStatisticsBackend
{
[DependsOn(
typeof(AcmStatisticsBackendCoreModule),
typeof(AbpAutoMapperModule))]
public class AcmStatisticsBackendApplicationModule : AbpModule
{
public override void PreInitialize()
{
Configuration.Authorization.Providers.Add();
}
public override void Initialize()
{
var thisAssembly = typeof(AcmStatisticsBackendApplicationModule).GetAssembly();
IocManager.RegisterAssemblyByConvention(thisAssembly);
// Scan the assembly for classes which inherit from AutoMapper.Profile
Configuration.Modules.AbpAutoMapper().Configurators.Add(
cfg => cfg.AddMaps(thisAssembly));
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Authorization/AbpLoginResultTypeHelper.cs
================================================
using System;
using Abp;
using Abp.Authorization;
using Abp.Dependency;
using Abp.UI;
namespace AcmStatisticsBackend.Authorization
{
public class AbpLoginResultTypeHelper : AbpServiceBase, ITransientDependency
{
public AbpLoginResultTypeHelper()
{
LocalizationSourceName = AcmStatisticsBackendConsts.LocalizationSourceName;
}
public Exception CreateExceptionForFailedLoginAttempt(AbpLoginResultType result, string usernameOrEmailAddress, string tenancyName)
{
switch (result)
{
case AbpLoginResultType.Success:
return new Exception("Don't call this method with a success result!");
case AbpLoginResultType.InvalidUserNameOrEmailAddress:
case AbpLoginResultType.InvalidPassword:
return new UserFriendlyException(L("InvalidUserNameOrPassword"));
case AbpLoginResultType.InvalidTenancyName:
return new UserFriendlyException(L("ThereIsNoTenantDefinedWithName{0}", tenancyName));
case AbpLoginResultType.TenantIsNotActive:
return new UserFriendlyException(L("TenantIsNotActive", tenancyName));
case AbpLoginResultType.UserIsNotActive:
return new UserFriendlyException(L("UserIsNotActiveAndCanNotLogin", usernameOrEmailAddress));
case AbpLoginResultType.UserEmailIsNotConfirmed:
return new UserFriendlyException(L("UserEmailIsNotConfirmedAndCanNotLogin"));
case AbpLoginResultType.LockedOut:
return new UserFriendlyException(L("UserLockedOutMessage"));
default: // Can not fall to default actually. But other result types can be added in the future and we may forget to handle it
Logger.Warn("Unhandled login fail reason: " + result);
return new UserFriendlyException(L("LoginFailed"));
}
}
public string CreateLocalizedMessageForFailedLoginAttempt(AbpLoginResultType result, string usernameOrEmailAddress, string tenancyName)
{
switch (result)
{
case AbpLoginResultType.Success:
throw new Exception("Don't call this method with a success result!");
case AbpLoginResultType.InvalidUserNameOrEmailAddress:
case AbpLoginResultType.InvalidPassword:
return L("InvalidUserNameOrPassword");
case AbpLoginResultType.InvalidTenancyName:
return L("ThereIsNoTenantDefinedWithName{0}", tenancyName);
case AbpLoginResultType.TenantIsNotActive:
return L("TenantIsNotActive", tenancyName);
case AbpLoginResultType.UserIsNotActive:
return L("UserIsNotActiveAndCanNotLogin", usernameOrEmailAddress);
case AbpLoginResultType.UserEmailIsNotConfirmed:
return L("UserEmailIsNotConfirmedAndCanNotLogin");
default: // Can not fall to default actually. But other result types can be added in the future and we may forget to handle it
Logger.Warn("Unhandled login fail reason: " + result);
return L("LoginFailed");
}
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/DefaultQueryAppService.cs
================================================
using System.Diagnostics;
using System.Threading.Tasks;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using AcmStatisticsBackend.Authorization;
using AcmStatisticsBackend.Crawlers.Dto;
namespace AcmStatisticsBackend.Crawlers
{
///
[AbpAuthorize(PermissionNames.Statistics_DefaultQuery)]
public class DefaultQueryAppService : AcmStatisticsBackendAppServiceBase, IDefaultQueryAppService
{
private readonly IRepository _defaultQueryRepository;
public DefaultQueryAppService(IRepository defaultQueryRepository)
{
_defaultQueryRepository = defaultQueryRepository;
}
///
public async Task GetDefaultQueries()
{
var res = await _defaultQueryRepository.FirstOrDefaultAsync(e => e.UserId == AbpSession.UserId.Value);
return res == null ? new DefaultQueryDto() : ObjectMapper.Map(res);
}
///
public async Task SetDefaultQueries(DefaultQueryDto dto)
{
var entity = ObjectMapper.Map(dto);
Debug.Assert(AbpSession.UserId != null, "AbpSession.UserId != null");
var userId = AbpSession.UserId.Value;
var existEntity = await _defaultQueryRepository.FirstOrDefaultAsync(e => e.UserId == userId);
if (existEntity == null)
{
entity.UserId = userId;
await _defaultQueryRepository.InsertAsync(entity);
}
else
{
existEntity.MainUsername = entity.MainUsername;
existEntity.UsernamesInCrawlers = entity.UsernamesInCrawlers;
}
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/Dto/DefaultQueryDto.cs
================================================
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Abp.AutoMapper;
using Abp.Runtime.Validation;
namespace AcmStatisticsBackend.Crawlers.Dto
{
///
/// Store default query usernames
///
[AutoMap(typeof(DefaultQuery))]
public class DefaultQueryDto : ICustomValidate
{
///
/// main username
///
[MinLength(0)]
public string MainUsername { get; set; } = "";
///
/// Usernames in each crawlers. Key is the name of crawler, value is a list that contains
/// all usernames in this crawler.
///
public Dictionary> UsernamesInCrawlers { get; set; } =
new Dictionary>();
public void AddValidationErrors(CustomValidationContext context)
{
foreach (var usernamesInCrawler in UsernamesInCrawlers)
{
if (usernamesInCrawler.Value == null)
{
context.Results.Add(new ValidationResult("Items in UsernamesInCrawlers should not be null."));
}
}
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/Dto/DeleteQueryHistoryInput.cs
================================================
using System.Diagnostics.CodeAnalysis;
namespace AcmStatisticsBackend.Crawlers.Dto
{
public class DeleteQueryHistoryInput
{
///
/// Delete history by certain id.
///
public long? Id { get; set; }
///
/// Delete histories in the list.
///
[MaybeNull]
public long[] Ids { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/Dto/GetAcWorkerHistoryInput.cs
================================================
using System.ComponentModel.DataAnnotations;
namespace AcmStatisticsBackend.Crawlers.Dto
{
public class GetAcWorkerHistoryInput
{
[Range(1, long.MaxValue)]
public long QueryHistoryId { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/Dto/GetQueryHistoryAndSummaryOutput.cs
================================================
using System;
using System.ComponentModel.DataAnnotations;
namespace AcmStatisticsBackend.Crawlers.Dto
{
public class GetQueryHistoryAndSummaryOutput
{
[Range(1, long.MaxValue)]
public long HistoryId { get; set; }
///
/// The id of the summary.
///
/// It can be null if the summary does not exist
///
[Range(1, long.MaxValue)]
public long? SummaryId { get; set; }
[Required]
public DateTime CreationTime { get; set; }
///
/// Submission count
///
/// Is null if summary does not exist.
///
public int? Submission { get; set; }
///
/// Solved count
///
/// Is null if summary does not exist.
///
public int? Solved { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/Dto/GetQueryHistoryOutput.cs
================================================
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Abp.AutoMapper;
namespace AcmStatisticsBackend.Crawlers.Dto
{
[AutoMap(typeof(QueryHistory))]
public class GetQueryHistoryOutput
{
[Range(1, long.MaxValue)]
public long Id { get; set; }
[Required]
public DateTime CreationTime { get; set; }
///
/// Main username of query history, can be null or empty
///
public string MainUsername { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/Dto/GetQuerySummaryInput.cs
================================================
using System.ComponentModel.DataAnnotations;
namespace AcmStatisticsBackend.Crawlers.Dto
{
public class GetQuerySummaryInput
{
[Range(1, long.MaxValue)]
public long QueryHistoryId { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/Dto/QueryCrawlerSummaryDto.cs
================================================
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using AutoMapper;
namespace AcmStatisticsBackend.Crawlers.Dto
{
[AutoMap(typeof(QueryCrawlerSummary))]
public class QueryCrawlerSummaryDto
{
///
/// The name of the crawler. Frontend can get its title by this field.
///
[Required]
public string CrawlerName { get; set; }
///
/// Submission count.
///
[Range(0, int.MaxValue)]
public int Submission { get; set; }
///
/// Solved count.
///
[Range(0, int.MaxValue)]
public int Solved { get; set; }
///
/// Usernames used in this crawler
///
public ICollection Usernames { get; set; }
public bool IsVirtualJudge { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/Dto/QuerySummaryDto.cs
================================================
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Abp.AutoMapper;
namespace AcmStatisticsBackend.Crawlers.Dto
{
[AutoMap(typeof(QuerySummary))]
public class QuerySummaryDto
{
[Range(1, long.MaxValue)]
public long QueryHistoryId { get; set; }
///
/// When the summary is generated
///
public DateTime GenerateTime { get; set; }
///
/// Main username, can be null or empty
///
public string MainUsername { get; set; }
///
/// Query summaries of each crawler.
///
[Required]
public ICollection QueryCrawlerSummaries { get; set; }
///
/// Warnings in summary generation.
///
[Required]
public ICollection SummaryWarnings { get; set; }
///
/// Total submission count
///
[Range(0, int.MaxValue)]
public int Submission { get; set; }
///
/// Total solved count, redundant problems (including problems in virtual_judge) are removed.
///
[Range(0, int.MaxValue)]
public int Solved { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/Dto/QueryWorkerHistoryDto.cs
================================================
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using Abp.AutoMapper;
using Abp.Runtime.Validation;
namespace AcmStatisticsBackend.Crawlers.Dto
{
[AutoMap(typeof(QueryWorkerHistory))]
public class QueryWorkerHistoryDto : ICustomValidate
{
///
/// The name of the crawler. Frontend can get its title by this field.
///
[Required]
public string CrawlerName { get; set; }
///
/// The username used to query this crawler.
///
[Required]
public string Username { get; set; }
///
/// Error message of the crawler. If it's not null, current query is failed, and
/// and are all 0.
///
[MaybeNull]
public string ErrorMessage { get; set; }
///
/// Submission count.
///
[Range(0, int.MaxValue)]
public int Submission { get; set; }
///
/// Solved count.
///
[Range(0, int.MaxValue)]
public int Solved { get; set; }
///
/// The list of problem ids that user solved.
///
/// Can be null if crawler does not support it.
///
[MaybeNull]
public string[] SolvedList { get; set; }
///
/// Whether current crawler is virtual judge.
///
public bool IsVirtualJudge { get; set; }
///
/// If is false, this field is null.
/// Otherwise, this field contains submissions count in each crawler.
///
[MaybeNull]
public Dictionary SubmissionsByCrawlerName { get; set; }
public void AddValidationErrors(CustomValidationContext context)
{
if (!string.IsNullOrEmpty(ErrorMessage))
{
if (SolvedList != null || SubmissionsByCrawlerName != null)
{
context.Results.Add(
new ValidationResult(
"These fields must be null when error message exists",
new[] { nameof(SolvedList), nameof(SubmissionsByCrawlerName) }));
}
return;
}
if (IsVirtualJudge)
{
if (SolvedList == null || SubmissionsByCrawlerName == null)
{
context.Results.Add(
new ValidationResult(
"These fields should not be null when crawler is virtual judge",
new[] { nameof(SolvedList), nameof(SubmissionsByCrawlerName) }));
}
}
else
{
if (SubmissionsByCrawlerName != null)
{
context.Results.Add(new ValidationResult(
"This field should bu null when crawler is not virtual judge",
new[] { nameof(SubmissionsByCrawlerName) }));
}
}
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/Dto/SaveOrReplaceQueryHistoryInput.cs
================================================
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Abp.AutoMapper;
namespace AcmStatisticsBackend.Crawlers.Dto
{
[AutoMapTo(typeof(QueryHistory))]
public class SaveOrReplaceQueryHistoryInput
{
///
/// Main username of query history, can be null or empty
///
public string MainUsername { get; set; }
///
/// Query history of each crawler.
///
public ICollection QueryWorkerHistories { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/Dto/SaveOrReplaceQueryHistoryOutput.cs
================================================
using System.ComponentModel.DataAnnotations;
namespace AcmStatisticsBackend.Crawlers.Dto
{
public class SaveOrReplaceQueryHistoryOutput
{
[Range(1, long.MaxValue)]
public long QueryHistoryId { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/Dto/UsernameInCrawlerDto.cs
================================================
using System.ComponentModel.DataAnnotations;
using AutoMapper;
namespace AcmStatisticsBackend.Crawlers.Dto
{
[AutoMap(typeof(UsernameInCrawler))]
public class UsernameInCrawlerDto
{
///
/// Which crawler (virtual judge) the username is from.
///
/// If it is null or empty string, the username is from
/// its own crawler.
///
public string FromCrawlerName { get; set; }
[Required]
public string Username { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/IDefaultQueryAppService.cs
================================================
using System.Threading.Tasks;
using Abp.Application.Services;
using AcmStatisticsBackend.Crawlers.Dto;
namespace AcmStatisticsBackend.Crawlers
{
///
/// Manage user's default usernames which will be automatically entered in
/// statistics page.
///
public interface IDefaultQueryAppService : IApplicationService
{
///
/// Get user's default usernames which will be automatically entered in
/// statistics page.
///
Task GetDefaultQueries();
///
/// Set user's default usernames which will be automatically entered in
/// statistics page.
///
Task SetDefaultQueries(DefaultQueryDto dto);
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/IQueryHistoryAppService.cs
================================================
using System.Threading.Tasks;
using Abp.Application.Services;
using Abp.Application.Services.Dto;
using AcmStatisticsBackend.Crawlers.Dto;
namespace AcmStatisticsBackend.Crawlers
{
///
/// Manage users' crawler query history
///
public interface IQueryHistoryAppService : IApplicationService
{
///
/// Save a crawler query history, does not validate data.
///
/// If there is another record in the same day, the old one is replaced.
///
/// The new query history id
Task SaveOrReplaceQueryHistory(SaveOrReplaceQueryHistoryInput input);
///
/// Delete a query history
///
Task DeleteQueryHistory(DeleteQueryHistoryInput input);
///
/// Get a list of current user's query history, sorted from newest to oldest.
///
Task> GetQueryHistories(PagedResultRequestDto input);
///
/// Get all that belong to certain .
///
Task> GetQueryWorkerHistories(GetAcWorkerHistoryInput input);
///
/// Get query summary of certain query history
///
/// input the id of query history
Task GetQuerySummary(GetQuerySummaryInput input);
///
/// Get a list of current user's query history, sorted from newest to oldest.
/// The submission and solved number are also included.
///
Task>
GetQueryHistoriesAndSummaries(PagedResultRequestDto input);
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Crawlers/QueryHistoryAppService.cs
================================================
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.Timing;
using Abp.Timing.Timezone;
using Abp.UI;
using AcmStatisticsBackend.Authorization;
using AcmStatisticsBackend.Crawlers.Dto;
using AcmStatisticsBackend.ServiceClients;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace AcmStatisticsBackend.Crawlers
{
///
[AbpAuthorize(PermissionNames.AcHistory_Histories)]
public class QueryHistoryAppService : AcmStatisticsBackendAppServiceBase, IQueryHistoryAppService
{
private readonly IRepository _acHistoryRepository;
private readonly IRepository _acWorkerHistoryRepository;
private readonly IRepository _querySummaryRepository;
private readonly IRepository _queryCrawlerSummaryRepository;
private readonly IClockProvider _clockProvider;
private readonly ITimeZoneConverter _timeZoneConverter;
private readonly ICrawlerApiBackendClient _crawlerApiBackendClient;
private readonly SummaryGenerator _summaryGenerator;
public QueryHistoryAppService(
IRepository acHistoryRepository,
IRepository acWorkerHistoryRepository,
IClockProvider clockProvider,
ITimeZoneConverter timeZoneConverter,
ICrawlerApiBackendClient crawlerApiBackendClient,
IRepository querySummaryRepository,
IRepository queryCrawlerSummaryRepository,
SummaryGenerator summaryGenerator)
{
_acHistoryRepository = acHistoryRepository;
_acWorkerHistoryRepository = acWorkerHistoryRepository;
_clockProvider = clockProvider;
_timeZoneConverter = timeZoneConverter;
_crawlerApiBackendClient = crawlerApiBackendClient;
_querySummaryRepository = querySummaryRepository;
_queryCrawlerSummaryRepository = queryCrawlerSummaryRepository;
_summaryGenerator = summaryGenerator;
}
///
public async Task SaveOrReplaceQueryHistory(
SaveOrReplaceQueryHistoryInput input)
{
// 添加新记录
var acHistory = ObjectMapper.Map(input);
// AutoMapper will change empty array to null. The code below is used to restore them
foreach (var (entity, dto) in acHistory.QueryWorkerHistories.Zip(input.QueryWorkerHistories))
{
if (dto.SolvedList == null)
{
entity.SolvedList = null;
}
if (dto.SubmissionsByCrawlerName == null)
{
entity.SubmissionsByCrawlerName = null;
}
}
Debug.Assert(AbpSession.UserId != null, "AbpSession.UserId != null");
acHistory.UserId = AbpSession.UserId.Value;
acHistory.CreationTime = _clockProvider.Now;
acHistory.IsReliableSource = false;
var crawlerMeta = await _crawlerApiBackendClient.GetCrawlerMeta();
var querySummary = _summaryGenerator.Generate(
crawlerMeta,
acHistory.QueryWorkerHistories.AsReadOnly());
await RemoveLatestHistoryTheSameDayOf(acHistory.CreationTime);
var historyId = await _acHistoryRepository.InsertAndGetIdAsync(acHistory);
querySummary.QueryHistoryId = historyId;
await _querySummaryRepository.InsertAsync(querySummary);
return new SaveOrReplaceQueryHistoryOutput
{
QueryHistoryId = historyId,
};
}
private async Task RemoveLatestHistoryTheSameDayOf(DateTime day)
{
var latestItem = await _acHistoryRepository.GetAll()
.Where(e => e.UserId == AbpSession.UserId.Value)
.OrderByDescending(e => e.CreationTime)
.FirstOrDefaultAsync();
if (latestItem != null)
{
Debug.Assert(AbpSession.UserId != null, "AbpSession.UserId != null");
var currentLocalTime = _timeZoneConverter.Convert(
day, AbpSession.TenantId, AbpSession.UserId.Value);
var latestItemCreationTimeLocal = _timeZoneConverter.Convert(
latestItem.CreationTime, AbpSession.TenantId, AbpSession.UserId.Value);
Debug.Assert(currentLocalTime != null, nameof(currentLocalTime) + " != null");
Debug.Assert(latestItemCreationTimeLocal != null, nameof(latestItemCreationTimeLocal) + " != null");
if (latestItemCreationTimeLocal.Value.Date == currentLocalTime.Value.Date)
{
await DoDeleteHistory(latestItem);
}
}
}
///
[HttpPost]
public async Task DeleteQueryHistory(DeleteQueryHistoryInput input)
{
if (input.Id.HasValue)
{
var entity = await GetAuthorizedEntity(input.Id.Value);
await DoDeleteHistory(entity);
}
if (input.Ids != null)
{
foreach (var id in input.Ids)
{
var entity = await GetAuthorizedEntity(id);
await DoDeleteHistory(entity);
}
}
}
///
public async Task> GetQueryHistories(PagedResultRequestDto input)
{
var list = await QueryHistoriesOfCurrentUser()
.OrderByDescending(e => e.CreationTime)
.PageBy(input)
.ToListAsync();
var count = await QueryHistoriesOfCurrentUser().CountAsync();
var resultList = ObjectMapper.Map>(list);
return new PagedResultDto(count, resultList);
}
private IQueryable QueryHistoriesOfCurrentUser()
{
return _acHistoryRepository.GetAll()
.Where(e => e.UserId == AbpSession.UserId.Value);
}
///
public async Task> GetQueryWorkerHistories(GetAcWorkerHistoryInput input)
{
var queryHistory = await GetAuthorizedEntity(input.QueryHistoryId);
var entityList = await _acWorkerHistoryRepository.GetAll()
.Where(e => e.QueryHistoryId == queryHistory.Id)
.ToListAsync();
var list = ObjectMapper.Map>(entityList);
// AutoMapper will change empty array to null. The code below is used to restore them
foreach (var (dto, entity) in list.Zip(entityList))
{
if (entity.SolvedList == null)
{
dto.SolvedList = null;
}
if (entity.SubmissionsByCrawlerName == null)
{
dto.SubmissionsByCrawlerName = null;
}
}
return new ListResultDto(list);
}
///
public async Task GetQuerySummary(GetQuerySummaryInput input)
{
var history = await GetAuthorizedEntity(input.QueryHistoryId);
var summary = await _querySummaryRepository.FirstOrDefaultAsync(
e => e.QueryHistoryId == history.Id);
if (summary == null)
{
throw new UserFriendlyException("This query history does not have summary");
}
var queryCrawlerSummary = await _queryCrawlerSummaryRepository.GetAllIncluding(
e => e.Usernames)
.Where(e => e.QuerySummaryId == summary.Id)
.ToListAsync();
var querySummaryDto = ObjectMapper.Map(summary);
querySummaryDto.QueryCrawlerSummaries =
ObjectMapper.Map>(queryCrawlerSummary);
querySummaryDto.MainUsername = history.MainUsername;
return querySummaryDto;
}
///
public async Task> GetQueryHistoriesAndSummaries(
PagedResultRequestDto input)
{
var list = await
(from h in QueryHistoriesOfCurrentUser()
.OrderByDescending(e => e.CreationTime)
.PageBy(input)
join s in _querySummaryRepository.GetAll()
on h.Id equals s.Id into grouping
from s in grouping.DefaultIfEmpty()
select new GetQueryHistoryAndSummaryOutput
{
HistoryId = h.Id,
SummaryId = s.Id,
CreationTime = h.CreationTime,
Solved = s.Solved == 0 && s.Submission == 0 ? null : s.Solved,
Submission = s.Solved == 0 && s.Submission == 0 ? null : s.Submission,
}).ToListAsync();
var count = await QueryHistoriesOfCurrentUser().CountAsync();
return new PagedResultDto(count, list);
}
///
/// 根据ID获取对象,并检查权限。
///
/// AcHistory的ID
/// AcHistory
/// 如果该对象不是由此用户创建,抛出异常
private async Task GetAuthorizedEntity(long id)
{
var acHistory = await _acHistoryRepository.GetAsync(id);
if (acHistory.UserId != AbpSession.UserId)
{
throw new AbpAuthorizationException("You do not have permissions to visit the entity.");
}
return acHistory;
}
///
/// 移除 AcHistory 和与其关联的 AcWorkerHistory,不检查用户是否有权限访问这个Entity
///
private async Task DoDeleteHistory(QueryHistory entity)
{
await _acHistoryRepository.DeleteAsync(entity);
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Net/MimeTypes/MimeTypeNames.cs
================================================
using System;
namespace AcmStatisticsBackend.Net.MimeTypes
{
/* Copied from:
* http://stackoverflow.com/questions/10362140/asp-mvc-are-there-any-constants-for-the-default-content-types */
///
/// Common mime types.
///
public static class MimeTypeNames
{
/// Used to denote the encoding necessary for files containing JavaScript source code. The alternative MIME type for this file type is text/javascript.
public const string ApplicationXJavascript = "application/x-javascript";
/// 24bit Linear PCM audio at 8-48kHz, 1-N channels; Defined in RFC 3190.
public const string AudioL24 = "audio/L24";
/// Adobe Flash files for example with the extension .swf.
public const string ApplicationXShockwaveFlash = "application/x-shockwave-flash";
/// Arbitrary binary data.[5] Generally speaking this type identifies files that are not associated with a specific application. Contrary to past assumptions by software packages such as Apache this is not a type that should be applied to unknown files. In such a case, a server or application should not indicate a content type, as it may be incorrect, but rather, should omit the type in order to allow the recipient to guess the type.[6].
public const string ApplicationOctetStream = "application/octet-stream";
/// Atom feeds.
public const string ApplicationAtomXml = "application/atom+xml";
/// Cascading Style Sheets; Defined in RFC 2318.
public const string TextCss = "text/css";
/// commands; subtype resident in Gecko browsers like Firefox 3.5.
public const string TextCmd = "text/cmd";
/// Comma-separated values; Defined in RFC 4180.
public const string TextCsv = "text/csv";
/// deb (file format), a software package format used by the Debian project.
public const string ApplicationXDeb = "application/x-deb";
/// Defined in RFC 1847.
public const string MultipartEncrypted = "multipart/encrypted";
/// Defined in RFC 1847.
public const string MultipartSigned = "multipart/signed";
/// Defined in RFC 2616.
public const string MessageHttp = "message/http";
/// Defined in RFC 4735.
public const string ModelExample = "model/example";
/// device-independent document in DVI format.
public const string ApplicationXDvi = "application/x-dvi";
/// DTD files; Defined by RFC 3023.
public const string ApplicationXmlDtd = "application/xml-dtd";
/// ECMAScript/JavaScript; Defined in RFC 4329 (equivalent to application/ecmascript but with looser processing rules) It is not accepted in IE 8 or earlier - text/javascript is accepted but it is defined as obsolete in RFC 4329. The "type" attribute of the. <script> tag in HTML5 is optional and in practice omitting the media type of JavaScript programs is the most interoperable solution since all browsers have always assumed the correct default even before HTML5.
public const string ApplicationJavascript = "application/javascript";
/// ECMAScript/JavaScript; Defined in RFC 4329 (equivalent to application/javascript but with stricter processing rules).
public const string ApplicationEcmascript = "application/ecmascript";
/// EDI EDIFACT data; Defined in RFC 1767.
public const string ApplicationEdifact = "application/EDIFACT";
/// EDI X12 data; Defined in RFC 1767.
public const string ApplicationEdiX12 = "application/EDI-X12";
/// Email; Defined in RFC 2045 and RFC 2046.
public const string MessagePartial = "message/partial";
/// Email; EML files, MIME files, MHT files, MHTML files; Defined in RFC 2045 and RFC 2046.
public const string MessageRfc822 = "message/rfc822";
/// Extensible Markup Language; Defined in RFC 3023.
public const string TextXml = "text/xml";
/// Flash video (FLV files).
public const string VideoXFlv = "video/x-flv";
/// GIF image; Defined in RFC 2045 and RFC 2046.
public const string ImageGif = "image/gif";
/// GoogleWebToolkit data.
public const string TextXGwtRpc = "text/x-gwt-rpc";
/// Gzip.
public const string ApplicationXGzip = "application/x-gzip";
/// HTML; Defined in RFC 2854.
public const string TextHtml = "text/html";
/// ICO image; Registered[9].
public const string ImageVndMicrosoftIcon = "image/vnd.microsoft.icon";
/// IGS files, IGES files; Defined in RFC 2077.
public const string ModelIges = "model/iges";
/// IMDN Instant Message Disposition Notification; Defined in RFC 5438.
public const string MessageImdnXml = "message/imdn+xml";
/// JavaScript Object Notation JSON; Defined in RFC 4627.
public const string ApplicationJson = "application/json";
/// JavaScript Object Notation (JSON) Patch; Defined in RFC 6902.
public const string ApplicationJsonPatch = "application/json-patch+json";
/// JavaScript - Defined in and obsoleted by RFC 4329 in order to discourage its usage in favor of application/javascript. However,text/javascript is allowed in HTML 4 and 5 and, unlike application/javascript, has cross-browser support. The "type" attribute of the. <script> tag in HTML5 is optional and there is no need to use it at all since all browsers have always assumed the correct default (even in HTML 4 where it was required by the specification).
[Obsolete]
public const string TextJavascript = "text/javascript";
/// JPEG JFIF image; Associated with Internet Explorer; Listed in ms775147(v=vs.85) - Progressive JPEG, initiated before global browser support for progressive JPEGs (Microsoft and Firefox).
public const string ImagePjpeg = "image/pjpeg";
/// JPEG JFIF image; Defined in RFC 2045 and RFC 2046.
public const string ImageJpeg = "image/jpeg";
/// jQuery template data.
public const string TextXJqueryTmpl = "text/x-jquery-tmpl";
/// KML files (e.g. for Google Earth).
public const string ApplicationVndGoogleEarthKmlXml = "application/vnd.google-earth.kml+xml";
/// LaTeX files.
public const string ApplicationXLatex = "application/x-latex";
/// Matroska open media format.
public const string VideoXMatroska = "video/x-matroska";
/// Microsoft Excel 2007 files.
public const string ApplicationVndOpenxmlformatsOfficedocumentSpreadsheetmlSheet = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
/// Microsoft Excel files.
public const string ApplicationVndMsExcel = "application/vnd.ms-excel";
/// Microsoft Powerpoint 2007 files.
public const string ApplicationVndOpenxmlformatsOfficedocumentPresentationmlPresentation = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
/// Microsoft Powerpoint files.
public const string ApplicationVndMsPowerpoint = "application/vnd.ms-powerpoint";
/// Microsoft Word 2007 files.
public const string ApplicationVndOpenxmlformatsOfficedocumentWordprocessingmlDocument = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
/// Microsoft Word files[15].
public const string ApplicationMsword = "application/msword";
/// MIME Email; Defined in RFC 2045 and RFC 2046.
public const string MultipartAlternative = "multipart/alternative";
/// MIME Email; Defined in RFC 2045 and RFC 2046.
public const string MultipartMixed = "multipart/mixed";
/// MIME Email; Defined in RFC 2387 and used by MHTML (HTML mail).
public const string MultipartRelated = "multipart/related";
/// MIME Webform; Defined in RFC 2388.
public const string MultipartFormData = "multipart/form-data";
/// Mozilla XUL files.
public const string ApplicationVndMozillaXulXml = "application/vnd.mozilla.xul+xml";
/// MP3 or other MPEG audio; Defined in RFC 3003.
public const string AudioMpeg = "audio/mpeg";
/// MP4 audio.
public const string AudioMp4 = "audio/mp4";
/// MP4 video; Defined in RFC 4337.
public const string VideoMp4 = "video/mp4";
/// MPEG-1 video with multiplexed audio; Defined in RFC 2045 and RFC 2046.
public const string VideoMpeg = "video/mpeg";
/// MSH files, MESH files; Defined in RFC 2077, SILO files.
public const string ModelMesh = "model/mesh";
/// mulaw audio at 8 kHz, 1 channel; Defined in RFC 2046.
public const string AudioBasic = "audio/basic";
/// Ogg Theora or other video (with audio); Defined in RFC 5334.
public const string VideoOgg = "video/ogg";
/// Ogg Vorbis, Speex, Flac and other audio; Defined in RFC 5334.
public const string AudioOgg = "audio/ogg";
/// Ogg, a multimedia bitstream container format; Defined in RFC 5334.
public const string ApplicationOgg = "application/ogg";
/// OP.
public const string ApplicationXopXml = "application/xop+xml";
/// OpenDocument Graphics; Registered[14].
public const string ApplicationVndOasisOpendocumentGraphics = "application/vnd.oasis.opendocument.graphics";
/// OpenDocument Presentation; Registered[13].
public const string ApplicationVndOasisOpendocumentPresentation = "application/vnd.oasis.opendocument.presentation";
/// OpenDocument Spreadsheet; Registered[12].
public const string ApplicationVndOasisOpendocumentSpreadsheet = "application/vnd.oasis.opendocument.spreadsheet";
/// OpenDocument Text; Registered[11].
public const string ApplicationVndOasisOpendocumentText = "application/vnd.oasis.opendocument.text";
/// p12 files.
public const string ApplicationXPkcs12 = "application/x-pkcs12";
/// p7b and spc files.
public const string ApplicationXPkcs7Certificates = "application/x-pkcs7-certificates";
/// p7c files.
public const string ApplicationXPkcs7Mime = "application/x-pkcs7-mime";
/// p7r files.
public const string ApplicationXPkcs7Certreqresp = "application/x-pkcs7-certreqresp";
/// p7s files.
public const string ApplicationXPkcs7Signature = "application/x-pkcs7-signature";
/// Portable Document Format, PDF has been in use for document exchange on the Internet since 1993; Defined in RFC 3778.
public const string ApplicationPdf = "application/pdf";
/// Portable Network Graphics; Registered,[8] Defined in RFC 2083.
public const string ImagePng = "image/png";
/// PostScript; Defined in RFC 2046.
public const string ApplicationPostscript = "application/postscript";
/// QuickTime video; Registered[10].
public const string VideoQuicktime = "video/quicktime";
/// RAR archive files.
public const string ApplicationXRarCompressed = "application/x-rar-compressed";
/// RealAudio; Documented in RealPlayer Customer Support Answer 2559.
public const string AudioVndRnRealaudio = "audio/vnd.rn-realaudio";
/// Resource Description Framework; Defined by RFC 3870.
public const string ApplicationRdfXml = "application/rdf+xml";
/// RSS feeds.
public const string ApplicationRssXml = "application/rss+xml";
/// SOAP; Defined by RFC 3902.
public const string ApplicationSoapXml = "application/soap+xml";
/// StuffIt archive files.
public const string ApplicationXStuffit = "application/x-stuffit";
/// SVG vector image; Defined in SVG Tiny 1.2 Specification Appendix M.
public const string ImageSvgXml = "image/svg+xml";
/// Tag Image File Format (only for Baseline TIFF); Defined in RFC 3302.
public const string ImageTiff = "image/tiff";
/// Tarball files.
public const string ApplicationXTar = "application/x-tar";
/// Textual data; Defined in RFC 2046 and RFC 3676.
public const string TextPlain = "text/plain";
/// TrueType Font No registered MIME type, but this is the most commonly used.
public const string ApplicationXFontTtf = "application/x-font-ttf";
/// vCard (contact information); Defined in RFC 6350.
public const string TextVcard = "text/vcard";
/// Vorbis encoded audio; Defined in RFC 5215.
public const string AudioVorbis = "audio/vorbis";
/// WAV audio; Defined in RFC 2361.
public const string AudioVndWave = "audio/vnd.wave";
/// Web Open Font Format; (candidate recommendation; use application/x-font-woff until standard is official).
public const string ApplicationFontWoff = "application/font-woff";
/// WebM Matroska-based open media format.
public const string VideoWebm = "video/webm";
/// WebM open media format.
public const string AudioWebm = "audio/webm";
/// Windows Media Audio Redirector; Documented in Microsoft help page.
public const string AudioXMsWax = "audio/x-ms-wax";
/// Windows Media Audio; Documented in Microsoft KB 288102.
public const string AudioXMsWma = "audio/x-ms-wma";
/// Windows Media Video; Documented in Microsoft KB 288102.
public const string VideoXMsWmv = "video/x-ms-wmv";
/// WRL files, VRML files; Defined in RFC 2077.
public const string ModelVrml = "model/vrml";
/// X3D ISO standard for representing 3D computer graphics, X3D XML files.
public const string ModelX3DXml = "model/x3d+xml";
/// X3D ISO standard for representing 3D computer graphics, X3DB binary files.
public const string ModelX3DBinary = "model/x3d+binary";
/// X3D ISO standard for representing 3D computer graphics, X3DV VRML files.
public const string ModelX3DVrml = "model/x3d+vrml";
/// XHTML; Defined by RFC 3236.
public const string ApplicationXhtmlXml = "application/xhtml+xml";
/// ZIP archive files; Registered[7].
public const string ApplicationZip = "application/zip";
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Properties/AssemblyInfo.cs
================================================
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AcmStatisticsBackend.Application")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3870c648-4aea-4b85-ba3f-f2f63b96136a")]
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Sessions/Dto/ApplicationInfoDto.cs
================================================
using System;
using System.Collections.Generic;
namespace AcmStatisticsBackend.Sessions.Dto
{
public class ApplicationInfoDto
{
public string Version { get; set; }
public DateTime ReleaseDate { get; set; }
public Dictionary Features { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Sessions/Dto/GetCurrentLoginInformationsOutput.cs
================================================
namespace AcmStatisticsBackend.Sessions.Dto
{
public class GetCurrentLoginInformationsOutput
{
public ApplicationInfoDto Application { get; set; }
public UserLoginInfoDto User { get; set; }
public TenantLoginInfoDto Tenant { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Sessions/Dto/TenantLoginInfoDto.cs
================================================
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using AcmStatisticsBackend.MultiTenancy;
namespace AcmStatisticsBackend.Sessions.Dto
{
[AutoMapFrom(typeof(Tenant))]
public class TenantLoginInfoDto : EntityDto
{
public string TenancyName { get; set; }
public string Name { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Sessions/Dto/UserLoginInfoDto.cs
================================================
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using AcmStatisticsBackend.Authorization.Users;
namespace AcmStatisticsBackend.Sessions.Dto
{
[AutoMapFrom(typeof(User))]
public class UserLoginInfoDto : EntityDto
{
public string Name { get; set; }
public string Surname { get; set; }
public string UserName { get; set; }
public string EmailAddress { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Sessions/ISessionAppService.cs
================================================
using System.Threading.Tasks;
using Abp.Application.Services;
using AcmStatisticsBackend.Sessions.Dto;
namespace AcmStatisticsBackend.Sessions
{
public interface ISessionAppService : IApplicationService
{
Task GetCurrentLoginInformations();
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Sessions/SessionAppService.cs
================================================
using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Auditing;
using AcmStatisticsBackend.Sessions.Dto;
namespace AcmStatisticsBackend.Sessions
{
public class SessionAppService : AcmStatisticsBackendAppServiceBase, ISessionAppService
{
[DisableAuditing]
public async Task GetCurrentLoginInformations()
{
var output = new GetCurrentLoginInformationsOutput
{
Application = new ApplicationInfoDto
{
Version = AppVersionHelper.Version,
ReleaseDate = AppVersionHelper.ReleaseDate,
Features = new Dictionary(),
},
};
if (AbpSession.TenantId.HasValue)
{
output.Tenant = ObjectMapper.Map(await GetCurrentTenantAsync());
}
if (AbpSession.UserId.HasValue)
{
output.User = ObjectMapper.Map(await GetCurrentUserAsync());
}
return output;
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Settings/Dto/UpdateAutoSaveHistoryInput.cs
================================================
namespace AcmStatisticsBackend.Settings.Dto
{
public class UpdateAutoSaveHistoryInput
{
public bool AutoSaveHistory { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Settings/Dto/UserSettingsConfigDto.cs
================================================
using System.Collections.Generic;
namespace AcmStatisticsBackend.Settings.Dto
{
public class UserSettingsConfigDto
{
public IDictionary Values { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Settings/Dto/UserTimeZoneDto.cs
================================================
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Abp.Runtime.Validation;
using TimeZoneConverter;
namespace AcmStatisticsBackend.Settings.Dto
{
public class UserTimeZoneDto : ICustomValidate
{
///
/// Time zone of the user. It is a windows time zone name.
/// See
/// for all possible values.
///
[Required]
public string TimeZone { get; set; }
public void AddValidationErrors(CustomValidationContext context)
{
if (!TZConvert.KnownWindowsTimeZoneIds.Contains(TimeZone))
{
context.Results.Add(new ValidationResult("TimeZone must be valid!"));
}
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Settings/IUserConfigAppService.cs
================================================
using System.Threading.Tasks;
using AcmStatisticsBackend.Settings.Dto;
namespace AcmStatisticsBackend.Settings
{
///
/// Manage user config
///
public interface IUserConfigAppService
{
///
/// Get all user settings available to frontend
///
Task GetUserSettings();
///
/// Update config about whether the history should be auto-saved
///
Task UpdateAutoSaveHistory(UpdateAutoSaveHistoryInput input);
///
/// Set time zone of current user.
///
Task SetUserTimeZone(UserTimeZoneDto dto);
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Application/Settings/UserConfigAppService.cs
================================================
using System.Collections.Generic;
using System.Threading.Tasks;
using Abp.Authorization;
using Abp.Configuration;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Runtime.Session;
using Abp.Timing;
using Abp.UI;
using AcmStatisticsBackend.Authorization;
using AcmStatisticsBackend.Configuration;
using AcmStatisticsBackend.Settings.Dto;
namespace AcmStatisticsBackend.Settings
{
///
[AbpAuthorize]
public class UserConfigAppService : AcmStatisticsBackendAppServiceBase, IUserConfigAppService
{
private readonly ISettingDefinitionManager _settingDefinitionManager;
private readonly IIocResolver _iocResolver;
private readonly IClockProvider _clockProvider;
private readonly IRepository _userSettingAttributeRepository;
public UserConfigAppService(ISettingDefinitionManager settingDefinitionManager, IIocResolver iocResolver, IClockProvider clockProvider, IRepository userSettingAttributeRepository)
{
_settingDefinitionManager = settingDefinitionManager;
_iocResolver = iocResolver;
_clockProvider = clockProvider;
_userSettingAttributeRepository = userSettingAttributeRepository;
}
///
public async Task GetUserSettings()
{
var config = new UserSettingsConfigDto
{
Values = new Dictionary(),
};
var settings = await SettingManager.GetAllSettingValuesAsync(SettingScopes.All);
using var scope = _iocResolver.CreateScope();
foreach (var settingValue in settings)
{
if (!await _settingDefinitionManager.GetSettingDefinition(settingValue.Name)
.ClientVisibilityProvider
.CheckVisible(scope))
{
continue;
}
config.Values.Add(settingValue.Name, settingValue.Value);
}
return config;
}
///
[AbpAuthorize(PermissionNames.Settings_Update)]
public async Task UpdateAutoSaveHistory(UpdateAutoSaveHistoryInput input)
{
await SettingManager.ChangeSettingForUserAsync(
AbpSession.ToUserIdentifier(),
AppSettingNames.AutoSaveHistory,
input.AutoSaveHistory ? "true" : "false");
}
///
[AbpAuthorize(PermissionNames.Settings_Update)]
public async Task SetUserTimeZone(UserTimeZoneDto dto)
{
var settings = await GetOrCreateUserSettingAttribute();
if (settings.LastTimeZoneChangedTime.HasValue
&& settings.LastTimeZoneChangedTime.Value.AddDays(1) > _clockProvider.Now)
{
throw new UserFriendlyException("Please wait 24 hours to set time zone again!");
}
await SettingManager.ChangeSettingForUserAsync(
AbpSession.ToUserIdentifier(),
TimingSettingNames.TimeZone,
dto.TimeZone);
settings.LastTimeZoneChangedTime = _clockProvider.Now;
}
private async Task GetOrCreateUserSettingAttribute()
{
return await _userSettingAttributeRepository.FirstOrDefaultAsync(
item => item.UserId == AbpSession.UserId.Value)
??
await _userSettingAttributeRepository.InsertAsync(
new UserSettingAttribute
{
UserId = AbpSession.GetUserId(),
});
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/AcmStatisticsBackend.Core.csproj
================================================
1.0.0.0net8.0AcmStatisticsBackend.CoreAcmStatisticsBackend.CorefalsefalsefalseAbpCompanyName-AcmStatisticsBackend-56C2EF2F-ABD6-4EFC-AAF2-2E81C34E8FB1AcmStatisticsBackend
================================================
FILE: backend/src/AcmStatisticsBackend.Core/AcmStatisticsBackendConsts.cs
================================================
namespace AcmStatisticsBackend
{
public class AcmStatisticsBackendConsts
{
public const string LocalizationSourceName = "AcmStatisticsBackend";
public const string ConnectionStringName = "Default";
public const bool MultiTenancyEnabled = false;
///
/// 用户没有输入邮箱时,使用这个后缀作为邮箱名
///
public const string NoEmailSuffix = "@noemail.fake";
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/AcmStatisticsBackendCoreModule.cs
================================================
using Abp.Dependency;
using Abp.Modules;
using Abp.Reflection.Extensions;
using Abp.Timing;
using Abp.Zero;
using Abp.Zero.Configuration;
using AcmStatisticsBackend.Authorization.Roles;
using AcmStatisticsBackend.Authorization.Users;
using AcmStatisticsBackend.Configuration;
using AcmStatisticsBackend.Localization;
using AcmStatisticsBackend.MultiTenancy;
using AcmStatisticsBackend.Timing;
using Castle.MicroKernel.Registration;
namespace AcmStatisticsBackend
{
[DependsOn(typeof(AbpZeroCoreModule))]
public class AcmStatisticsBackendCoreModule : AbpModule
{
public override void PreInitialize()
{
Clock.Provider = ClockProviders.Utc;
IocManager.IocContainer.Register(
Component.For()
.Instance(ClockProviders.Utc)
.LifestyleSingleton());
Configuration.Auditing.IsEnabledForAnonymousUsers = true;
// Declare entity types
Configuration.Modules.Zero().EntityTypes.Tenant = typeof(Tenant);
Configuration.Modules.Zero().EntityTypes.Role = typeof(Role);
Configuration.Modules.Zero().EntityTypes.User = typeof(User);
AcmStatisticsBackendLocalizationConfigurer.Configure(Configuration.Localization);
// Enable this line to create a multi-tenant application.
Configuration.MultiTenancy.IsEnabled = AcmStatisticsBackendConsts.MultiTenancyEnabled;
// Configure roles
AppRoleConfig.Configure(Configuration.Modules.Zero().RoleManagement);
Configuration.Settings.Providers.Add();
}
public override void Initialize()
{
IocManager.RegisterAssemblyByConvention(typeof(AcmStatisticsBackendCoreModule).GetAssembly());
}
public override void PostInitialize()
{
IocManager.Resolve().StartupTime = Clock.Now;
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/AcmStatisticsBackendExtensions.cs
================================================
using System;
using System.Collections;
using System.Collections.Generic;
namespace AcmStatisticsBackend
{
public static class AcmStatisticsBackendExtensions
{
#pragma warning disable SA1618
///
/// 用法:
///
/// Get().A().Object().WithIn(it => {
/// it.methodA();
/// it.methodB();
/// })
///
///
public static TR WithIn(this TT obj, Func func)
where TT : class
{
return func(obj);
}
#pragma warning restore SA1618
public static TR WithIn(this ref TT obj, Func func)
where TT : struct
{
return func(obj);
}
public static void WithIn(this T obj, Action action)
where T : class
{
action(obj);
}
public static void WithIn(this ref T obj, Action action)
where T : struct
{
action(obj);
}
// from https://stackoverflow.com/a/47815787
public static void Deconstruct(this T[] items, out T t0)
{
t0 = items.Length > 0 ? items[0] : default;
}
public static void Deconstruct(this T[] items, out T t0, out T t1)
{
t0 = items.Length > 0 ? items[0] : default;
t1 = items.Length > 1 ? items[1] : default;
}
// from https://stackoverflow.com/a/34362585
public static IReadOnlyCollection AsReadOnly(this ICollection source)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
return source as IReadOnlyCollection ?? new ReadOnlyCollectionAdapter(source);
}
private sealed class ReadOnlyCollectionAdapter : IReadOnlyCollection
{
private readonly ICollection _source;
public ReadOnlyCollectionAdapter(ICollection source) => this._source = source;
public int Count => _source.Count;
public IEnumerator GetEnumerator() => _source.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/AppVersionHelper.cs
================================================
using System;
using System.IO;
using Abp.Reflection.Extensions;
namespace AcmStatisticsBackend
{
///
/// Central point for application version.
///
public class AppVersionHelper
{
///
/// Gets current version of the application.
/// It's also shown in the web page.
///
public const string Version = "5.1.0.0";
///
/// Gets release (last build) date of the application.
/// It's shown in the web page.
///
public static DateTime ReleaseDate => LzyReleaseDate.Value;
private static readonly Lazy LzyReleaseDate = new Lazy(() => new FileInfo(typeof(AppVersionHelper).GetAssembly().Location).LastWriteTime);
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/AcmStatisticsBackendAuthorizationProvider.cs
================================================
using Abp.Authorization;
using Abp.Localization;
using Abp.MultiTenancy;
namespace AcmStatisticsBackend.Authorization
{
public class AcmStatisticsBackendAuthorizationProvider : AuthorizationProvider
{
public override void SetPermissions(IPermissionDefinitionContext context)
{
context.CreatePermission(PermissionNames.Pages_Users, L("Users"));
context.CreatePermission(PermissionNames.Pages_Roles, L("Roles"));
context.CreatePermission(PermissionNames.Pages_Tenants, L("Tenants"),
multiTenancySides: MultiTenancySides.Host);
context.CreatePermission(PermissionNames.Statistics_DefaultQuery, F("Default query username"));
context.CreatePermission(PermissionNames.AcHistory_Histories, F("Query history"));
context.CreatePermission(PermissionNames.Settings_Update, F("Change user's own settings"));
}
private static ILocalizableString L(string name)
{
return new LocalizableString(name, AcmStatisticsBackendConsts.LocalizationSourceName);
}
private static ILocalizableString F(string content)
{
return new FixedLocalizableString(content);
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/LoginManager.cs
================================================
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Zero.Configuration;
using AcmStatisticsBackend.Authorization.Roles;
using AcmStatisticsBackend.Authorization.Users;
using AcmStatisticsBackend.MultiTenancy;
using Microsoft.AspNetCore.Identity;
namespace AcmStatisticsBackend.Authorization
{
public class LogInManager : AbpLogInManager
{
public LogInManager(
UserManager userManager,
IMultiTenancyConfig multiTenancyConfig,
IRepository tenantRepository,
IUnitOfWorkManager unitOfWorkManager,
ISettingManager settingManager,
IRepository userLoginAttemptRepository,
IUserManagementConfig userManagementConfig,
IIocResolver iocResolver,
IPasswordHasher passwordHasher,
RoleManager roleManager,
UserClaimsPrincipalFactory claimsPrincipalFactory)
: base(
userManager,
multiTenancyConfig,
tenantRepository,
unitOfWorkManager,
settingManager,
userLoginAttemptRepository,
userManagementConfig,
iocResolver,
passwordHasher,
roleManager,
claimsPrincipalFactory)
{
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/PermissionChecker.cs
================================================
using Abp.Authorization;
using AcmStatisticsBackend.Authorization.Roles;
using AcmStatisticsBackend.Authorization.Users;
namespace AcmStatisticsBackend.Authorization
{
public class PermissionChecker : PermissionChecker
{
public PermissionChecker(UserManager userManager)
: base(userManager)
{
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/PermissionNames.cs
================================================
namespace AcmStatisticsBackend.Authorization
{
public static class PermissionNames
{
#pragma warning disable SA1310 // Field names should not contain underscore
public const string Pages_Tenants = "Pages.Tenants";
public const string Pages_Users = "Pages.Users";
public const string Pages_Roles = "Pages.Roles";
public const string Statistics_DefaultQuery = "Statistics.DefaultQuery";
public const string AcHistory_Histories = "AcHistory.Histories";
public const string Settings_Update = "Settings.Update";
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/Roles/AppRoleConfig.cs
================================================
using Abp.MultiTenancy;
using Abp.Zero.Configuration;
namespace AcmStatisticsBackend.Authorization.Roles
{
public static class AppRoleConfig
{
public static void Configure(IRoleManagementConfig roleManagementConfig)
{
// Static host roles
roleManagementConfig.StaticRoles.Add(
new StaticRoleDefinition(
StaticRoleNames.Host.Admin,
MultiTenancySides.Host));
// Static tenant roles
roleManagementConfig.StaticRoles.Add(
new StaticRoleDefinition(
StaticRoleNames.Tenants.Admin,
MultiTenancySides.Tenant));
roleManagementConfig.StaticRoles.Add(
new StaticRoleDefinition(
StaticRoleNames.Tenants.User,
MultiTenancySides.Tenant));
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/Roles/Role.cs
================================================
using System.ComponentModel.DataAnnotations;
using Abp.Authorization.Roles;
using AcmStatisticsBackend.Authorization.Users;
namespace AcmStatisticsBackend.Authorization.Roles
{
public class Role : AbpRole
{
public Role()
{
}
public Role(int? tenantId, string displayName)
: base(tenantId, displayName)
{
}
public Role(int? tenantId, string name, string displayName)
: base(tenantId, name, displayName)
{
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/Roles/RoleManager.cs
================================================
using System.Collections.Generic;
using Abp.Authorization;
using Abp.Authorization.Roles;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Organizations;
using Abp.Runtime.Caching;
using Abp.Zero.Configuration;
using AcmStatisticsBackend.Authorization.Users;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
namespace AcmStatisticsBackend.Authorization.Roles
{
public class RoleManager : AbpRoleManager
{
public RoleManager(
RoleStore store,
IEnumerable> roleValidators,
ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors,
ILogger> logger,
IPermissionManager permissionManager,
ICacheManager cacheManager,
IUnitOfWorkManager unitOfWorkManager,
IRoleManagementConfig roleManagementConfig,
IRepository organizationUnitRepository,
IRepository organizationUnitRoleRepository)
: base(
store,
roleValidators,
keyNormalizer,
errors, logger,
permissionManager,
cacheManager,
unitOfWorkManager,
roleManagementConfig,
organizationUnitRepository,
organizationUnitRoleRepository)
{
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/Roles/RoleStore.cs
================================================
using Abp.Authorization.Roles;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using AcmStatisticsBackend.Authorization.Users;
namespace AcmStatisticsBackend.Authorization.Roles
{
public class RoleStore : AbpRoleStore
{
public RoleStore(
IUnitOfWorkManager unitOfWorkManager,
IRepository roleRepository,
IRepository rolePermissionSettingRepository)
: base(
unitOfWorkManager,
roleRepository,
rolePermissionSettingRepository)
{
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/Roles/StaticRoleNames.cs
================================================
namespace AcmStatisticsBackend.Authorization.Roles
{
public static class StaticRoleNames
{
public static class Host
{
public const string Admin = "Admin";
}
public static class Tenants
{
public const string Admin = "Admin";
public const string User = "User";
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/Users/User.cs
================================================
using System;
using System.Collections.Generic;
using Abp.Authorization.Users;
using Abp.Extensions;
namespace AcmStatisticsBackend.Authorization.Users
{
public class User : AbpUser
{
public const string DefaultPassword = "123qwe";
public static string CreateRandomPassword()
{
return Guid.NewGuid().ToString("N").Truncate(16);
}
public static User CreateTenantAdminUser(int tenantId, string emailAddress)
{
var user = new User
{
TenantId = tenantId,
UserName = AdminUserName,
Name = AdminUserName,
Surname = AdminUserName,
EmailAddress = emailAddress,
Roles = new List(),
};
user.SetNormalizedNames();
return user;
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/Users/UserClaimsPrincipalFactory.cs
================================================
using Abp.Authorization;
using Abp.Domain.Uow;
using AcmStatisticsBackend.Authorization.Roles;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
namespace AcmStatisticsBackend.Authorization.Users
{
public class UserClaimsPrincipalFactory : AbpUserClaimsPrincipalFactory
{
public UserClaimsPrincipalFactory(
UserManager userManager,
RoleManager roleManager,
IOptions optionsAccessor,
IUnitOfWorkManager unitOfWorkManager)
: base(
userManager,
roleManager,
optionsAccessor,
unitOfWorkManager)
{
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/Users/UserDeletingEventHandler.cs
================================================
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Events.Bus.Entities;
using Abp.Events.Bus.Handlers;
using AcmStatisticsBackend.Crawlers;
namespace AcmStatisticsBackend.Authorization.Users
{
public class UserDeletingEventHandler : IAsyncEventHandler>, ITransientDependency
{
private readonly IRepository _defaultQueryRepository;
private readonly IRepository _acHistoryRepository;
public UserDeletingEventHandler(IRepository defaultQueryRepository,
IRepository acHistoryRepository)
{
_defaultQueryRepository = defaultQueryRepository;
_acHistoryRepository = acHistoryRepository;
}
public async Task HandleEventAsync(EntityDeletingEventData eventData)
{
await _defaultQueryRepository.HardDeleteAsync(
e => e.UserId == eventData.Entity.Id);
await _acHistoryRepository.DeleteAsync(
e => e.UserId == eventData.Entity.Id);
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/Users/UserManager.cs
================================================
using System;
using System.Collections.Generic;
using Abp.Authorization;
using Abp.Authorization.Roles;
using Abp.Authorization.Users;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Organizations;
using Abp.Runtime.Caching;
using AcmStatisticsBackend.Authorization.Roles;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace AcmStatisticsBackend.Authorization.Users
{
public class UserManager : AbpUserManager
{
public UserManager(AbpRoleManager roleManager, AbpUserStore userStore, IOptions optionsAccessor, IPasswordHasher passwordHasher, IEnumerable> userValidators, IEnumerable> passwordValidators, ILookupNormalizer keyNormalizer, IdentityErrorDescriber errors, IServiceProvider services, ILogger> logger, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ICacheManager cacheManager, IRepository organizationUnitRepository, IRepository userOrganizationUnitRepository, IOrganizationUnitSettings organizationUnitSettings, ISettingManager settingManager, IRepository userLoginRepository) : base(roleManager, userStore, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger, permissionManager, unitOfWorkManager, cacheManager, organizationUnitRepository, userOrganizationUnitRepository, organizationUnitSettings, settingManager, userLoginRepository)
{
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/Users/UserRegistrationManager.cs
================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Abp.Authorization.Users;
using Abp.Domain.Services;
using Abp.Domain.Uow;
using Abp.IdentityFramework;
using Abp.Runtime.Session;
using Abp.UI;
using AcmStatisticsBackend.Authorization.Roles;
using AcmStatisticsBackend.MultiTenancy;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
namespace AcmStatisticsBackend.Authorization.Users
{
public class UserRegistrationManager : DomainService
{
public IAbpSession AbpSession { get; set; }
private readonly TenantManager _tenantManager;
private readonly UserManager _userManager;
private readonly RoleManager _roleManager;
private readonly IPasswordHasher _passwordHasher;
public UserRegistrationManager(
TenantManager tenantManager,
UserManager userManager,
RoleManager roleManager,
IPasswordHasher passwordHasher)
{
_tenantManager = tenantManager;
_userManager = userManager;
_roleManager = roleManager;
_passwordHasher = passwordHasher;
AbpSession = NullAbpSession.Instance;
}
[UnitOfWork]
public virtual async Task RegisterAsync(string userName, string plainPassword)
{
CheckForTenant();
var tenant = await GetActiveTenantAsync();
var user = new User
{
TenantId = tenant.Id,
IsActive = true,
UserName = userName,
EmailAddress = userName + AcmStatisticsBackendConsts.NoEmailSuffix,
IsEmailConfirmed = false,
Roles = new List(),
Name = "",
Surname = "",
};
user.SetNormalizedNames();
foreach (var defaultRole in await _roleManager.Roles.Where(r => r.IsDefault).ToListAsync())
{
user.Roles.Add(new UserRole(tenant.Id, user.Id, defaultRole.Id));
}
await _userManager.InitializeOptionsAsync(tenant.Id);
CheckErrors(await _userManager.CreateAsync(user, plainPassword));
await CurrentUnitOfWork.SaveChangesAsync();
return user;
}
private void CheckForTenant()
{
if (!AbpSession.TenantId.HasValue)
{
throw new InvalidOperationException("Can not register host users!");
}
}
private async Task GetActiveTenantAsync()
{
if (!AbpSession.TenantId.HasValue)
{
return null;
}
return await GetActiveTenantAsync(AbpSession.TenantId.Value);
}
private async Task GetActiveTenantAsync(int tenantId)
{
var tenant = await _tenantManager.FindByIdAsync(tenantId);
if (tenant == null)
{
throw new UserFriendlyException(L("UnknownTenantId{0}", tenantId));
}
if (!tenant.IsActive)
{
throw new UserFriendlyException(L("TenantIdIsNotActive{0}", tenantId));
}
return tenant;
}
protected virtual void CheckErrors(IdentityResult identityResult)
{
identityResult.CheckErrors(LocalizationManager);
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Authorization/Users/UserStore.cs
================================================
using Abp.Authorization.Users;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Linq;
using Abp.Organizations;
using AcmStatisticsBackend.Authorization.Roles;
namespace AcmStatisticsBackend.Authorization.Users
{
public class UserStore : AbpUserStore
{
public UserStore(
IUnitOfWorkManager unitOfWorkManager,
IRepository userRepository,
IRepository roleRepository,
IRepository userRoleRepository,
IRepository userLoginRepository,
IRepository userClaimRepository,
IRepository userPermissionSettingRepository,
IRepository userOrganizationUnitRepository,
IRepository organizationUnitRoleRepository,
IRepository userTokenRepository)
: base(
unitOfWorkManager,
userRepository,
roleRepository,
userRoleRepository,
userLoginRepository,
userClaimRepository,
userPermissionSettingRepository,
userOrganizationUnitRepository,
organizationUnitRoleRepository,
userTokenRepository)
{
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Configuration/AppConfigurations.cs
================================================
using System.Collections.Concurrent;
using Abp.Extensions;
using Abp.Reflection.Extensions;
using Microsoft.Extensions.Configuration;
namespace AcmStatisticsBackend.Configuration
{
public static class AppConfigurations
{
private static readonly ConcurrentDictionary _configurationCache;
static AppConfigurations()
{
_configurationCache = new ConcurrentDictionary();
}
public static IConfigurationRoot Get(string path, string environmentName = null, bool addUserSecrets = false)
{
var cacheKey = path + "#" + environmentName + "#" + addUserSecrets;
return _configurationCache.GetOrAdd(
cacheKey,
_ => BuildConfiguration(path, environmentName, addUserSecrets));
}
private static IConfigurationRoot BuildConfiguration(string path, string environmentName = null, bool addUserSecrets = false)
{
var builder = new ConfigurationBuilder()
.SetBasePath(path)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
if (!environmentName.IsNullOrWhiteSpace())
{
builder = builder.AddJsonFile($"appsettings.{environmentName}.json", optional: true);
}
builder = builder.AddEnvironmentVariables();
if (addUserSecrets)
{
builder.AddUserSecrets(typeof(AppConfigurations).GetAssembly());
}
return builder.Build();
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Configuration/AppEnvironmentVariables.cs
================================================
using System;
namespace AcmStatisticsBackend.Configuration
{
public class AppEnvironmentVariables
{
public static string DefaultAdminPassword =>
Environment.GetEnvironmentVariable("BACKEND_ADMIN_DEFAULT_PASSWORD")
?? "123qwe";
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Configuration/AppSettingNames.cs
================================================
namespace AcmStatisticsBackend.Configuration
{
public static class AppSettingNames
{
public const string UiTheme = "App.UiTheme";
public const string AutoSaveHistory = "App.AutoSaveHistory";
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Configuration/AppSettingProvider.cs
================================================
using System.Collections.Generic;
using Abp.Configuration;
namespace AcmStatisticsBackend.Configuration
{
public class AppSettingProvider : SettingProvider
{
public override IEnumerable GetSettingDefinitions(SettingDefinitionProviderContext context)
{
return new[]
{
new SettingDefinition(AppSettingNames.UiTheme, "red",
scopes: SettingScopes.Application | SettingScopes.Tenant | SettingScopes.User,
isVisibleToClients: true),
new SettingDefinition(AppSettingNames.AutoSaveHistory, "true", scopes: SettingScopes.User,
isVisibleToClients: true),
};
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Crawlers/DefaultQuery.cs
================================================
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Abp.Domain.Entities.Auditing;
using AcmStatisticsBackend.Authorization.Users;
namespace AcmStatisticsBackend.Crawlers
{
///
/// 用户的默认查询。用户登录后,查题页面会自动填充此查询的内容
///
public class DefaultQuery : FullAuditedEntity
{
[Required]
public User User { get; set; }
public long UserId { get; set; }
///
/// 主用户名
///
[Required]
[MinLength(0)]
public string MainUsername { get; set; }
///
/// 在各个爬虫上的用户名。key为爬虫名称,value为一个用户名的列表,表示在该爬虫上的所有用户名。
///
[Required]
public Dictionary> UsernamesInCrawlers { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Crawlers/QueryCrawlerSummary.cs
================================================
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Abp.Domain.Entities;
namespace AcmStatisticsBackend.Crawlers
{
///
/// Store the summary of a certain crawler.
///
public class QueryCrawlerSummary : Entity
{
[Required]
public QuerySummary QuerySummary { get; set; }
public long QuerySummaryId { get; set; }
///
/// The name of the crawler. Frontend can get its title by this field.
///
[Required]
public string CrawlerName { get; set; }
///
/// Submission count.
///
[Range(0, int.MaxValue)]
public int Submission { get; set; }
///
/// Solved count.
///
[Range(0, int.MaxValue)]
public int Solved { get; set; }
///
/// Usernames used in this crawler
///
public ICollection Usernames { get; set; }
public bool IsVirtualJudge { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Crawlers/QueryHistory.cs
================================================
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Abp.Domain.Entities;
using AcmStatisticsBackend.Authorization.Users;
namespace AcmStatisticsBackend.Crawlers
{
///
/// 一次查询历史记录
///
public class QueryHistory : Entity
{
[Required]
public DateTime CreationTime { get; set; }
///
/// The user related to this entity
///
public User User { get; set; }
public long UserId { get; set; }
///
/// Main username of query history, can be empty
///
[Required]
[MinLength(0)]
public string MainUsername { get; set; }
///
/// Query history of each crawler.
///
[Required]
public ICollection QueryWorkerHistories { get; set; }
///
/// Is data source reliable (solved/submission are really from certain username)
///
/// When get the history from user directly, it should be false;
/// when get it from crawler-api-backend, it should be true.
///
public bool IsReliableSource { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Crawlers/QuerySummary.cs
================================================
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Abp.Domain.Entities;
namespace AcmStatisticsBackend.Crawlers
{
///
/// The summary of a certain query.
///
public class QuerySummary : Entity
{
[Required]
public QueryHistory QueryHistory { get; set; }
public long QueryHistoryId { get; set; }
///
/// When the summary is generated
///
public DateTime GenerateTime { get; set; }
///
/// Query summaries of each crawler.
///
[Required]
public ICollection QueryCrawlerSummaries { get; set; }
///
/// Warnings in summary generation.
///
[Required]
public ICollection SummaryWarnings { get; set; }
///
/// Total submission count
///
[Range(0, int.MaxValue)]
public int Submission { get; set; }
///
/// Total solved count, redundant problems (including problems in virtual_judge) are removed.
///
[Range(0, int.MaxValue)]
public int Solved { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Crawlers/QueryWorkerHistory.cs
================================================
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using Abp.Domain.Entities;
namespace AcmStatisticsBackend.Crawlers
{
///
/// Query history in a certain crawler
///
public class QueryWorkerHistory : Entity
{
///
/// QueryHistory the entity related to
///
[Required]
public QueryHistory QueryHistory { get; set; }
public long QueryHistoryId { get; set; }
///
/// The name of the crawler. Frontend can get its title by this field.
///
[Required]
public string CrawlerName { get; set; }
///
/// The username used to query this crawler.
///
[Required]
public string Username { get; set; }
///
/// Error message of the crawler. If it's not null, current query is failed, and
/// and are all 0.
///
[MaybeNull]
public string ErrorMessage { get; set; }
///
/// Submission count.
///
[Range(0, int.MaxValue)]
public int Submission { get; set; }
///
/// Solved count.
///
[Range(0, int.MaxValue)]
public int Solved { get; set; }
///
/// The list of problem ids that user solved.
///
/// Can be null if crawler does not support it.
///
[MaybeNull]
public string[] SolvedList { get; set; }
///
/// Whether current crawler is virtual judge when the history is submitted.
///
public bool IsVirtualJudge { get; set; }
///
/// If is false, this field is null.
/// Otherwise, this field contains submissions count in each crawler.
///
[MaybeNull]
public IDictionary SubmissionsByCrawlerName { get; set; }
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Crawlers/SummaryGenerator.cs
================================================
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using Abp.Dependency;
using Abp.Extensions;
using Abp.Timing;
using Abp.UI;
using AcmStatisticsBackend.ServiceClients;
namespace AcmStatisticsBackend.Crawlers
{
///
/// Generate summarise from
///
public class SummaryGenerator : ISingletonDependency
{
private readonly IClockProvider _clockProvider;
public SummaryGenerator(IClockProvider clockProvider)
{
_clockProvider = clockProvider;
}
///
/// Generate summary from .
/// should already be loaded.
///
/// It will not modify the parameter.
///
[Pure]
public QuerySummary Generate(
IReadOnlyCollection crawlerMeta,
IReadOnlyCollection workerHistories)
{
var histories = workerHistories
.Where(item => item.ErrorMessage.IsNullOrEmpty())
.ToList();
ResolveSummaryData(crawlerMeta, histories,
out var summaries,
out var warnings,
out var directlyAddSolvedWorkerList);
foreach (var worker in directlyAddSolvedWorkerList)
{
var summary = summaries[worker.CrawlerName];
summary.Usernames.Add(new UsernameInCrawler
{
Username = worker.Username,
});
}
var localJudgeDict = summaries
.Where(it => it.Value.IsVirtualJudge == false)
.ToDictionary(
p => p.Key,
p => new QueryCrawlerSummary
{
CrawlerName = p.Value.CrawlerName,
Solved = p.Value.SolvedSet.Count,
Submission = p.Value.Submissions,
Usernames = p.Value.Usernames.ToList(),
IsVirtualJudge = p.Value.IsVirtualJudge,
});
// directlyAddSolvedWorkerList only exists in local judges
foreach (var worker in directlyAddSolvedWorkerList)
{
var summary = localJudgeDict[worker.CrawlerName];
summary.Solved += worker.Solved;
summary.Submission += worker.Submission;
}
var virtualJudgeList = summaries
.Select(it => it.Value)
.Where(it => it.IsVirtualJudge)
.SelectMany(it => new[]
{
new QueryCrawlerSummary
{
CrawlerName = it.CrawlerName,
Solved = it.SolvedSet.Count,
Submission = it.Submissions,
Usernames = it.Usernames.ToList(),
IsVirtualJudge = false,
},
new QueryCrawlerSummary
{
CrawlerName = it.CrawlerName,
Solved = it.NotMergedSolvedSet.Count,
Submission = it.NotMergedSubmissions,
Usernames = it.NotMergedUsernames.ToList(),
IsVirtualJudge = true,
},
});
var summaryList = localJudgeDict
.Select(p => p.Value)
.Concat(virtualJudgeList)
.Where(a => a.Usernames.Count > 0
&& (a.Submission > 0 || a.Solved > 0))
.OrderBy(a => a.CrawlerName)
.ToList();
return new QuerySummary
{
QueryCrawlerSummaries = summaryList,
SummaryWarnings = warnings,
Solved = summaryList.Sum(a => a.Solved),
Submission = summaryList.Sum(a => a.Submission),
GenerateTime = _clockProvider.Now,
};
}
///
/// Pre-process data
///
private static void ResolveSummaryData(
IReadOnlyCollection crawlerMeta,
IReadOnlyCollection workerHistories,
out Dictionary summaries,
out List warnings,
out List directlyAddSolvedWorkerList)
{
summaries = InitSummaries(crawlerMeta);
warnings = new List();
directlyAddSolvedWorkerList = new List();
EnsureCrawlerType(crawlerMeta, summaries, workerHistories);
foreach (var worker in workerHistories)
{
var summary = summaries[worker.CrawlerName];
summary.Usernames.Add(new UsernameInCrawler
{
Username = worker.Username,
});
if (summary.IsVirtualJudge)
{
summary.NotMergedUsernames.Add(new UsernameInCrawler
{
Username = worker.Username,
});
}
if (worker.SolvedList == null)
{
Debug.Assert(worker.IsVirtualJudge == false,
"All virtual judges should have solved list");
warnings.Add(new SummaryWarning(
worker.CrawlerName,
"This crawler does not have a solved list and " +
"its result will be directly added to summary."));
directlyAddSolvedWorkerList.Add(worker);
continue;
}
if (worker.IsVirtualJudge)
{
if (worker.SubmissionsByCrawlerName.Values.Sum() != worker.Submission)
{
warnings.Add(new SummaryWarning(worker.CrawlerName,
"submissionByCrawler field of this crawler does not match its submission field, " +
"and only results in submissionByCrawler are used."));
}
HandleVirtualJudgeProblems(worker, summary, summaries);
HandleVirtualJudgeSubmissions(worker, summary, summaries);
}
else
{
summary.Submissions += worker.Submission;
summary.SolvedSet.UnionWith(worker.SolvedList);
}
}
}
private static void EnsureCrawlerType(
IReadOnlyCollection crawlerMeta,
IReadOnlyDictionary summaries,
IReadOnlyCollection workerHistories)
{
var workerHasSolvedList = new Dictionary();
foreach (var history in workerHistories)
{
if (workerHasSolvedList.TryGetValue(history.CrawlerName, out var hasSolvedList))
{
if (hasSolvedList != (history.SolvedList != null))
{
var title = GetCrawlerTitle(crawlerMeta, history);
throw new UserFriendlyException($"All workers of crawler {title} must have solved list!");
}
}
else
{
workerHasSolvedList.Add(history.CrawlerName, history.SolvedList != null);
}
if (!summaries.TryGetValue(history.CrawlerName, out var summary))
{
throw new UserFriendlyException(
$"The meta data of crawler {history.CrawlerName} does not exist.");
}
if (summary.IsVirtualJudge != history.IsVirtualJudge)
{
var title = GetCrawlerTitle(crawlerMeta, history);
if (summary.IsVirtualJudge)
{
throw new UserFriendlyException(
$"According to crawler meta, the type of crawler {title} should be a virtual judge.");
}
else
{
throw new UserFriendlyException(
$"According to crawler meta, the type of crawler {title} should not be a virtual judge.");
}
}
if (history.IsVirtualJudge && history.SolvedList == null)
{
var title = GetCrawlerTitle(crawlerMeta, history);
throw new UserFriendlyException($"Virtual judge {title} should have a solved list.");
}
}
}
private static string GetCrawlerTitle(
IReadOnlyCollection crawlerMeta,
QueryWorkerHistory history)
{
var meta = crawlerMeta.First(item => item.CrawlerName == history.CrawlerName);
return meta.CrawlerTitle;
}
private static void HandleVirtualJudgeProblems(
QueryWorkerHistory worker,
CrawlerSummaryData vjSummary,
IReadOnlyDictionary summaries)
{
foreach (var problem in worker.SolvedList)
{
var (problemCrawlerName, problemId)
= problem.Split('-');
if (summaries.TryGetValue(problemCrawlerName, out var problemCrawlerSummary))
{
problemCrawlerSummary.Usernames.Add(new UsernameInCrawler
{
Username = worker.Username,
FromCrawlerName = worker.CrawlerName == problemCrawlerName
? null
: worker.CrawlerName,
});
problemCrawlerSummary.SolvedSet.Add(problemId);
}
else
{
vjSummary.NotMergedSolvedSet.Add(problem);
}
}
}
private static void HandleVirtualJudgeSubmissions(
QueryWorkerHistory worker,
CrawlerSummaryData vjSummary,
IReadOnlyDictionary summaries)
{
foreach (var (crawler, submissions) in worker.SubmissionsByCrawlerName)
{
if (summaries.TryGetValue(crawler, out var crawlerSummary))
{
crawlerSummary.Submissions += submissions;
crawlerSummary.Usernames.Add(new UsernameInCrawler
{
Username = worker.Username,
FromCrawlerName = worker.CrawlerName == crawler
? null
: worker.CrawlerName,
});
}
else
{
vjSummary.NotMergedSubmissions += submissions;
}
}
}
private static Dictionary InitSummaries(
IReadOnlyCollection crawlerMeta)
{
return crawlerMeta
.ToDictionary(
crawlerMetaItem => crawlerMetaItem.CrawlerName,
crawlerMetaItem => new CrawlerSummaryData
{
CrawlerName = crawlerMetaItem.CrawlerName,
IsVirtualJudge = crawlerMetaItem.IsVirtualJudge,
});
}
///
/// Data structure to use inside the algorithm
///
private class CrawlerSummaryData
{
public string CrawlerName { get; set; }
public bool IsVirtualJudge { get; set; }
// in virtual judge, the two items means its local judge result
public HashSet SolvedSet { get; } = new HashSet();
public int Submissions { get; set; }
public HashSet Usernames { get; }
// only work in virtual judge
public HashSet NotMergedSolvedSet { get; } = new HashSet();
public int NotMergedSubmissions { get; set; }
public HashSet NotMergedUsernames { get; }
public CrawlerSummaryData()
{
Usernames = new HashSet(new UsernameInCrawlerEqualityComparer());
NotMergedUsernames = new HashSet(new UsernameInCrawlerEqualityComparer());
}
}
private class UsernameInCrawlerEqualityComparer : IEqualityComparer
{
public bool Equals(UsernameInCrawler x, UsernameInCrawler y)
{
if (x == null && y == null)
{
return true;
}
if (x == null || y == null)
{
return false;
}
return x.Username == y.Username && x.FromCrawlerName == y.FromCrawlerName;
}
public int GetHashCode(UsernameInCrawler obj)
{
return $"{obj.FromCrawlerName ?? string.Empty}/{obj.Username ?? string.Empty}"
.GetHashCode();
}
}
}
}
================================================
FILE: backend/src/AcmStatisticsBackend.Core/Crawlers/SummaryWarning.cs
================================================
using System.Collections.Generic;
using Abp.Domain.Values;
namespace AcmStatisticsBackend.Crawlers
{
///
/// A warning in
///
public class SummaryWarning : ValueObject
{
public SummaryWarning(string crawlerName, string content)
{
CrawlerName = crawlerName;
Content = content;
}
///
/// The crawler the warning is about
///
public string CrawlerName { get; }
///
/// Warning content
///
public string Content { get; }
protected override IEnumerable