From f31c051beb0104fddd31b212480aa1745fd3400b Mon Sep 17 00:00:00 2001 From: Ivan Magda Date: Fri, 30 Jul 2021 16:29:54 +0300 Subject: [PATCH 01/12] Optimize finding a particular object (#1022) * Add NSManagedObjectContextExtensions * Add ManagedObject protocol * Conform to ManagedObject & add BasePersistenceService * Reformat code * refreshAllObjects on applicationDidReceiveMemoryWarning(_:) --- Stepic.xcodeproj/project.pbxproj | 28 +-- .../Events/AmplitudeAnalyticsEvents.swift | 2 +- Stepic/Legacy/AppDelegate.swift | 8 +- .../CardStep/CardStepDelegate.swift | 4 + .../AdaptiveSteps/Views/CardOverlayView.swift | 4 +- .../Views/StepCardView/StepCardView.swift | 1 + .../Certificates/CertificatesPresenter.swift | 24 ++- .../CertificatesViewController.swift | 1 + .../SearchQueriesPersistentManager.swift | 2 +- .../SearchQueriesViewController.swift | 2 +- .../BaseQuiz/QuizControllerDelegate.swift | 3 + .../InputAccessory/CodeSnippetSymbols.swift | 2 +- .../Extensions/StandardsExtensions.swift | 2 +- .../Extensions/UIButtonExtensions.swift | 2 +- .../Legacy/Extensions/UIViewExtensions.swift | 2 +- Stepic/Legacy/Helpers/ConnectionHelper.swift | 2 +- Stepic/Legacy/Helpers/StringHelper.swift | 2 +- Stepic/Legacy/Helpers/TimeFormatHelper.swift | 2 +- .../ApplicationInfo/ApplicationInfo.swift | 10 + .../Assignment+CoreDataProperties.swift | 48 ++--- .../Entities/Assignment/Assignment.swift | 23 +-- .../AttemptEntity+CoreDataProperties.swift | 99 +++++++++- .../Entities/Attempt/AttemptEntity.swift | 140 ++------------ .../Block/Block+CoreDataProperties.swift | 25 --- .../Legacy/Model/Entities/Block/Block.swift | 13 +- ...atalogBlockEntity+CoreDataProperties.swift | 90 ++++++++- .../CatalogBlock/CatalogBlockEntity.swift | 115 +----------- .../Certificate+CoreDataProperties.swift | 103 ++++------- .../Entities/Certificate/Certificate.swift | 43 +---- .../CodeLimit+CoreDataProperties.swift | 39 +--- .../Model/Entities/CodeLimit/CodeLimit.swift | 21 +-- .../CodeSample+CoreDataProperties.swift | 33 +--- .../Entities/CodeSample/CodeSample.swift | 21 +-- .../CodeTemplate+CoreDataProperties.swift | 39 +--- .../Entities/CodeTemplates/CodeTemplate.swift | 36 ++-- .../Course/Course+CoreDataProperties.swift | 20 -- .../Legacy/Model/Entities/Course/Course.swift | 172 +----------------- ...CourseBeneficiary+CoreDataProperties.swift | 17 -- .../CourseBeneficiary/CourseBeneficiary.swift | 9 +- .../CourseBenefit+CoreDataProperties.swift | 17 -- .../CourseBenefit/CourseBenefit.swift | 9 +- ...rseBenefitByMonth+CoreDataProperties.swift | 17 -- .../CourseBenefitByMonth.swift | 9 +- ...rseBenefitSummary+CoreDataProperties.swift | 17 -- .../CourseBenefitSummary.swift | 9 +- .../CourseList+CoreDataProperties.swift | 18 +- .../Entities/CourseList/CourseListModel.swift | 21 +-- .../CoursePurchase+CoreDataProperties.swift | 17 -- .../CoursePurchase/CoursePurchase.swift | 9 +- .../CourseReview+CoreDataProperties.swift | 29 --- .../Entities/CourseReview/CourseReview.swift | 31 ++-- ...urseReviewSummary+CoreDataProperties.swift | 21 --- .../CourseReviewSummary.swift | 21 +-- .../DiscussionThread+CoreDataProperties.swift | 13 -- .../DiscussionThread/DiscussionThread.swift | 13 +- .../EmailAddress+CoreDataProperties.swift | 21 --- .../Entities/EmailAddress/EmailAddress.swift | 41 ++--- .../ExamSession+CoreDataProperties.swift | 13 -- .../Entities/ExamSession/ExamSession.swift | 13 +- .../LastCodeLanguage+CoreDataProperties.swift | 13 -- .../LastCodeLanguage/LastCodeLanguage.swift | 5 +- .../LastStep+CoreDataProperties.swift | 23 +-- .../Model/Entities/LastStep/LastStep.swift | 25 +-- .../Lesson/Lesson+CoreDataProperties.swift | 24 --- .../Legacy/Model/Entities/Lesson/Lesson.swift | 112 +----------- .../Notification+CoreDataProperties.swift | 21 --- .../Notification+FetchMethods.swift | 15 +- .../Entities/Notification/Notification.swift | 82 ++++----- .../ProctorSession+CoreDataProperties.swift | 13 -- .../ProctorSession/ProctorSession.swift | 13 +- .../Profile/Profile+CoreDataProperties.swift | 25 --- .../Model/Entities/Profile/Profile.swift | 26 +-- .../Progress+CoreDataProperties.swift | 24 --- .../Model/Entities/Progress/Progress.swift | 41 ++--- .../Section/Section+CoreDataProperties.swift | 24 --- .../Model/Entities/Section/Section.swift | 32 ++-- .../SocialProfile+CoreDataProperties.swift | 17 -- .../SocialProfile/SocialProfile.swift | 17 +- .../Step/Step+CoreDataProperties.swift | 24 --- Stepic/Legacy/Model/Entities/Step/Step.swift | 14 +- .../StepOptions+CoreDataProperties.swift | 21 --- .../Entities/StepOptions/StepOptions.swift | 19 +- ...StoryPartReaction+CoreDataProperties.swift | 17 -- .../StoryPartReaction/StoryPartReaction.swift | 29 ++- .../SubmissionEntity+CoreDataProperties.swift | 99 +++++++++- .../Submission/SubmissionEntity.swift | 139 ++------------ .../Unit/Unit+CoreDataProperties.swift | 24 --- Stepic/Legacy/Model/Entities/Unit/Unit.swift | 60 ++---- .../User/User+CoreDataProperties.swift | 28 --- Stepic/Legacy/Model/Entities/User/User.swift | 28 ++- ...serActivityEntity+CoreDataProperties.swift | 19 +- .../UserActivity/UserActivityEntity.swift | 40 ++-- .../UserCourse+CoreDataProperties.swift | 19 -- .../Entities/UserCourse/UserCourse.swift | 11 +- .../Video/Video+CoreDataProperties.swift | 24 --- .../Legacy/Model/Entities/Video/Video.swift | 54 ++---- .../VideoURL+CoreDataProperties.swift | 24 --- .../Model/Entities/VideoURL/VideoURL.swift | 13 +- .../Model/ExecutionQueue/ExecutionQueue.swift | 4 +- .../ExecutionQueue/ExecutionQueues.swift | 1 + .../PersistentTaskRecoveryManager.swift | 2 +- Stepic/Legacy/Model/JSONSerializable.swift | 2 +- Stepic/Legacy/Model/Network/AuthAPI.swift | 8 +- .../Model/Network/Endpoints/APIEndpoint.swift | 2 +- .../Endpoints/CourseBenefitSummariesAPI.swift | 2 +- .../Network/Endpoints/EnrollmentsAPI.swift | 2 +- .../Network/Endpoints/NotificationsAPI.swift | 2 +- .../RequestMakers/RetrieveRequestMaker.swift | 7 +- .../Model/Notifications/DeviceDefaults.swift | 1 + .../LoadingPaginationView.swift | 2 +- .../PickerViewController.swift | 4 +- .../Tooltip/TooltipDefaultsManager.swift | 1 + ...agedObjectContext+BatchDeleteRequest.swift | 10 - ...agedObjectContext+BatchUpdateRequest.swift | 10 - .../NSManagedObjectContextExtensions.swift | 59 ++++++ .../UIKit/UIColor+DynamicColor.swift | 2 +- .../View/ProcessedContentWebView.swift | 1 + .../Provider/SyllabusDownloadsService.swift | 1 + .../CourseList/CourseListDataFlow.swift | 1 + ...mpleCourseListCollectionViewDelegate.swift | 2 +- .../Modules/Lesson/LessonProvider.swift | 2 +- .../ChildProtocols/QuizInputProtocol.swift | 5 + Stepic/Sources/Protocols/IDTypeable.swift | 7 - Stepic/Sources/Protocols/Identifiable.swift | 7 + Stepic/Sources/Protocols/ManagedObject.swift | 113 ++++++++++++ .../UserActivitiesNetworkService.swift | 2 +- .../AssignmentsPersistenceService.swift | 49 +---- .../AttemptsPersistenceService.swift | 82 ++------- .../Persistence/BasePersistenceService.swift | 79 ++++++++ .../BlocksPersistenceService.swift | 34 +--- .../CatalogBlocksPersistenceService.swift | 162 +++-------------- .../CertificatesPersistenceService.swift | 94 ++++------ .../CodeLimitsPersistenceService.swift | 34 +--- .../CodeSamplesPersistenceService.swift | 34 +--- .../CodeTemplatesPersistenceService.swift | 35 +--- ...ourseBeneficiariesPersistenceService.swift | 54 +----- ...rseBenefitByMonthsPersistenceService.swift | 117 ++---------- ...seBenefitSummariesPersistenceService.swift | 75 +------- .../CourseBenefitsPersistenceService.swift | 107 +---------- .../CourseListsPersistenceService.swift | 45 +---- .../CoursePurchasesPersistenceService.swift | 73 ++------ ...rseReviewSummariesPersistenceService.swift | 53 +----- .../CourseReviewsPersistenceService.swift | 42 +---- .../CoursesPersistenceService.swift | 43 +---- .../DiscussionThreadsPersistenceService.swift | 42 +---- .../EmailAddressesPersistenceService.swift | 47 +---- .../ExamSessionsPersistenceService.swift | 47 +---- .../LastCodeLanguagePersistenceService.swift | 35 +--- .../LastStepPersistenceService.swift | 34 +--- .../LessonsPersistenceService.swift | 54 +----- .../NotificationsPersistenceService.swift | 35 +--- .../ProctorSessionsPersistenceService.swift | 47 +---- .../ProfilesPersistenceService.swift | 74 +------- .../ProgressesPersistenceService.swift | 57 +----- .../SectionsPersistenceService.swift | 58 +----- .../SocialProfilesPersistenceService.swift | 44 +---- .../StepOptionsPersistenceService.swift | 32 +--- .../Persistence/StepsPersistenceService.swift | 54 +----- ...toryPartsReactionsPersistenceService.swift | 64 ++----- .../SubmissionsPersistenceService.swift | 77 +------- .../Persistence/UnitsPersistenceService.swift | 58 +----- .../UserActivitiesPersistenceService.swift | 91 +-------- .../UserCoursesPersistenceService.swift | 95 +--------- .../Persistence/UsersPersistenceService.swift | 49 +---- .../VideoURLsPersistenceService.swift | 34 +--- .../VideosPersistenceService.swift | 34 +--- .../StreakNotificationsStorageManager.swift | 2 +- 167 files changed, 1354 insertions(+), 4110 deletions(-) delete mode 100644 Stepic/Sources/Extensions/CoreData/NSManagedObjectContext+BatchDeleteRequest.swift delete mode 100644 Stepic/Sources/Extensions/CoreData/NSManagedObjectContext+BatchUpdateRequest.swift create mode 100644 Stepic/Sources/Extensions/CoreData/NSManagedObjectContextExtensions.swift delete mode 100644 Stepic/Sources/Protocols/IDTypeable.swift create mode 100644 Stepic/Sources/Protocols/Identifiable.swift create mode 100644 Stepic/Sources/Protocols/ManagedObject.swift create mode 100644 Stepic/Sources/Services/Models/Persistence/BasePersistenceService.swift diff --git a/Stepic.xcodeproj/project.pbxproj b/Stepic.xcodeproj/project.pbxproj index 4e97ae1efc..e4f1ad0ab2 100644 --- a/Stepic.xcodeproj/project.pbxproj +++ b/Stepic.xcodeproj/project.pbxproj @@ -433,6 +433,7 @@ 2C0FE8CE25F81B8100626289 /* InstructionsResponse.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C0FE8CD25F81B8100626289 /* InstructionsResponse.swift */; }; 2C0FE8D425F81D0500626289 /* InstructionDataPlainObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C0FE8D325F81D0500626289 /* InstructionDataPlainObject.swift */; }; 2C0FE8E225F81D9C00626289 /* InstructionsNetworkService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C0FE8E125F81D9C00626289 /* InstructionsNetworkService.swift */; }; + 2C0FF78D26B2A3E800BF9E32 /* NSManagedObjectContextExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C0FF78C26B2A3E800BF9E32 /* NSManagedObjectContextExtensions.swift */; }; 2C10100B239EFAD700440651 /* DiscountingPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C10100A239EFAD700440651 /* DiscountingPolicy.swift */; }; 2C104B682069064D0026FEB9 /* autocomplete_suggestions.plist in Resources */ = {isa = PBXBuildFile; fileRef = 2C104B672069064D0026FEB9 /* autocomplete_suggestions.plist */; }; 2C10650825ECE1610094FC39 /* CourseInfoTabInfoSkeletonView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C10650725ECE1610094FC39 /* CourseInfoTabInfoSkeletonView.swift */; }; @@ -442,7 +443,6 @@ 2C11C9F224EFC81500A4647B /* LeftAlignedCollectionViewFlowLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C11C9F124EFC81500A4647B /* LeftAlignedCollectionViewFlowLayout.swift */; }; 2C11C9F424EFCB2600A4647B /* UIFont+SizeOfString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C11C9F324EFCB2600A4647B /* UIFont+SizeOfString.swift */; }; 2C1219901F9655AB00A43E98 /* NotificationsSection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C12198F1F9655AB00A43E98 /* NotificationsSection.swift */; }; - 2C129F5626AADB0B005C86F1 /* NSManagedObjectContext+BatchUpdateRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C129F5526AADB0B005C86F1 /* NSManagedObjectContext+BatchUpdateRequest.swift */; }; 2C12E4722565668000DC52CB /* UIViewController+PresentPanModal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C12E4712565668000DC52CB /* UIViewController+PresentPanModal.swift */; }; 2C130E3C2512402B00389AEB /* LaunchArguments.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C130E3B2512402B00389AEB /* LaunchArguments.swift */; }; 2C16495922C10DD400DF18CA /* UserActivitiesNetworkService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C16495822C10DD300DF18CA /* UserActivitiesNetworkService.swift */; }; @@ -683,6 +683,8 @@ 2C6FA0B52588B1CF00D50DAA /* GridSimpleCourseListView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C6FA0B42588B1CF00D50DAA /* GridSimpleCourseListView.swift */; }; 2C7024BA23D00762002A0246 /* SettingsRightDetailSwitchTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C7024B923D00762002A0246 /* SettingsRightDetailSwitchTableViewCell.swift */; }; 2C7024BC23D00799002A0246 /* SettingsRightDetailSwitchCellView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C7024BB23D00799002A0246 /* SettingsRightDetailSwitchCellView.swift */; }; + 2C71BC0726B34D27000AF7B8 /* Identifiable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C71BC0626B34D27000AF7B8 /* Identifiable.swift */; }; + 2C71BC0926B34D43000AF7B8 /* BasePersistenceService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C71BC0826B34D43000AF7B8 /* BasePersistenceService.swift */; }; 2C71F10B256D9C9400A1D40B /* DefaultSimpleCourseListCollectionViewDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C71F10A256D9C9400A1D40B /* DefaultSimpleCourseListCollectionViewDataSource.swift */; }; 2C71F110256D9CAC00A1D40B /* DefaultSimpleCourseListCollectionViewDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C71F10F256D9CAC00A1D40B /* DefaultSimpleCourseListCollectionViewDelegate.swift */; }; 2C71F118256DA2FF00A1D40B /* SimpleCourseListCellSkeletonView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C71F117256DA2FF00A1D40B /* SimpleCourseListCellSkeletonView.swift */; }; @@ -905,7 +907,6 @@ 2CAD8B9D2170CDB4003F420B /* LocalNotificationProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CAD8B9C2170CDB4003F420B /* LocalNotificationProtocol.swift */; }; 2CADE6182487B4BD00F523FA /* GoogleService-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 2CADE6172487B4BC00F523FA /* GoogleService-Info.plist */; }; 2CADFEF424C1325F00008C65 /* AchievementProgressData.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CADFEF324C1325F00008C65 /* AchievementProgressData.swift */; }; - 2CB06B1E25E6809A00DEF0AA /* IDTypeable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB06B1D25E6809A00DEF0AA /* IDTypeable.swift */; }; 2CB1139C2591F5F60093B572 /* StoryReactionsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB1139B2591F5F60093B572 /* StoryReactionsView.swift */; }; 2CB113A6259203C90093B572 /* StoryPartReaction.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB113A5259203C90093B572 /* StoryPartReaction.swift */; }; 2CB113AB259203DC0093B572 /* StoryPartReaction+CoreDataProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CB113AA259203DC0093B572 /* StoryPartReaction+CoreDataProperties.swift */; }; @@ -1051,7 +1052,6 @@ 2CE532F7266E965600E80983 /* course-benefit-summaries.json in Resources */ = {isa = PBXBuildFile; fileRef = 2CE532F6266E965600E80983 /* course-benefit-summaries.json */; }; 2CE532F9266EB02200E80983 /* CourseBenefitSummariesAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CE532F8266EB02200E80983 /* CourseBenefitSummariesAPI.swift */; }; 2CE532FB266EB0A400E80983 /* CourseBenefitSummariesPersistenceService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CE532FA266EB0A400E80983 /* CourseBenefitSummariesPersistenceService.swift */; }; - 2CE53300266EBDC200E80983 /* NSManagedObjectContext+BatchDeleteRequest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CE532FF266EBDC200E80983 /* NSManagedObjectContext+BatchDeleteRequest.swift */; }; 2CE61D832412960500DA2CBA /* SpotlightSearchableItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CE61D822412960500DA2CBA /* SpotlightSearchableItem.swift */; }; 2CE61D852412961500DA2CBA /* SpotlightDomainIdentifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CE61D842412961500DA2CBA /* SpotlightDomainIdentifier.swift */; }; 2CE664E320F5207A0082F3FE /* Downloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CE664DF20F520790082F3FE /* Downloader.swift */; }; @@ -1618,6 +1618,7 @@ 62E98EF6C22D39234F586361 /* ContinueCourseViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62E98EC2E16550A310CE6CEF /* ContinueCourseViewController.swift */; }; 62E98EF8366F3A12CA5092BF /* VerticalCourseListFlowLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62E986AFDD619AB21C4C0A51 /* VerticalCourseListFlowLayout.swift */; }; 62E98F05C243FB1C3EEBA452 /* CourseInfoStatsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62E9825DC46191B6B299CBC2 /* CourseInfoStatsView.swift */; }; + 62E98F13BC8E26F8FBC95D7A /* ManagedObject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62E98E646899D7ADA713E675 /* ManagedObject.swift */; }; 62E98F1672B90358D7188D02 /* AnalyticsEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62E98BDA7FFECA95F0389E12 /* AnalyticsEvent.swift */; }; 62E98F2598146750666AC334 /* CodeQuizInteractor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62E98B848C748B543CBEEFC4 /* CodeQuizInteractor.swift */; }; 62E98F431204AD9A46EBBC18 /* CodeEditorSettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62E98F34F48CF83CC3A6939B /* CodeEditorSettingsViewController.swift */; }; @@ -2298,6 +2299,7 @@ 2C0FE8CD25F81B8100626289 /* InstructionsResponse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InstructionsResponse.swift; sourceTree = ""; }; 2C0FE8D325F81D0500626289 /* InstructionDataPlainObject.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InstructionDataPlainObject.swift; sourceTree = ""; }; 2C0FE8E125F81D9C00626289 /* InstructionsNetworkService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InstructionsNetworkService.swift; sourceTree = ""; }; + 2C0FF78C26B2A3E800BF9E32 /* NSManagedObjectContextExtensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NSManagedObjectContextExtensions.swift; sourceTree = ""; }; 2C101009239E7A1E00440651 /* Model_discount_policy.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Model_discount_policy.xcdatamodel; sourceTree = ""; }; 2C10100A239EFAD700440651 /* DiscountingPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiscountingPolicy.swift; sourceTree = ""; }; 2C104B672069064D0026FEB9 /* autocomplete_suggestions.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = autocomplete_suggestions.plist; sourceTree = ""; }; @@ -2308,7 +2310,6 @@ 2C11C9F124EFC81500A4647B /* LeftAlignedCollectionViewFlowLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LeftAlignedCollectionViewFlowLayout.swift; sourceTree = ""; }; 2C11C9F324EFCB2600A4647B /* UIFont+SizeOfString.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIFont+SizeOfString.swift"; sourceTree = ""; }; 2C12198F1F9655AB00A43E98 /* NotificationsSection.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationsSection.swift; sourceTree = ""; }; - 2C129F5526AADB0B005C86F1 /* NSManagedObjectContext+BatchUpdateRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NSManagedObjectContext+BatchUpdateRequest.swift"; sourceTree = ""; }; 2C12E4712565668000DC52CB /* UIViewController+PresentPanModal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIViewController+PresentPanModal.swift"; sourceTree = ""; }; 2C130E3B2512402B00389AEB /* LaunchArguments.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LaunchArguments.swift; sourceTree = ""; }; 2C16495822C10DD300DF18CA /* UserActivitiesNetworkService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserActivitiesNetworkService.swift; sourceTree = ""; }; @@ -2578,6 +2579,8 @@ 2C6FA0B42588B1CF00D50DAA /* GridSimpleCourseListView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GridSimpleCourseListView.swift; sourceTree = ""; }; 2C7024B923D00762002A0246 /* SettingsRightDetailSwitchTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsRightDetailSwitchTableViewCell.swift; sourceTree = ""; }; 2C7024BB23D00799002A0246 /* SettingsRightDetailSwitchCellView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsRightDetailSwitchCellView.swift; sourceTree = ""; }; + 2C71BC0626B34D27000AF7B8 /* Identifiable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Identifiable.swift; sourceTree = ""; }; + 2C71BC0826B34D43000AF7B8 /* BasePersistenceService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BasePersistenceService.swift; sourceTree = ""; }; 2C71F10A256D9C9400A1D40B /* DefaultSimpleCourseListCollectionViewDataSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DefaultSimpleCourseListCollectionViewDataSource.swift; sourceTree = ""; }; 2C71F10F256D9CAC00A1D40B /* DefaultSimpleCourseListCollectionViewDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DefaultSimpleCourseListCollectionViewDelegate.swift; sourceTree = ""; }; 2C71F117256DA2FF00A1D40B /* SimpleCourseListCellSkeletonView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SimpleCourseListCellSkeletonView.swift; sourceTree = ""; }; @@ -2801,7 +2804,6 @@ 2CADE6172487B4BC00F523FA /* GoogleService-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "GoogleService-Info.plist"; sourceTree = ""; }; 2CADFEF324C1325F00008C65 /* AchievementProgressData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AchievementProgressData.swift; sourceTree = ""; }; 2CAFAF042609DC3E00701D9F /* Model_NSSecureCoding_v75.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Model_NSSecureCoding_v75.xcdatamodel; sourceTree = ""; }; - 2CB06B1D25E6809A00DEF0AA /* IDTypeable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IDTypeable.swift; sourceTree = ""; }; 2CB1139B2591F5F60093B572 /* StoryReactionsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StoryReactionsView.swift; sourceTree = ""; }; 2CB113A32592027F0093B572 /* Model_stories_reactions_v69.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Model_stories_reactions_v69.xcdatamodel; sourceTree = ""; }; 2CB113A5259203C90093B572 /* StoryPartReaction.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StoryPartReaction.swift; sourceTree = ""; }; @@ -2963,7 +2965,6 @@ 2CE532F6266E965600E80983 /* course-benefit-summaries.json */ = {isa = PBXFileReference; lastKnownFileType = text.json; path = "course-benefit-summaries.json"; sourceTree = ""; }; 2CE532F8266EB02200E80983 /* CourseBenefitSummariesAPI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CourseBenefitSummariesAPI.swift; sourceTree = ""; }; 2CE532FA266EB0A400E80983 /* CourseBenefitSummariesPersistenceService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CourseBenefitSummariesPersistenceService.swift; sourceTree = ""; }; - 2CE532FF266EBDC200E80983 /* NSManagedObjectContext+BatchDeleteRequest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "NSManagedObjectContext+BatchDeleteRequest.swift"; sourceTree = ""; }; 2CE61D822412960500DA2CBA /* SpotlightSearchableItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpotlightSearchableItem.swift; sourceTree = ""; }; 2CE61D842412961500DA2CBA /* SpotlightDomainIdentifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpotlightDomainIdentifier.swift; sourceTree = ""; }; 2CE664DF20F520790082F3FE /* Downloader.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Downloader.swift; sourceTree = ""; }; @@ -3522,6 +3523,7 @@ 62E98E4D4741666669A686DC /* CourseInfoTabSyllabusCellView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CourseInfoTabSyllabusCellView.swift; sourceTree = ""; }; 62E98E5CA4710BE490DE7E6D /* ContentLanguageSwitchProvider.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ContentLanguageSwitchProvider.swift; sourceTree = ""; }; 62E98E5D6E662E9B3CFE47DE /* CourseInfoTabReviewsAssembly.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CourseInfoTabReviewsAssembly.swift; sourceTree = ""; }; + 62E98E646899D7ADA713E675 /* ManagedObject.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ManagedObject.swift; sourceTree = ""; }; 62E98E680AE36BC996E47264 /* SectionsNetworkService.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SectionsNetworkService.swift; sourceTree = ""; }; 62E98E6904F6002E123A1A7C /* CodeQuizFullscreenRunCodePresenter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CodeQuizFullscreenRunCodePresenter.swift; sourceTree = ""; }; 62E98E718321FFBD61C5A671 /* CourseWidgetStatsItemView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CourseWidgetStatsItemView.swift; sourceTree = ""; }; @@ -6399,8 +6401,7 @@ 2CE532FE266EBD9100E80983 /* CoreData */ = { isa = PBXGroup; children = ( - 2CE532FF266EBDC200E80983 /* NSManagedObjectContext+BatchDeleteRequest.swift */, - 2C129F5526AADB0B005C86F1 /* NSManagedObjectContext+BatchUpdateRequest.swift */, + 2C0FF78C26B2A3E800BF9E32 /* NSManagedObjectContextExtensions.swift */, ); path = CoreData; sourceTree = ""; @@ -7769,6 +7770,7 @@ children = ( 2CB9529D22A0351F00A6117A /* AssignmentsPersistenceService.swift */, 2C04BA532407C3BF00D74D4B /* AttemptsPersistenceService.swift */, + 2C71BC0826B34D43000AF7B8 /* BasePersistenceService.swift */, 2CE9BF49248D09FC004F6659 /* BlocksPersistenceService.swift */, 2C1AC30D255B3D5900E6ECA9 /* CatalogBlocksPersistenceService.swift */, 62E983871207544AF21C27C6 /* CertificatesPersistenceService.swift */, @@ -8017,7 +8019,8 @@ 62E982AE7C8995C2C6F1A430 /* Protocols */ = { isa = PBXGroup; children = ( - 2CB06B1D25E6809A00DEF0AA /* IDTypeable.swift */, + 2C71BC0626B34D27000AF7B8 /* Identifiable.swift */, + 62E98E646899D7ADA713E675 /* ManagedObject.swift */, 62E98F9F759D04EFACC2579D /* NibLoadable.swift */, 62E980F9CFE23B23B5720F5E /* ProgrammaticallyInitializableViewProtocol.swift */, 62E98128FE2C79FBA6AD7D4B /* Reusable.swift */, @@ -10360,6 +10363,7 @@ 08E43E9E214C27B200E3CB50 /* ModalRouter.swift in Sources */, 083E1DA61C96E9F100B305E4 /* ApplicationInfo.swift in Sources */, 08F555501C4F93B700C877E8 /* Dataset.swift in Sources */, + 2C0FF78D26B2A3E800BF9E32 /* NSManagedObjectContextExtensions.swift in Sources */, 2CDA1AF72613920200E36BF7 /* ExamSession.swift in Sources */, 2C97E00A215E47EC005684A1 /* SearchQueriesPresenter.swift in Sources */, 08CA59EA1BBD3D55008DC44D /* UILabelExtensions.swift in Sources */, @@ -10514,6 +10518,7 @@ 08F485AF1C58E946000165AA /* SortingDataset.swift in Sources */, 2CF1B33E2163BE720008DA0C /* StoriesAssembly.swift in Sources */, 2C04BA542407C3BF00D74D4B /* AttemptsPersistenceService.swift in Sources */, + 2C71BC0926B34D43000AF7B8 /* BasePersistenceService.swift in Sources */, 083AE48320BD72CA00102FE4 /* PersonalDeadlinesService.swift in Sources */, 080DCF171C4518BC00DE3E2E /* SearchResult.swift in Sources */, 2CC3518F1F682B6C004255B6 /* SocialAuthHeaderView.swift in Sources */, @@ -10608,7 +10613,6 @@ 2C71F10B256D9C9400A1D40B /* DefaultSimpleCourseListCollectionViewDataSource.swift in Sources */, 2C0B42C1234CD17C00B03EA1 /* CustomMenuBlockTableViewCell.swift in Sources */, 085DF8DB1C9AB94B006809D9 /* TimeFormatHelper.swift in Sources */, - 2CB06B1E25E6809A00DEF0AA /* IDTypeable.swift in Sources */, 2C5DF1391FEBDC8C003B1177 /* CardsStepsPresenter.swift in Sources */, 08F485A01C579319000165AA /* NumberReply.swift in Sources */, 2CD846471F25FB6C00E8153C /* Profile+CoreDataProperties.swift in Sources */, @@ -10662,7 +10666,6 @@ 2CA6A1E6266624F4000AAA90 /* ReviewsAndWishlistContainerViewController.swift in Sources */, 2C11C9F424EFCB2600A4647B /* UIFont+SizeOfString.swift in Sources */, 08E43E98214C279700E3CB50 /* PushRouter.swift in Sources */, - 2C129F5626AADB0B005C86F1 /* NSManagedObjectContext+BatchUpdateRequest.swift in Sources */, 2CC3518A1F682A02004255B6 /* SocialAuthCollectionViewCell.swift in Sources */, 086D5B52201283C2000F7715 /* TooltipFactory.swift in Sources */, 0813EEA61BFE5A5400DB4B83 /* Assignment+CoreDataProperties.swift in Sources */, @@ -10978,6 +10981,7 @@ 62E98E72EB42F2A772BF9760 /* AchievementProgressesAPI.swift in Sources */, 2CFFC6232681EBB3005D3082 /* CourseRevenueIncomeView.swift in Sources */, 62E98622F3B03F7282DC06D8 /* AchievementDescription.swift in Sources */, + 2C71BC0726B34D27000AF7B8 /* Identifiable.swift in Sources */, 62E98381EC6AD8DD7613C32D /* AchievementsListViewController.swift in Sources */, 2C5E90822333CF4C00288BE3 /* LastCodeLanguage+CoreDataProperties.swift in Sources */, 2C73E24124D0117400340052 /* NewProfileSocialProfilesViewModel.swift in Sources */, @@ -11328,7 +11332,6 @@ 2CF8DF5B25F25CA300F577C2 /* ReviewPlainObject.swift in Sources */, 62E98AAB78A4AC1374AF2FE8 /* EditStepDataFlow.swift in Sources */, 62E98D3AA0AF10457B47857C /* EditStepInteractor.swift in Sources */, - 2CE53300266EBDC200E80983 /* NSManagedObjectContext+BatchDeleteRequest.swift in Sources */, 2C0FA689252F4D7A0032DDEC /* Typography.swift in Sources */, 62E98A9F7DF282A326FF2F5A /* EditStepPresenter.swift in Sources */, 62E986AB8C08F56B64F290B4 /* EditStepProvider.swift in Sources */, @@ -11904,6 +11907,7 @@ 2A28D42937FBB186FA6FA6BB /* CourseRevenueTabMonthlyViewController.swift in Sources */, 733EA9B5B70C811D7A144DF3 /* CourseRevenueTabMonthlyInputProtocol.swift in Sources */, EF3252195A0C7A3F15319D12 /* CourseRevenueTabMonthlyOutputProtocol.swift in Sources */, + 62E98F13BC8E26F8FBC95D7A /* ManagedObject.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/Stepic/Legacy/Analytics/Events/AmplitudeAnalyticsEvents.swift b/Stepic/Legacy/Analytics/Events/AmplitudeAnalyticsEvents.swift index 0830ee1e67..f486d3b1c7 100644 --- a/Stepic/Legacy/Analytics/Events/AmplitudeAnalyticsEvents.swift +++ b/Stepic/Legacy/Analytics/Events/AmplitudeAnalyticsEvents.swift @@ -84,7 +84,7 @@ extension AnalyticsEvent { title: String, isWishlisted: Bool? = nil ) -> AmplitudeAnalyticsEvent { - var parameters: [String : Any] = [ + var parameters: [String: Any] = [ "source": source.rawValue, "course": id, "title": title diff --git a/Stepic/Legacy/AppDelegate.swift b/Stepic/Legacy/AppDelegate.swift index 12b4ad7e3e..64def61784 100644 --- a/Stepic/Legacy/AppDelegate.swift +++ b/Stepic/Legacy/AppDelegate.swift @@ -141,7 +141,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { return true } - // MARK: - Responding to App State Changes and System Events + // MARK: - Responding to App Life-Cycle Events func applicationWillEnterForeground(_ application: UIApplication) { self.notificationsRegistrationService.renewDeviceToken() @@ -189,6 +189,12 @@ class AppDelegate: UIResponder, UIApplicationDelegate { IAPService.shared.stopObservingPayments() } + // MARK: - Responding to Environment Changes + + func applicationDidReceiveMemoryWarning(_ application: UIApplication) { + CoreDataHelper.shared.context.refreshAllObjects() + } + // MARK: - Downloading Data in the Background func application( diff --git a/Stepic/Legacy/Controllers/AdaptiveSteps/CardStep/CardStepDelegate.swift b/Stepic/Legacy/Controllers/AdaptiveSteps/CardStep/CardStepDelegate.swift index a84d72ca07..ddbff504f1 100644 --- a/Stepic/Legacy/Controllers/AdaptiveSteps/CardStep/CardStepDelegate.swift +++ b/Stepic/Legacy/Controllers/AdaptiveSteps/CardStep/CardStepDelegate.swift @@ -18,8 +18,12 @@ protocol CardStepDelegate: AnyObject { extension CardStepDelegate { func stepSubmissionDidCorrect() {} + func stepSubmissionDidWrong() {} + func stepSubmissionDidRetry() {} + func contentLoadingDidFail() {} + func contentLoadingDidComplete() {} } diff --git a/Stepic/Legacy/Controllers/AdaptiveSteps/Views/CardOverlayView.swift b/Stepic/Legacy/Controllers/AdaptiveSteps/Views/CardOverlayView.swift index 632e5226ae..ee28c202d5 100644 --- a/Stepic/Legacy/Controllers/AdaptiveSteps/Views/CardOverlayView.swift +++ b/Stepic/Legacy/Controllers/AdaptiveSteps/Views/CardOverlayView.swift @@ -34,12 +34,12 @@ final class CardOverlayView: OverlayView { override var overlayState: SwipeResultDirection? { didSet { switch overlayState { - case .left : + case .left: overlayImageView.image = UIImage(named: overlayLeftImageName) leadingConstraint.deactivate() trailingConstraint.activate() - case .right : + case .right: overlayImageView.image = UIImage(named: overlayRightImageName) leadingConstraint.activate() diff --git a/Stepic/Legacy/Controllers/AdaptiveSteps/Views/StepCardView/StepCardView.swift b/Stepic/Legacy/Controllers/AdaptiveSteps/Views/StepCardView/StepCardView.swift index 71bcc69493..5c70cf2e4a 100644 --- a/Stepic/Legacy/Controllers/AdaptiveSteps/Views/StepCardView/StepCardView.swift +++ b/Stepic/Legacy/Controllers/AdaptiveSteps/Views/StepCardView/StepCardView.swift @@ -16,6 +16,7 @@ protocol StepCardViewDelegate: AnyObject { extension StepCardViewDelegate { func onControlButtonClick() {} + func onTitleButtonClick() {} } diff --git a/Stepic/Legacy/Controllers/Certificates/CertificatesPresenter.swift b/Stepic/Legacy/Controllers/Certificates/CertificatesPresenter.swift index de8703e791..6f1080c62b 100644 --- a/Stepic/Legacy/Controllers/Certificates/CertificatesPresenter.swift +++ b/Stepic/Legacy/Controllers/Certificates/CertificatesPresenter.swift @@ -16,6 +16,8 @@ final class CertificatesPresenter { private let coursesAPI: CoursesAPI private let presentationContainer: CertificatesPresentationContainer + private let certificatesPersistenceService: CertificatesPersistenceServiceProtocol + private var certificates: [Certificate] = [] { didSet { self.updatePersistentPresentationData() @@ -30,29 +32,33 @@ final class CertificatesPresenter { certificatesAPI: CertificatesAPI, coursesAPI: CoursesAPI, presentationContainer: CertificatesPresentationContainer, + certificatesPersistenceService: CertificatesPersistenceServiceProtocol, view: CertificatesView? ) { self.userID = userID self.certificatesAPI = certificatesAPI self.coursesAPI = coursesAPI self.presentationContainer = presentationContainer + self.certificatesPersistenceService = certificatesPersistenceService self.view = view } func getCachedCertificates() { let localIds = self.presentationContainer.certificatesIds - let localCertificates = Certificate.fetch(localIds, user: self.userID).sorted(by: { - guard let index1 = localIds.firstIndex(of: $0.id), - let index2 = localIds.firstIndex(of: $1.id) else { - return false + self.certificatesPersistenceService.fetch(ids: localIds, userID: self.userID).done { cachedCertificates in + let localCertificates = cachedCertificates.sorted(by: { + guard let index1 = localIds.firstIndex(of: $0.id), + let index2 = localIds.firstIndex(of: $1.id) else { + return false + } + return index1 < index2 + }).compactMap { [weak self] in + self?.makeViewData(from: $0) } - return index1 < index2 - }).compactMap { [weak self] in - self?.makeViewData(from: $0) - } - self.view?.setCertificates(certificates: localCertificates, hasNextPage: false) + self.view?.setCertificates(certificates: localCertificates, hasNextPage: false) + } } private func updatePersistentPresentationData() { diff --git a/Stepic/Legacy/Controllers/Certificates/CertificatesViewController.swift b/Stepic/Legacy/Controllers/Certificates/CertificatesViewController.swift index f3b18176ab..d76a36c967 100644 --- a/Stepic/Legacy/Controllers/Certificates/CertificatesViewController.swift +++ b/Stepic/Legacy/Controllers/Certificates/CertificatesViewController.swift @@ -30,6 +30,7 @@ final class CertificatesLegacyAssembly: Assembly { certificatesAPI: ApiDataDownloader.certificates, coursesAPI: ApiDataDownloader.courses, presentationContainer: PresentationContainer.certificates, + certificatesPersistenceService: CertificatesPersistenceService(), view: certificatesVC ) diff --git a/Stepic/Legacy/Controllers/Courses/SearchQueries/SearchQueriesPersistentManager.swift b/Stepic/Legacy/Controllers/Courses/SearchQueries/SearchQueriesPersistentManager.swift index 6b688e5e7b..d63d5d0a9f 100644 --- a/Stepic/Legacy/Controllers/Courses/SearchQueries/SearchQueriesPersistentManager.swift +++ b/Stepic/Legacy/Controllers/Courses/SearchQueries/SearchQueriesPersistentManager.swift @@ -33,7 +33,7 @@ final class SearchQueriesPersistentManager { key.indexOf(query.lowercased()) != nil }) let arr = [String](filteredQueries.sorted(by: { - (first: (key: String, value: Int), second: (key: String, value: Int)) in + (first: (key: String, value: Int), second: (key: String, value: Int)) in if first.value == second.value { return first.key.count < second.key.count } else { diff --git a/Stepic/Legacy/Controllers/Courses/SearchQueries/SearchQueriesView/SearchQueriesViewController.swift b/Stepic/Legacy/Controllers/Courses/SearchQueries/SearchQueriesView/SearchQueriesViewController.swift index 5ad27da073..48a5a442ca 100644 --- a/Stepic/Legacy/Controllers/Courses/SearchQueries/SearchQueriesView/SearchQueriesViewController.swift +++ b/Stepic/Legacy/Controllers/Courses/SearchQueries/SearchQueriesView/SearchQueriesViewController.swift @@ -121,7 +121,7 @@ extension SearchQueriesViewController: SearchQueriesView { case .updating: self.updatingView.setLoading() self.tableView.tableFooterView = self.updatingView - case.ok: + case .ok: self.tableView.tableFooterView = UIView() } } diff --git a/Stepic/Legacy/Controllers/Quizzes/BaseQuiz/QuizControllerDelegate.swift b/Stepic/Legacy/Controllers/Quizzes/BaseQuiz/QuizControllerDelegate.swift index d20a8728d9..37b76e3dbe 100644 --- a/Stepic/Legacy/Controllers/Quizzes/BaseQuiz/QuizControllerDelegate.swift +++ b/Stepic/Legacy/Controllers/Quizzes/BaseQuiz/QuizControllerDelegate.swift @@ -17,8 +17,11 @@ protocol QuizControllerDelegate: AnyObject { extension QuizControllerDelegate { func submissionDidCorrect() {} + func submissionDidWrong() {} + func submissionDidRetry() {} + func didWarningPlaceholderShow() {} } diff --git a/Stepic/Legacy/Controllers/Quizzes/CodeQuiz/InputAccessory/CodeSnippetSymbols.swift b/Stepic/Legacy/Controllers/Quizzes/CodeQuiz/InputAccessory/CodeSnippetSymbols.swift index 8689fffdd6..b2abc3bbba 100644 --- a/Stepic/Legacy/Controllers/Quizzes/CodeQuiz/InputAccessory/CodeSnippetSymbols.swift +++ b/Stepic/Legacy/Controllers/Quizzes/CodeQuiz/InputAccessory/CodeSnippetSymbols.swift @@ -16,7 +16,7 @@ struct CodeSnippetSymbols { static func snippets(language: CodeLanguage) -> [String] { switch language { - case .python : + case .python: return python case .java, .java8, .java9, .java11: return java diff --git a/Stepic/Legacy/Extensions/StandardsExtensions.swift b/Stepic/Legacy/Extensions/StandardsExtensions.swift index 0f86b75c0b..d6d9398406 100644 --- a/Stepic/Legacy/Extensions/StandardsExtensions.swift +++ b/Stepic/Legacy/Extensions/StandardsExtensions.swift @@ -51,7 +51,7 @@ func ??? (optional: T?, defaultValue: @autoclosure () -> String) -> String { } } -func ==(lhs: T?, rhs: T?) -> Bool { +func == (lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case (.some(let lhs), .some(let rhs)): return lhs == rhs diff --git a/Stepic/Legacy/Extensions/UIButtonExtensions.swift b/Stepic/Legacy/Extensions/UIButtonExtensions.swift index 1e9f0328e8..54e4e5ab55 100644 --- a/Stepic/Legacy/Extensions/UIButtonExtensions.swift +++ b/Stepic/Legacy/Extensions/UIButtonExtensions.swift @@ -9,7 +9,7 @@ import UIKit extension UIButton { - func setRoundedCorners(cornerRadius radius: CGFloat, borderWidth: CGFloat, borderColor: UIColor ) { + func setRoundedCorners(cornerRadius radius: CGFloat, borderWidth: CGFloat, borderColor: UIColor) { self.layer.cornerRadius = radius self.layer.borderWidth = borderWidth self.layer.borderColor = borderColor.cgColor diff --git a/Stepic/Legacy/Extensions/UIViewExtensions.swift b/Stepic/Legacy/Extensions/UIViewExtensions.swift index e539b8150d..6080004f36 100644 --- a/Stepic/Legacy/Extensions/UIViewExtensions.swift +++ b/Stepic/Legacy/Extensions/UIViewExtensions.swift @@ -17,7 +17,7 @@ extension UIView { self.clipsToBounds = true } - func setRoundedCorners(cornerRadius radius: CGFloat, borderWidth: CGFloat? = nil, borderColor: UIColor? = nil ) { + func setRoundedCorners(cornerRadius radius: CGFloat, borderWidth: CGFloat? = nil, borderColor: UIColor? = nil) { self.layer.cornerRadius = radius if let bw = borderWidth { self.layer.borderWidth = bw diff --git a/Stepic/Legacy/Helpers/ConnectionHelper.swift b/Stepic/Legacy/Helpers/ConnectionHelper.swift index 902f169223..b8d669e47d 100644 --- a/Stepic/Legacy/Helpers/ConnectionHelper.swift +++ b/Stepic/Legacy/Helpers/ConnectionHelper.swift @@ -25,7 +25,7 @@ final class ConnectionHelper: NSObject { func instantiate() {} - func addReachabilityChangedHandler(handler : @escaping (Bool) -> Void) { + func addReachabilityChangedHandler(handler: @escaping (Bool) -> Void) { reachabilityChangedHandlers.append(handler) } diff --git a/Stepic/Legacy/Helpers/StringHelper.swift b/Stepic/Legacy/Helpers/StringHelper.swift index 1c9bbb038a..f6b5f43d08 100644 --- a/Stepic/Legacy/Helpers/StringHelper.swift +++ b/Stepic/Legacy/Helpers/StringHelper.swift @@ -15,7 +15,7 @@ final class StringHelper { var randomString = "" - for _ in 0 ..< length { + for _ in 0.. \(dateComponentsFormatter.stringFromTimeInterval(time))") let additionalFormat = time >= 60 ? "" : (time < 10 ? "0:0" : "0:") - return "\(additionalFormat)\(time >= 60 ? dateComponentsFormatter.string(from: time)! : "\(Int(time))" )" + return "\(additionalFormat)\(time >= 60 ? dateComponentsFormatter.string(from: time)! : "\(Int(time))")" } } diff --git a/Stepic/Legacy/Model/Constants/ApplicationInfo/ApplicationInfo.swift b/Stepic/Legacy/Model/Constants/ApplicationInfo/ApplicationInfo.swift index f5f59d43ba..d216ffe11a 100644 --- a/Stepic/Legacy/Model/Constants/ApplicationInfo/ApplicationInfo.swift +++ b/Stepic/Legacy/Model/Constants/ApplicationInfo/ApplicationInfo.swift @@ -19,46 +19,56 @@ final class ApplicationInfo { static let host = "url.host" static let adaptiveRating = "url.adaptiveRating" } + enum Cookie { static let prefix = "cookie.prefix" } + enum Feature { static let courseUnenrollment = "feature.courseUnenrollment" static let streaks = "feature.streaks" static let notifications = "feature.notifications" } + enum Adaptive { static let supportedCourses = "adaptive.supportedCourses" static let isAdaptive = "adaptive.isAdaptive" static let mainColor = "adaptive.mainColor" static let coursesInfoURL = "adaptive.coursesInfoURL" } + enum RateApp { static let submissionsThreshold = "rateApp.submissionsThreshold" static let appStoreLink = "rateApp.appStoreLink" } + enum SocialProviders { static let vkId = "socialProviders.vk" static let facebookId = "socialProviders.facebook" static let googleId = "socialProviders.google" } + enum AuthType { static let social = "social" static let password = "password" + enum Social { static let id = "social.id" static let secret = "social.secret" static let redirect = "social.redirect_uri" } + enum Password { static let id = "password.id" static let secret = "password.secret" static let redirect = "password.redirect_uri" } } + enum Modules { static let tabs = "modules.tabs" } + enum Versions { static let stories = "versions.stories" } diff --git a/Stepic/Legacy/Model/Entities/Assignment/Assignment+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Assignment/Assignment+CoreDataProperties.swift index c6a6a4b8de..6dcca99789 100644 --- a/Stepic/Legacy/Model/Entities/Assignment/Assignment+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Assignment/Assignment+CoreDataProperties.swift @@ -1,16 +1,4 @@ -// -// Assignment+CoreDataProperties.swift -// Stepic -// -// Created by Alexander Karpov on 19.11.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// -// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu -// to delete and recreate this implementation file for your updated model. -// - import CoreData -import Foundation extension Assignment { @NSManaged var managedId: NSNumber? @@ -21,42 +9,30 @@ extension Assignment { @NSManaged var managedUnit: Unit? @NSManaged var managedProgress: Progress? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "Assignment", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "Assignment") - } - - convenience init() { - self.init(entity: Assignment.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { - set(newId) { - self.managedId = newId as NSNumber? - } get { - managedId?.intValue ?? -1 + self.managedId?.intValue ?? -1 + } + set { + self.managedId = NSNumber(value: newValue) } } var stepId: Int { - set(newId) { - self.managedStepId = newId as NSNumber? - } get { - managedStepId?.intValue ?? -1 + self.managedStepId?.intValue ?? -1 + } + set { + self.managedStepId = NSNumber(value: newValue) } } var unitId: Int { - set(newId) { - self.managedUnitId = newId as NSNumber? - } get { - managedUnitId?.intValue ?? -1 + self.managedUnitId?.intValue ?? -1 + } + set { + self.managedUnitId = NSNumber(value: newValue) } } diff --git a/Stepic/Legacy/Model/Entities/Assignment/Assignment.swift b/Stepic/Legacy/Model/Entities/Assignment/Assignment.swift index 58bee618d1..cf5bb2b192 100644 --- a/Stepic/Legacy/Model/Entities/Assignment/Assignment.swift +++ b/Stepic/Legacy/Model/Entities/Assignment/Assignment.swift @@ -1,35 +1,20 @@ -// -// Assignment.swift -// Stepic -// -// Created by Alexander Karpov on 19.11.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON @objc -final class Assignment: NSManagedObject, IDFetchable { - typealias IdType = Int - +final class Assignment: NSManagedObject, ManagedObject, IDFetchable { required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].intValue self.unitId = json[JSONKey.unit.rawValue].intValue self.stepId = json[JSONKey.step.rawValue].intValue self.progressId = json[JSONKey.progress.rawValue].stringValue } - func update(json: JSON) { - self.initialize(json) - } - enum JSONKey: String { case id case unit diff --git a/Stepic/Legacy/Model/Entities/Attempt/AttemptEntity+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Attempt/AttemptEntity+CoreDataProperties.swift index 8d55406fea..6fcc1bcd4d 100644 --- a/Stepic/Legacy/Model/Entities/Attempt/AttemptEntity+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Attempt/AttemptEntity+CoreDataProperties.swift @@ -17,11 +17,102 @@ extension AttemptEntity { @NSManaged var managedUser: User? @NSManaged var managedSubmission: SubmissionEntity? - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedID), ascending: false)] + var id: Int { + get { + self.managedID.intValue + } + set { + self.managedID = NSNumber(value: newValue) + } } - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "AttemptEntity") + var stepID: Step.IdType { + get { + self.managedStepID.intValue + } + set { + self.managedStepID = NSNumber(value: newValue) + } + } + + var step: Step? { + get { + self.managedStep + } + set { + self.managedStep = newValue + } + } + + var userID: User.IdType { + get { + self.managedUserID.intValue + } + set { + self.managedUserID = NSNumber(value: newValue) + } + } + + var user: User? { + get { + self.managedUser + } + set { + self.managedUser = newValue + } + } + + var dataset: Dataset? { + get { + self.managedDataset + } + set { + self.managedDataset = newValue + } + } + + var datasetURL: String? { + get { + self.managedDatasetURL + } + set { + self.managedDatasetURL = newValue + } + } + + var status: String? { + get { + self.managedStatus + } + set { + self.managedStatus = newValue + } + } + + var timeString: String? { + get { + self.managedTime + } + set { + self.managedTime = newValue + } + } + + var timeLeftString: String? { + get { + self.managedTimeLeft + } + set { + self.managedTimeLeft = newValue + } + } + + var submission: SubmissionEntity? { + get { + self.managedSubmission + } + set { + self.managedSubmission = newValue + } } } diff --git a/Stepic/Legacy/Model/Entities/Attempt/AttemptEntity.swift b/Stepic/Legacy/Model/Entities/Attempt/AttemptEntity.swift index 482cdff978..2f7cefb3d8 100644 --- a/Stepic/Legacy/Model/Entities/Attempt/AttemptEntity.swift +++ b/Stepic/Legacy/Model/Entities/Attempt/AttemptEntity.swift @@ -1,93 +1,13 @@ import CoreData -import Foundation -final class AttemptEntity: NSManagedObject { +final class AttemptEntity: NSManagedObject, ManagedObject, Identifiable { typealias IdType = Int - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "AttemptEntity", in: CoreDataHelper.shared.context)! + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedID), ascending: false)] } - var id: Int { - get { - self.managedID.intValue - } - set { - self.managedID = NSNumber(value: newValue) - } - } - - var stepID: Step.IdType { - get { - self.managedStepID.intValue - } - set { - self.managedStepID = NSNumber(value: newValue) - } - } - - var step: Step? { - get { - self.managedStep - } - set { - self.managedStep = newValue - } - } - - var userID: User.IdType { - get { - self.managedUserID.intValue - } - set { - self.managedUserID = NSNumber(value: newValue) - } - } - - var user: User? { - get { - self.managedUser - } - set { - self.managedUser = newValue - } - } - - var dataset: Dataset? { - get { - self.managedDataset - } - set { - self.managedDataset = newValue - } - } - - var datasetURL: String? { - get { - self.managedDatasetURL - } - set { - self.managedDatasetURL = newValue - } - } - - var status: String? { - get { - self.managedStatus - } - set { - self.managedStatus = newValue - } - } - - var timeString: String? { - get { - self.managedTime - } - set { - self.managedTime = newValue - } - } + static var idAttributeName: String { #keyPath(managedID) } var time: Date? { if let timeString = self.timeString, @@ -97,30 +17,6 @@ final class AttemptEntity: NSManagedObject { return nil } } - - var timeLeftString: String? { - get { - self.managedTimeLeft - } - set { - self.managedTimeLeft = newValue - } - } - - var submission: SubmissionEntity? { - get { - self.managedSubmission - } - set { - self.managedSubmission = newValue - } - } - - // MARK: Init - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) - } } // MARK: - AttemptEntity (PlainObject Support) - @@ -139,25 +35,21 @@ extension AttemptEntity { ) } - convenience init(attempt: Attempt, managedObjectContext: NSManagedObjectContext) { - guard let entity = NSEntityDescription.entity( - forEntityName: "AttemptEntity", in: managedObjectContext - ) else { - fatalError("Wrong object type") - } - - self.init(entity: entity, insertInto: managedObjectContext) + static func insert(into context: NSManagedObjectContext, attempt: Attempt) -> AttemptEntity { + let attemptEntity: AttemptEntity = context.insertObject() - self.id = attempt.id - self.stepID = attempt.stepID - self.dataset = attempt.dataset - self.datasetURL = attempt.datasetURL - self.status = attempt.status - self.timeString = attempt.time - self.timeLeftString = attempt.timeLeft + attemptEntity.id = attempt.id + attemptEntity.stepID = attempt.stepID + attemptEntity.dataset = attempt.dataset + attemptEntity.datasetURL = attempt.datasetURL + attemptEntity.status = attempt.status + attemptEntity.timeString = attempt.time + attemptEntity.timeLeftString = attempt.timeLeft if let userID = attempt.userID { - self.userID = userID + attemptEntity.userID = userID } + + return attemptEntity } } diff --git a/Stepic/Legacy/Model/Entities/Block/Block+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Block/Block+CoreDataProperties.swift index 34bebec05d..18f12fa3ed 100644 --- a/Stepic/Legacy/Model/Entities/Block/Block+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Block/Block+CoreDataProperties.swift @@ -1,17 +1,4 @@ -// -// Block+CoreDataProperties.swift -// Stepic -// -// Created by Alexander Karpov on 12.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// -// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu -// to delete and recreate this implementation file for your updated model. -// - import CoreData -import Foundation -import UIKit extension Block { @NSManaged var managedName: String? @@ -20,18 +7,6 @@ extension Block { @NSManaged var managedVideo: Video? @NSManaged var managedStep: Step? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "Block", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "Block") - } - - convenience init() { - self.init(entity: Block.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var name: String { get { self.managedName ?? "undefined" diff --git a/Stepic/Legacy/Model/Entities/Block/Block.swift b/Stepic/Legacy/Model/Entities/Block/Block.swift index f6a611785e..367b625006 100644 --- a/Stepic/Legacy/Model/Entities/Block/Block.swift +++ b/Stepic/Legacy/Model/Entities/Block/Block.swift @@ -1,16 +1,7 @@ -// -// Block.swift -// Stepic -// -// Created by Alexander Karpov on 12.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class Block: NSManagedObject { +final class Block: NSManagedObject, ManagedObject { var type: BlockType? { BlockType(rawValue: self.name) } var image: UIImage { @@ -32,7 +23,7 @@ final class Block: NSManagedObject { } required convenience init(json: JSON) { - self.init() + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) self.initialize(json) self.video = Video(json: json[JSONKey.video.rawValue]) } diff --git a/Stepic/Legacy/Model/Entities/CatalogBlock/CatalogBlockEntity+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/CatalogBlock/CatalogBlockEntity+CoreDataProperties.swift index 963958b98a..9e63cf367b 100644 --- a/Stepic/Legacy/Model/Entities/CatalogBlock/CatalogBlockEntity+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/CatalogBlock/CatalogBlockEntity+CoreDataProperties.swift @@ -13,11 +13,93 @@ extension CatalogBlockEntity { @NSManaged var managedIsTitleVisible: NSNumber? @NSManaged var managedContent: NSObject? - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedPosition), ascending: true)] + var id: Int { + get { + self.managedId?.intValue ?? 0 + } + set { + self.managedId = NSNumber(value: newValue) + } } - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "CatalogBlockEntity") + var position: Int { + get { + self.managedPosition?.intValue ?? 0 + } + set { + self.managedPosition = NSNumber(value: newValue) + } + } + + var title: String { + get { + self.managedTitle ?? "" + } + set { + self.managedTitle = newValue + } + } + + var descriptionString: String { + get { + self.managedDescription ?? "" + } + set { + self.managedDescription = newValue + } + } + + var language: String { + get { + self.managedLanguage ?? "" + } + set { + self.managedLanguage = newValue + } + } + + var platform: Int { + get { + self.managedPlatform?.intValue ?? PlatformType.ios.rawValue + } + set { + self.managedPlatform = NSNumber(value: newValue) + } + } + + var kind: String { + get { + self.managedKind ?? "" + } + set { + self.managedKind = newValue + } + } + + var appearance: String { + get { + self.managedAppearance ?? "" + } + set { + self.managedAppearance = newValue + } + } + + var isTitleVisible: Bool { + get { + self.managedIsTitleVisible?.boolValue ?? true + } + set { + self.managedIsTitleVisible = NSNumber(value: newValue) + } + } + + var content: [CatalogBlockContentItem] { + get { + self.managedContent as? [CatalogBlockContentItem] ?? [] + } + set { + self.managedContent = NSArray(array: newValue) + } } } diff --git a/Stepic/Legacy/Model/Entities/CatalogBlock/CatalogBlockEntity.swift b/Stepic/Legacy/Model/Entities/CatalogBlock/CatalogBlockEntity.swift index 0aa23037d1..62972c062a 100644 --- a/Stepic/Legacy/Model/Entities/CatalogBlock/CatalogBlockEntity.swift +++ b/Stepic/Legacy/Model/Entities/CatalogBlock/CatalogBlockEntity.swift @@ -1,103 +1,8 @@ import CoreData -import Foundation -final class CatalogBlockEntity: NSManagedObject { - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "CatalogBlockEntity", in: CoreDataHelper.shared.context)! - } - - var id: Int { - get { - self.managedId?.intValue ?? 0 - } - set { - self.managedId = NSNumber(value: newValue) - } - } - - var position: Int { - get { - self.managedPosition?.intValue ?? 0 - } - set { - self.managedPosition = NSNumber(value: newValue) - } - } - - var title: String { - get { - self.managedTitle ?? "" - } - set { - self.managedTitle = newValue - } - } - - var descriptionString: String { - get { - self.managedDescription ?? "" - } - set { - self.managedDescription = newValue - } - } - - var language: String { - get { - self.managedLanguage ?? "" - } - set { - self.managedLanguage = newValue - } - } - - var platform: Int { - get { - self.managedPlatform?.intValue ?? PlatformType.ios.rawValue - } - set { - self.managedPlatform = NSNumber(value: newValue) - } - } - - var kind: String { - get { - self.managedKind ?? "" - } - set { - self.managedKind = newValue - } - } - - var appearance: String { - get { - self.managedAppearance ?? "" - } - set { - self.managedAppearance = newValue - } - } - - var isTitleVisible: Bool { - get { - self.managedIsTitleVisible?.boolValue ?? true - } - set { - self.managedIsTitleVisible = NSNumber(value: newValue) - } - } - - var content: [CatalogBlockContentItem] { - get { - self.managedContent as? [CatalogBlockContentItem] ?? [] - } - set { - self.managedContent = NSArray(array: newValue) - } - } - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) +final class CatalogBlockEntity: NSManagedObject, ManagedObject, Identifiable { + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedPosition), ascending: true)] } } @@ -119,15 +24,13 @@ extension CatalogBlockEntity { ) } - convenience init(catalogBlock: CatalogBlock, managedObjectContext: NSManagedObjectContext) { - guard let entity = NSEntityDescription.entity( - forEntityName: "CatalogBlockEntity", in: managedObjectContext - ) else { - fatalError("Wrong object type") - } - - self.init(entity: entity, insertInto: managedObjectContext) + static func insert(into context: NSManagedObjectContext, catalogBlock: CatalogBlock) -> CatalogBlockEntity { + let catalogBlockEntity: CatalogBlockEntity = context.insertObject() + catalogBlockEntity.update(catalogBlock: catalogBlock) + return catalogBlockEntity + } + func update(catalogBlock: CatalogBlock) { self.id = catalogBlock.id self.position = catalogBlock.position self.title = catalogBlock.title diff --git a/Stepic/Legacy/Model/Entities/Certificate/Certificate+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Certificate/Certificate+CoreDataProperties.swift index c303defdc3..d30512bd22 100644 --- a/Stepic/Legacy/Model/Entities/Certificate/Certificate+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Certificate/Certificate+CoreDataProperties.swift @@ -1,13 +1,4 @@ -// -// Certificate+CoreDataProperties.swift -// Stepic -// -// Created by Ostrenkiy on 11.04.17. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension Certificate { @NSManaged var managedId: NSNumber? @@ -20,106 +11,90 @@ extension Certificate { @NSManaged var managedURL: String? @NSManaged var managedisPublic: NSNumber? @NSManaged var managedIsWithScore: NSNumber? - @NSManaged var managedCourse: Course? - - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "Certificate", in: CoreDataHelper.shared.context)! - } - - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "Certificate") - } - convenience init() { - self.init(entity: Certificate.oldEntity, insertInto: CoreDataHelper.shared.context) - } + @NSManaged var managedCourse: Course? var id: Int { - set(newId) { - self.managedId = newId as NSNumber? - } get { - managedId?.intValue ?? -1 + self.managedId?.intValue ?? -1 + } + set { + self.managedId = NSNumber(value: newValue) } } var courseId: Int { - set(newId) { - self.managedCourseId = newId as NSNumber? - } get { - managedCourseId?.intValue ?? -1 + self.managedCourseId?.intValue ?? -1 + } + set { + self.managedCourseId = NSNumber(value: newValue) } } var userId: Int { - set(newId) { - self.managedUserId = newId as NSNumber? - } get { - managedUserId?.intValue ?? -1 + self.managedUserId?.intValue ?? -1 + } + set { + self.managedUserId = NSNumber(value: newValue) } } var issueDate: Date? { - set(date) { - self.managedIssueDate = date - } get { - managedIssueDate + self.managedIssueDate + } + set { + self.managedIssueDate = newValue } } var updateDate: Date? { - set(date) { - self.managedUpdateDate = date - } get { - managedUpdateDate + self.managedUpdateDate + } + set { + self.managedUpdateDate = newValue } - } - - enum CertificateType: String { - case distinction = "distinction", regular = "regular" } var type: CertificateType { - set(type) { - self.managedType = type.rawValue - } get { - CertificateType(rawValue: self.managedType ?? "regular") ?? .regular + if let managedType = self.managedType { + return CertificateType(rawValue: managedType) ?? .regular + } + return .regular + } + set { + self.managedType = newValue.rawValue } } var grade: Int { - set(newGrade) { - self.managedGrade = newGrade as NSNumber? - } get { - managedGrade?.intValue ?? 0 + self.managedGrade?.intValue ?? 0 + } + set { + self.managedGrade = NSNumber(value: newValue) } } var urlString: String? { - set(newUrlString) { - self.managedURL = newUrlString - } get { self.managedURL } + set { + self.managedURL = newValue + } } var isPublic: Bool? { get { self.managedisPublic?.boolValue ?? false } - set(value) { - self.managedisPublic = value as NSNumber? + set { + self.managedisPublic = newValue as NSNumber? } } @@ -136,8 +111,8 @@ extension Certificate { get { self.managedCourse } - set(value) { - self.managedCourse = value + set { + self.managedCourse = newValue } } } diff --git a/Stepic/Legacy/Model/Entities/Certificate/Certificate.swift b/Stepic/Legacy/Model/Entities/Certificate/Certificate.swift index 7ebd1fae15..e9ae0cbef8 100644 --- a/Stepic/Legacy/Model/Entities/Certificate/Certificate.swift +++ b/Stepic/Legacy/Model/Entities/Certificate/Certificate.swift @@ -1,25 +1,21 @@ -// -// Certificate+CoreDataClass.swift -// Stepic -// -// Created by Ostrenkiy on 11.04.17. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON @objc -final class Certificate: NSManagedObject, IDFetchable { +final class Certificate: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int + enum CertificateType: String { + case distinction = "distinction" + case regular = "regular" + } + required convenience init(json: JSON) { - self.init() - initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].intValue self.userId = json[JSONKey.user.rawValue].intValue self.courseId = json[JSONKey.course.rawValue].intValue @@ -32,27 +28,6 @@ final class Certificate: NSManagedObject, IDFetchable { self.isWithScore = json[JSONKey.isWithScore.rawValue].boolValue } - func update(json: JSON) { - initialize(json) - } - - static func fetch(_ ids: [Int], user userId: Int) -> [Certificate] { - let request: NSFetchRequest = Certificate.fetchRequest - - let idPredicates = ids.map { NSPredicate(format: "managedId == %@", $0 as NSNumber) } - let idCompoundPredicate = NSCompoundPredicate(type: .or, subpredicates: idPredicates) - let userPredicate = NSPredicate(format: "managedUserId == %@", userId as NSNumber) - - request.predicate = NSCompoundPredicate(type: .and, subpredicates: [idCompoundPredicate, userPredicate]) - - do { - let results = try CoreDataHelper.shared.context.fetch(request) - return results - } catch { - return [] - } - } - enum JSONKey: String { case id case user diff --git a/Stepic/Legacy/Model/Entities/CodeLimit/CodeLimit+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/CodeLimit/CodeLimit+CoreDataProperties.swift index c7adac9008..0fcc62c022 100644 --- a/Stepic/Legacy/Model/Entities/CodeLimit/CodeLimit+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/CodeLimit/CodeLimit+CoreDataProperties.swift @@ -1,13 +1,4 @@ -// -// CodeLimit+CoreDataProperties.swift -// Stepic -// -// Created by Ostrenkiy on 30.05.17. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension CodeLimit { @NSManaged var managedLanguage: String? @@ -16,42 +7,30 @@ extension CodeLimit { @NSManaged var managedOptions: StepOptions? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "CodeLimit", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "CodeLimit") - } - - convenience init() { - self.init(entity: CodeLimit.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var languageString: String { get { - managedLanguage ?? "" + self.managedLanguage ?? "" } - set(value) { - managedLanguage = value + set { + self.managedLanguage = newValue } } var memory: Double { get { - managedMemory?.doubleValue ?? 0.0 + self.managedMemory?.doubleValue ?? 0.0 } - set(value) { - managedMemory = value as NSNumber? + set { + self.managedMemory = NSNumber(value: newValue) } } var time: Double { get { - managedTime?.doubleValue ?? 0.0 + self.managedTime?.doubleValue ?? 0.0 } - set(value) { - managedTime = value as NSNumber? + set { + self.managedTime = NSNumber(value: newValue) } } } diff --git a/Stepic/Legacy/Model/Entities/CodeLimit/CodeLimit.swift b/Stepic/Legacy/Model/Entities/CodeLimit/CodeLimit.swift index e977592b2e..3a8374d7ad 100644 --- a/Stepic/Legacy/Model/Entities/CodeLimit/CodeLimit.swift +++ b/Stepic/Legacy/Model/Entities/CodeLimit/CodeLimit.swift @@ -1,16 +1,7 @@ -// -// CodeLimit.swift -// Stepic -// -// Created by Ostrenkiy on 30.05.17. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class CodeLimit: NSManagedObject { +final class CodeLimit: NSManagedObject, ManagedObject { var language: CodeLanguage? { CodeLanguage(rawValue: languageString) } override var description: String { @@ -18,20 +9,16 @@ final class CodeLimit: NSManagedObject { } required convenience init(language: String, json: JSON) { - self.init() - self.initialize(language: language, json: json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(language: language, json: json) } - func initialize(language: String, json: JSON) { + func update(language: String, json: JSON) { self.languageString = language self.time = json[JSONKey.time.rawValue].doubleValue self.memory = json[JSONKey.memory.rawValue].doubleValue } - func update(language: String, json: JSON) { - self.initialize(language: language, json: json) - } - func equals(_ object: Any?) -> Bool { guard let object = object as? CodeLimit else { return false diff --git a/Stepic/Legacy/Model/Entities/CodeSample/CodeSample+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/CodeSample/CodeSample+CoreDataProperties.swift index 9f34eefe59..990b49e701 100644 --- a/Stepic/Legacy/Model/Entities/CodeSample/CodeSample+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/CodeSample/CodeSample+CoreDataProperties.swift @@ -1,13 +1,4 @@ -// -// CodeSample+CoreDataProperties.swift -// Stepic -// -// Created by Ostrenkiy on 22.06.17. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension CodeSample { @NSManaged var managedInput: String? @@ -15,33 +6,21 @@ extension CodeSample { @NSManaged var managedOptions: StepOptions? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "CodeSample", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "CodeSample") - } - - convenience init() { - self.init(entity: CodeSample.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var input: String { get { - managedInput ?? "" + self.managedInput ?? "" } - set(value) { - managedInput = value + set { + self.managedInput = newValue } } var output: String { get { - managedOutput ?? "" + self.managedOutput ?? "" } - set(value) { - managedOutput = value + set { + self.managedOutput = newValue } } } diff --git a/Stepic/Legacy/Model/Entities/CodeSample/CodeSample.swift b/Stepic/Legacy/Model/Entities/CodeSample/CodeSample.swift index 7d5f4dda7d..07de5f3ff1 100644 --- a/Stepic/Legacy/Model/Entities/CodeSample/CodeSample.swift +++ b/Stepic/Legacy/Model/Entities/CodeSample/CodeSample.swift @@ -1,34 +1,21 @@ -// -// CodeSample.swift -// Stepic -// -// Created by Ostrenkiy on 22.06.17. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class CodeSample: NSManagedObject { +final class CodeSample: NSManagedObject, ManagedObject { override var description: String { "CodeSample(input: \(self.input), output: \(self.output)" } required convenience init(input: String, output: String) { - self.init() - self.initialize(input: input, output: output) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(input: input, output: output) } - func initialize(input: String, output: String) { + func update(input: String, output: String) { self.input = input self.output = output } - func update(input: String, output: String) { - self.initialize(input: input, output: output) - } - func equals(_ object: Any?) -> Bool { guard let object = object as? CodeSample else { return false diff --git a/Stepic/Legacy/Model/Entities/CodeTemplates/CodeTemplate+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/CodeTemplates/CodeTemplate+CoreDataProperties.swift index 469899c014..f2663150db 100644 --- a/Stepic/Legacy/Model/Entities/CodeTemplates/CodeTemplate+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/CodeTemplates/CodeTemplate+CoreDataProperties.swift @@ -1,13 +1,4 @@ -// -// CodeTemplate+CoreDataProperties.swift -// Stepic -// -// Created by Ostrenkiy on 30.05.17. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension CodeTemplate { @NSManaged var managedLanguage: String? @@ -16,42 +7,30 @@ extension CodeTemplate { @NSManaged var managedOptions: StepOptions? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "CodeTemplate", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "CodeTemplate") - } - - convenience init() { - self.init(entity: CodeTemplate.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var languageString: String { get { - managedLanguage ?? "" + self.managedLanguage ?? "" } - set(value) { - managedLanguage = value + set { + self.managedLanguage = newValue } } var templateString: String { get { - managedTemplateString ?? "" + self.managedTemplateString ?? "" } - set(value) { - managedTemplateString = value + set { + self.managedTemplateString = newValue } } var isUserGenerated: Bool { get { - managedIsUserGenerated?.boolValue ?? true + self.managedIsUserGenerated?.boolValue ?? true } - set(value) { - managedIsUserGenerated = value as NSNumber? + set { + self.managedIsUserGenerated = NSNumber(value: newValue) } } } diff --git a/Stepic/Legacy/Model/Entities/CodeTemplates/CodeTemplate.swift b/Stepic/Legacy/Model/Entities/CodeTemplates/CodeTemplate.swift index 6ad6e819dd..3f28c19b1d 100644 --- a/Stepic/Legacy/Model/Entities/CodeTemplates/CodeTemplate.swift +++ b/Stepic/Legacy/Model/Entities/CodeTemplates/CodeTemplate.swift @@ -1,48 +1,38 @@ -// -// CodeTemplate.swift -// Stepic -// -// Created by Ostrenkiy on 30.05.17. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class CodeTemplate: NSManagedObject { - var language: CodeLanguage? { CodeLanguage(rawValue: languageString) } +final class CodeTemplate: NSManagedObject, ManagedObject { + var language: CodeLanguage? { CodeLanguage(rawValue: self.languageString) } override var description: String { "CodeTemplate(languageString: \(self.languageString), templateString: \(self.templateString)" } - required convenience init(language: CodeLanguage, template: String) { + convenience init() { + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + } + + convenience init(language: CodeLanguage, template: String) { self.init() - let lan = language.rawValue - self.initialize(language: lan, template: template) + self.update(language: language.rawValue, template: template) } - required convenience init(language: String, template: String) { + convenience init(language: String, template: String) { self.init() - self.initialize(language: language, template: template) + self.update(language: language, template: template) } - required convenience init(language: String, template: String, isUserGenerated: Bool) { + convenience init(language: String, template: String, isUserGenerated: Bool) { self.init() - self.initialize(language: language, template: template) + self.update(language: language, template: template) self.isUserGenerated = isUserGenerated } - func initialize(language: String, template: String) { + func update(language: String, template: String) { self.languageString = language self.templateString = template } - func update(language: String, template: String) { - self.initialize(language: language, template: template) - } - func equals(_ object: Any?) -> Bool { guard let object = object as? CodeTemplate else { return false diff --git a/Stepic/Legacy/Model/Entities/Course/Course+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Course/Course+CoreDataProperties.swift index 63bd722b72..9b840eb68e 100644 --- a/Stepic/Legacy/Model/Entities/Course/Course+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Course/Course+CoreDataProperties.swift @@ -1,16 +1,4 @@ -// -// Course+CoreDataProperties.swift -// -// -// Created by Alexander Karpov on 25.09.15. -// -// -// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu -// to delete and recreate this implementation file for your updated model. -// - import CoreData -import Foundation extension Course { @NSManaged var managedId: NSNumber? @@ -88,14 +76,6 @@ extension Course { @NSManaged var managedCourseBenefitByMonths: NSOrderedSet? @NSManaged var managedCourseBeneficiaries: NSSet? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "Course", in: CoreDataHelper.shared.context)! - } - - convenience init() { - self.init(entity: Course.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { set(newId) { self.managedId = newId as NSNumber? diff --git a/Stepic/Legacy/Model/Entities/Course/Course.swift b/Stepic/Legacy/Model/Entities/Course/Course.swift index 912e132297..bb944ec59f 100644 --- a/Stepic/Legacy/Model/Entities/Course/Course.swift +++ b/Stepic/Legacy/Model/Entities/Course/Course.swift @@ -1,18 +1,9 @@ -// -// Course.swift -// -// -// Created by Alexander Karpov on 25.09.15. -// -// - import CoreData -import Foundation import PromiseKit import SwiftyJSON @objc -final class Course: NSManagedObject, IDFetchable { +final class Course: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int var sectionDeadlines: [SectionDeadline]? { @@ -105,11 +96,11 @@ final class Course: NSManagedObject, IDFetchable { } required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].intValue self.title = json[JSONKey.title.rawValue].stringValue self.courseDescription = json[JSONKey.description.rawValue].stringValue @@ -179,141 +170,7 @@ final class Course: NSManagedObject, IDFetchable { } } - func update(json: JSON) { - self.initialize(json) - } - - @available(*, deprecated, message: "Legacy") - func loadAllInstructors(success: @escaping (() -> Void)) { - _ = ApiDataDownloader.users.retrieve( - ids: self.instructorsArray, - existing: self.instructors, - refreshMode: .update, - success: { users in - self.instructors = Sorter.sort(users, byIds: self.instructorsArray) - CoreDataHelper.shared.save() - success() - }, - error: { _ in - print("error while loading section") - } - ) - } - - @available(*, deprecated, message: "Legacy") - func loadAllSections( - success: @escaping (() -> Void), - error errorHandler : @escaping (() -> Void), - withProgresses: Bool = true - ) { - if sectionsArray.isEmpty { - success() - return - } - - let requestSectionsCount = 50 - var dimCount = 0 - var idsArray = [[Int]]() - for (index, sectionId) in self.sectionsArray.enumerated() { - if index % requestSectionsCount == 0 { - idsArray.append([Int]()) - dimCount += 1 - } - idsArray[dimCount - 1].append(sectionId) - } - - var downloadedSections = [Section]() - - let idsDownloaded: ([Section]) -> Void = { - secs in - downloadedSections.append(contentsOf: secs) - if downloadedSections.count == self.sectionsArray.count { - self.sections = Sorter.sort(downloadedSections, byIds: self.sectionsArray) - CoreDataHelper.shared.save() - success() - } - } - - var wasError = false - let errorWhileDownloading : () -> Void = { - if !wasError { - wasError = true - errorHandler() - } - } - - for ids in idsArray { - _ = ApiDataDownloader.sections.retrieve(ids: ids, existing: self.sections, refreshMode: .update, success: { - secs in - if withProgresses { - self.loadProgressesForSections(sections: secs, success: { - idsDownloaded(secs) - }, error: { - errorWhileDownloading() - }) - } else { - idsDownloaded(secs) - } - }, error: { - _ in - print("error while loading section") - errorWhileDownloading() - }) - } - } - @available(*, deprecated, message: "Legacy") - func loadProgressesForSections( - sections: [Section], - success completion: @escaping (() -> Void), - error errorHandler : @escaping (() -> Void) - ) { - var progressIds: [String] = [] - var progresses: [Progress] = [] - for section in sections { - if let progressId = section.progressId { - progressIds += [progressId] - } - - if let progress = section.progress { - progresses += [progress] - } - } - - if progressIds.count == 0 { - completion() - return - } - - _ = ApiDataDownloader.progresses.retrieve(ids: progressIds, existing: progresses, refreshMode: .update, success: { - newProgresses -> Void in - progresses = Sorter.sort(newProgresses, byIds: progressIds) - - if progresses.count == 0 { - CoreDataHelper.shared.save() - completion() - return - } - - var progressCnt = 0 - for i in 0 ..< sections.count { - if sections[i].progressId == progresses[progressCnt].id { - sections[i].progress = progresses[progressCnt] - progressCnt += 1 - } - if progressCnt == progresses.count { - break - } - } - CoreDataHelper.shared.save() - completion() - }, error: { - (_) -> Void in - print("Error while downloading progresses") - errorHandler() - }) - } - static func fetch( _ ids: [Int], featured: Bool? = nil, @@ -357,6 +214,7 @@ final class Course: NSManagedObject, IDFetchable { } } + @available(*, deprecated, message: "Legacy") static func getAllCourses(enrolled: Bool? = nil) -> [Course] { let request = NSFetchRequest(entityName: "Course") var predicate = NSPredicate(value: true) @@ -377,26 +235,6 @@ final class Course: NSManagedObject, IDFetchable { } } - func getSection(before section: Section) -> Section? { - let currentIndex = sectionsArray.firstIndex(of: section.id) - if currentIndex == nil || currentIndex == sectionsArray.startIndex { - return nil - } else { - let prevId = sectionsArray[currentIndex!.advanced(by: -1)] - return sections.filter({ $0.id == prevId }).first - } - } - - func getSection(after section: Section) -> Section? { - let currentIndex = sectionsArray.firstIndex(of: section.id) - if currentIndex == nil || currentIndex == sectionsArray.endIndex.advanced(by: -1) { - return nil - } else { - let nextId = sectionsArray[currentIndex!.advanced(by: 1)] - return sections.filter({ $0.id == nextId }).first - } - } - // MARK: Inner Types enum JSONKey: String { diff --git a/Stepic/Legacy/Model/Entities/CourseBeneficiary/CourseBeneficiary+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/CourseBeneficiary/CourseBeneficiary+CoreDataProperties.swift index 1005b3a2ec..291239ae14 100644 --- a/Stepic/Legacy/Model/Entities/CourseBeneficiary/CourseBeneficiary+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/CourseBeneficiary/CourseBeneficiary+CoreDataProperties.swift @@ -1,5 +1,4 @@ import CoreData -import Foundation extension CourseBeneficiary { @NSManaged var managedId: NSNumber? @@ -11,22 +10,6 @@ extension CourseBeneficiary { @NSManaged var managedUser: User? @NSManaged var managedCourse: Course? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "CourseBeneficiary", in: CoreDataHelper.shared.context)! - } - - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "CourseBeneficiary") - } - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { get { self.managedId?.intValue ?? -1 diff --git a/Stepic/Legacy/Model/Entities/CourseBeneficiary/CourseBeneficiary.swift b/Stepic/Legacy/Model/Entities/CourseBeneficiary/CourseBeneficiary.swift index 665743a3cf..da9e7e5eda 100644 --- a/Stepic/Legacy/Model/Entities/CourseBeneficiary/CourseBeneficiary.swift +++ b/Stepic/Legacy/Model/Entities/CourseBeneficiary/CourseBeneficiary.swift @@ -1,12 +1,15 @@ import CoreData -import Foundation import SwiftyJSON -final class CourseBeneficiary: NSManagedObject, JSONSerializable { +final class CourseBeneficiary: NSManagedObject, ManagedObject, JSONSerializable { typealias IdType = Int + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] + } + required convenience init(json: JSON) { - self.init() + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) self.update(json: json) } diff --git a/Stepic/Legacy/Model/Entities/CourseBenefit/CourseBenefit+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/CourseBenefit/CourseBenefit+CoreDataProperties.swift index ac44c1ddd5..b4e0da85d9 100644 --- a/Stepic/Legacy/Model/Entities/CourseBenefit/CourseBenefit+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/CourseBenefit/CourseBenefit+CoreDataProperties.swift @@ -1,5 +1,4 @@ import CoreData -import Foundation extension CourseBenefit { @NSManaged var managedId: NSNumber? @@ -18,22 +17,6 @@ extension CourseBenefit { @NSManaged var managedCourse: Course? @NSManaged var managedBuyer: User? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "CourseBenefit", in: CoreDataHelper.shared.context)! - } - - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "CourseBenefit") - } - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: IdType { get { self.managedId?.intValue ?? -1 diff --git a/Stepic/Legacy/Model/Entities/CourseBenefit/CourseBenefit.swift b/Stepic/Legacy/Model/Entities/CourseBenefit/CourseBenefit.swift index 6389f90af7..28be982143 100644 --- a/Stepic/Legacy/Model/Entities/CourseBenefit/CourseBenefit.swift +++ b/Stepic/Legacy/Model/Entities/CourseBenefit/CourseBenefit.swift @@ -1,10 +1,13 @@ import CoreData -import Foundation import SwiftyJSON -final class CourseBenefit: NSManagedObject, JSONSerializable { +final class CourseBenefit: NSManagedObject, ManagedObject, JSONSerializable { typealias IdType = Int + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] + } + var status: CourseBenefitStatus? { CourseBenefitStatus(rawValue: self.statusString) } var userSharePercent: Float? { @@ -12,7 +15,7 @@ final class CourseBenefit: NSManagedObject, JSONSerializable { } required convenience init(json: JSON) { - self.init() + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) self.update(json: json) } diff --git a/Stepic/Legacy/Model/Entities/CourseBenefitByMonth/CourseBenefitByMonth+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/CourseBenefitByMonth/CourseBenefitByMonth+CoreDataProperties.swift index 2a60957d24..332dbb92b5 100644 --- a/Stepic/Legacy/Model/Entities/CourseBenefitByMonth/CourseBenefitByMonth+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/CourseBenefitByMonth/CourseBenefitByMonth+CoreDataProperties.swift @@ -1,5 +1,4 @@ import CoreData -import Foundation extension CourseBenefitByMonth { @NSManaged var managedId: String? @@ -21,22 +20,6 @@ extension CourseBenefitByMonth { @NSManaged var managedUser: User? @NSManaged var managedCourse: Course? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "CourseBenefitByMonth", in: CoreDataHelper.shared.context)! - } - - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "CourseBenefitByMonth") - } - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: String { get { self.managedId ?? "" diff --git a/Stepic/Legacy/Model/Entities/CourseBenefitByMonth/CourseBenefitByMonth.swift b/Stepic/Legacy/Model/Entities/CourseBenefitByMonth/CourseBenefitByMonth.swift index 19659ccbdf..0419d6206a 100644 --- a/Stepic/Legacy/Model/Entities/CourseBenefitByMonth/CourseBenefitByMonth.swift +++ b/Stepic/Legacy/Model/Entities/CourseBenefitByMonth/CourseBenefitByMonth.swift @@ -1,17 +1,20 @@ import CoreData -import Foundation import SwiftDate import SwiftyJSON -final class CourseBenefitByMonth: NSManagedObject, JSONSerializable { +final class CourseBenefitByMonth: NSManagedObject, ManagedObject, JSONSerializable { typealias IdType = String + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] + } + var date: DateInRegion? { self.dateString.toISODate(region: Date.europeMoscowRegion) } required convenience init(json: JSON) { - self.init() + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) self.update(json: json) } diff --git a/Stepic/Legacy/Model/Entities/CourseBenefitSummary/CourseBenefitSummary+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/CourseBenefitSummary/CourseBenefitSummary+CoreDataProperties.swift index 75968d1b4b..866d90b15e 100644 --- a/Stepic/Legacy/Model/Entities/CourseBenefitSummary/CourseBenefitSummary+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/CourseBenefitSummary/CourseBenefitSummary+CoreDataProperties.swift @@ -1,5 +1,4 @@ import CoreData -import Foundation extension CourseBenefitSummary { @NSManaged var managedId: NSNumber? @@ -15,22 +14,6 @@ extension CourseBenefitSummary { @NSManaged var managedCourse: Course? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "CourseBenefitSummary", in: CoreDataHelper.shared.context)! - } - - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "CourseBenefitSummary") - } - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { get { self.managedId?.intValue ?? -1 diff --git a/Stepic/Legacy/Model/Entities/CourseBenefitSummary/CourseBenefitSummary.swift b/Stepic/Legacy/Model/Entities/CourseBenefitSummary/CourseBenefitSummary.swift index 1a90671cd4..313da5a6e9 100644 --- a/Stepic/Legacy/Model/Entities/CourseBenefitSummary/CourseBenefitSummary.swift +++ b/Stepic/Legacy/Model/Entities/CourseBenefitSummary/CourseBenefitSummary.swift @@ -1,10 +1,13 @@ import CoreData -import Foundation import SwiftyJSON -final class CourseBenefitSummary: NSManagedObject, JSONSerializable { +final class CourseBenefitSummary: NSManagedObject, ManagedObject, JSONSerializable { typealias IdType = Int + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] + } + var isEmpty: Bool { self.totalUserIncome.isZero && self.totalTurnover.isZero @@ -13,7 +16,7 @@ final class CourseBenefitSummary: NSManagedObject, JSONSerializable { } required convenience init(json: JSON) { - self.init() + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) self.update(json: json) } diff --git a/Stepic/Legacy/Model/Entities/CourseList/CourseList+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/CourseList/CourseList+CoreDataProperties.swift index b5cf6eef1f..fb8464a751 100644 --- a/Stepic/Legacy/Model/Entities/CourseList/CourseList+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/CourseList/CourseList+CoreDataProperties.swift @@ -1,13 +1,4 @@ -// -// CourseList+CoreDataProperties.swift -// Stepic -// -// Created by Ostrenkiy on 10.11.2017. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension CourseListModel { @NSManaged var managedId: NSNumber? @@ -15,18 +6,11 @@ extension CourseListModel { @NSManaged var managedDescription: String? @NSManaged var managedLanguage: String? @NSManaged var managedPosition: NSNumber? + @NSManaged var managedCoursesArray: NSObject? @NSManaged var managedSimilarAuthorsArray: NSObject? @NSManaged var managedSimilarCourseListsArray: NSObject? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "CourseList", in: CoreDataHelper.shared.context)! - } - - convenience init() { - self.init(entity: CourseListModel.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { set(newId) { self.managedId = newId as NSNumber? diff --git a/Stepic/Legacy/Model/Entities/CourseList/CourseListModel.swift b/Stepic/Legacy/Model/Entities/CourseList/CourseListModel.swift index 3929d0f2da..74e70cd6a3 100644 --- a/Stepic/Legacy/Model/Entities/CourseList/CourseListModel.swift +++ b/Stepic/Legacy/Model/Entities/CourseList/CourseListModel.swift @@ -1,23 +1,20 @@ -// -// CourseList.swift -// Stepic -// -// Created by Ostrenkiy on 10.11.2017. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import PromiseKit import SwiftyJSON -final class CourseListModel: NSManagedObject, IDFetchable { +final class CourseListModel: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int + static var entityName: String { "CourseList" } + + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: "managedPosition", ascending: true)] + } + var language: ContentLanguage { ContentLanguage(languageString: self.languageString) } required convenience init(json: JSON) { - self.init() + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) self.update(json: json) } @@ -33,7 +30,7 @@ final class CourseListModel: NSManagedObject, IDFetchable { } static func fetchAsync(ids: [CourseListModel.IdType]) -> Guarantee<[CourseListModel]> { - DatabaseFetchService.fetchAsync(entityName: "CourseList", ids: ids) + DatabaseFetchService.fetchAsync(entityName: Self.entityName, ids: ids) } enum JSONKey: String { diff --git a/Stepic/Legacy/Model/Entities/CoursePurchase/CoursePurchase+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/CoursePurchase/CoursePurchase+CoreDataProperties.swift index 904a8370da..f27cdb1ae0 100644 --- a/Stepic/Legacy/Model/Entities/CoursePurchase/CoursePurchase+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/CoursePurchase/CoursePurchase+CoreDataProperties.swift @@ -1,5 +1,4 @@ import CoreData -import Foundation extension CoursePurchase { @NSManaged var managedId: NSNumber? @@ -10,22 +9,6 @@ extension CoursePurchase { @NSManaged var managedCourse: Course? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "CoursePurchase", in: CoreDataHelper.shared.context)! - } - - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "CoursePurchase") - } - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { get { self.managedId?.intValue ?? 0 diff --git a/Stepic/Legacy/Model/Entities/CoursePurchase/CoursePurchase.swift b/Stepic/Legacy/Model/Entities/CoursePurchase/CoursePurchase.swift index ac77b0f331..155004acf2 100644 --- a/Stepic/Legacy/Model/Entities/CoursePurchase/CoursePurchase.swift +++ b/Stepic/Legacy/Model/Entities/CoursePurchase/CoursePurchase.swift @@ -1,12 +1,15 @@ import CoreData -import Foundation import SwiftyJSON -final class CoursePurchase: NSManagedObject, JSONSerializable, IDFetchable { +final class CoursePurchase: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] + } + required convenience init(json: JSON) { - self.init() + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) self.update(json: json) } diff --git a/Stepic/Legacy/Model/Entities/CourseReview/CourseReview+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/CourseReview/CourseReview+CoreDataProperties.swift index 5abbe49ad1..5db9e9c211 100644 --- a/Stepic/Legacy/Model/Entities/CourseReview/CourseReview+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/CourseReview/CourseReview+CoreDataProperties.swift @@ -1,13 +1,4 @@ -// -// CourseReview+CoreDataProperties.swift -// Stepic -// -// Created by Vladislav Kiryukhin on 12/02/2019. -// Copyright © 2019 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension CourseReview { @NSManaged var managedText: String? @@ -20,26 +11,6 @@ extension CourseReview { @NSManaged var managedCourse: Course? @NSManaged var managedUser: User? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "CourseReview", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "CourseReview") - } - - convenience init() { - self.init(entity: CourseReview.oldEntity, insertInto: CoreDataHelper.shared.context) - } - - convenience init(courseID: Course.IdType, userID: User.IdType, score: Int, text: String) { - self.init(entity: CourseReview.oldEntity, insertInto: CoreDataHelper.shared.context) - self.courseID = courseID - self.userID = userID - self.score = score - self.text = text - } - var id: Int { set { self.managedId = newValue as NSNumber? diff --git a/Stepic/Legacy/Model/Entities/CourseReview/CourseReview.swift b/Stepic/Legacy/Model/Entities/CourseReview/CourseReview.swift index 9cf8b78812..dfb2776c72 100644 --- a/Stepic/Legacy/Model/Entities/CourseReview/CourseReview.swift +++ b/Stepic/Legacy/Model/Entities/CourseReview/CourseReview.swift @@ -1,17 +1,8 @@ -// -// CourseReview.swift -// Stepic -// -// Created by Vladislav Kiryukhin on 12/02/2019. -// Copyright © 2019 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import PromiseKit import SwiftyJSON -final class CourseReview: NSManagedObject, JSONSerializable, IDFetchable { +final class CourseReview: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int var json: JSON { @@ -23,8 +14,16 @@ final class CourseReview: NSManagedObject, JSONSerializable, IDFetchable { ] } + convenience init(courseID: Course.IdType, userID: User.IdType, score: Int, text: String) { + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.courseID = courseID + self.userID = userID + self.score = score + self.text = text + } + required convenience init(json: JSON) { - self.init() + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) initialize(json) } @@ -41,8 +40,9 @@ final class CourseReview: NSManagedObject, JSONSerializable, IDFetchable { initialize(json) } + @available(*, deprecated, message: "Legacy") static func fetch(courseID: Course.IdType) -> Guarantee<[CourseReview]> { - let request = NSFetchRequest(entityName: "CourseReview") + let request = CourseReview.sortedFetchRequest let descriptor = NSSortDescriptor(key: "managedId", ascending: false) let predicate = NSPredicate(format: "managedCourseId == %@", courseID.fetchValue) @@ -65,8 +65,9 @@ final class CourseReview: NSManagedObject, JSONSerializable, IDFetchable { } } + @available(*, deprecated, message: "Legacy") static func fetch(userID: User.IdType) -> Guarantee<[CourseReview]> { - let request = CourseReview.fetchRequest + let request = CourseReview.sortedFetchRequest let descriptor = NSSortDescriptor(key: "managedId", ascending: false) let predicate = NSPredicate(format: "managedUserId == %@", userID.fetchValue) @@ -89,8 +90,9 @@ final class CourseReview: NSManagedObject, JSONSerializable, IDFetchable { } } + @available(*, deprecated, message: "Legacy") static func fetch(courseID: Course.IdType, userID: User.IdType) -> Guarantee<[CourseReview]> { - let request = NSFetchRequest(entityName: "CourseReview") + let request = CourseReview.sortedFetchRequest let descriptor = NSSortDescriptor(key: "managedId", ascending: false) let courseIDPredicate = NSPredicate(format: "managedCourseId == %@", courseID.fetchValue) @@ -115,6 +117,7 @@ final class CourseReview: NSManagedObject, JSONSerializable, IDFetchable { } } + @available(*, deprecated, message: "Legacy") static func delete(_ id: CourseReview.IdType) -> Guarantee { CourseReview.fetchAsync(ids: [id]).done { courseReviews in courseReviews.forEach { diff --git a/Stepic/Legacy/Model/Entities/CourseReviewSummary/CourseReviewSummary+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/CourseReviewSummary/CourseReviewSummary+CoreDataProperties.swift index 335e2f2953..4a55bf0b2e 100644 --- a/Stepic/Legacy/Model/Entities/CourseReviewSummary/CourseReviewSummary+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/CourseReviewSummary/CourseReviewSummary+CoreDataProperties.swift @@ -1,13 +1,4 @@ -// -// CourseReviewSummary+CoreDataProperties.swift -// Stepic -// -// Created by Ostrenkiy on 29.09.2017. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension CourseReviewSummary { @NSManaged var managedDistribution: NSObject? @@ -17,18 +8,6 @@ extension CourseReviewSummary { @NSManaged var managedCourse: Course? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "CourseReviewSummary", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "CourseReviewSummary") - } - - convenience init() { - self.init(entity: CourseReviewSummary.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { get { self.managedId?.intValue ?? -1 diff --git a/Stepic/Legacy/Model/Entities/CourseReviewSummary/CourseReviewSummary.swift b/Stepic/Legacy/Model/Entities/CourseReviewSummary/CourseReviewSummary.swift index 8c9b7e809b..87489dcdc9 100644 --- a/Stepic/Legacy/Model/Entities/CourseReviewSummary/CourseReviewSummary.swift +++ b/Stepic/Legacy/Model/Entities/CourseReviewSummary/CourseReviewSummary.swift @@ -1,16 +1,7 @@ -// -// CourseReviewSummary.swift -// Stepic -// -// Created by Ostrenkiy on 29.09.2017. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class CourseReviewSummary: NSManagedObject, JSONSerializable, IDFetchable { +final class CourseReviewSummary: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int var rating: Int { @@ -18,21 +9,17 @@ final class CourseReviewSummary: NSManagedObject, JSONSerializable, IDFetchable } required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].intValue self.average = json[JSONKey.average.rawValue].floatValue self.count = json[JSONKey.count.rawValue].intValue self.distribution = json[JSONKey.distribution.rawValue].arrayValue.compactMap(\.int) } - func update(json: JSON) { - self.initialize(json) - } - enum JSONKey: String { case id case average diff --git a/Stepic/Legacy/Model/Entities/DiscussionThread/DiscussionThread+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/DiscussionThread/DiscussionThread+CoreDataProperties.swift index 38f6660c9a..1b4da7d6cf 100644 --- a/Stepic/Legacy/Model/Entities/DiscussionThread/DiscussionThread+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/DiscussionThread/DiscussionThread+CoreDataProperties.swift @@ -1,5 +1,4 @@ import CoreData -import Foundation extension DiscussionThread { @NSManaged var managedId: String? @@ -9,18 +8,6 @@ extension DiscussionThread { @NSManaged var managedStep: Step? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "DiscussionThread", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "DiscussionThread") - } - - convenience init() { - self.init(entity: DiscussionThread.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: String { get { self.managedId ?? "" diff --git a/Stepic/Legacy/Model/Entities/DiscussionThread/DiscussionThread.swift b/Stepic/Legacy/Model/Entities/DiscussionThread/DiscussionThread.swift index a1d46ee09f..03ad556a2c 100644 --- a/Stepic/Legacy/Model/Entities/DiscussionThread/DiscussionThread.swift +++ b/Stepic/Legacy/Model/Entities/DiscussionThread/DiscussionThread.swift @@ -1,8 +1,7 @@ import CoreData -import Foundation import SwiftyJSON -final class DiscussionThread: NSManagedObject, JSONSerializable, IDFetchable { +final class DiscussionThread: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = String var json: JSON { @@ -19,21 +18,17 @@ final class DiscussionThread: NSManagedObject, JSONSerializable, IDFetchable { } required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].stringValue self.thread = json[JSONKey.thread.rawValue].stringValue self.discussionsCount = json[JSONKey.discussionsCount.rawValue].intValue self.discussionProxy = json[JSONKey.discussionProxy.rawValue].stringValue } - func update(json: JSON) { - self.initialize(json) - } - // MARK: Enums enum JSONKey: String { diff --git a/Stepic/Legacy/Model/Entities/EmailAddress/EmailAddress+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/EmailAddress/EmailAddress+CoreDataProperties.swift index df3c03477f..45c2ae0a5f 100644 --- a/Stepic/Legacy/Model/Entities/EmailAddress/EmailAddress+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/EmailAddress/EmailAddress+CoreDataProperties.swift @@ -1,13 +1,4 @@ -// -// EmailAddress+CoreDataProperties.swift -// Stepic -// -// Created by Ivan Magda on 10/9/19. -// Copyright © 2019 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension EmailAddress { @NSManaged var managedId: NSNumber? @@ -18,18 +9,6 @@ extension EmailAddress { @NSManaged var managedProfile: Profile? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "EmailAddress", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "EmailAddress") - } - - convenience init() { - self.init(entity: EmailAddress.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { get { self.managedId?.intValue ?? -1 diff --git a/Stepic/Legacy/Model/Entities/EmailAddress/EmailAddress.swift b/Stepic/Legacy/Model/Entities/EmailAddress/EmailAddress.swift index 245fab8a39..fcf071a4b3 100644 --- a/Stepic/Legacy/Model/Entities/EmailAddress/EmailAddress.swift +++ b/Stepic/Legacy/Model/Entities/EmailAddress/EmailAddress.swift @@ -1,35 +1,9 @@ -// -// EmailAddress.swift -// Stepic -// -// Created by Ivan Magda on 10/9/19. -// Copyright © 2019 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class EmailAddress: NSManagedObject, JSONSerializable, IDFetchable { +final class EmailAddress: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int - required convenience init(json: JSON) { - self.init() - self.initialize(json) - } - - func initialize(_ json: JSON) { - self.id = json["id"].intValue - self.userID = json["user"].intValue - self.email = json["email"].stringValue - self.isVerified = json["is_verified"].boolValue - self.isPrimary = json["is_primary"].boolValue - } - - func update(json: JSON) { - self.initialize(json) - } - var json: JSON { [ "id": self.id as AnyObject, @@ -39,4 +13,17 @@ final class EmailAddress: NSManagedObject, JSONSerializable, IDFetchable { "is_primary": self.isPrimary as AnyObject ] } + + required convenience init(json: JSON) { + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) + } + + func update(json: JSON) { + self.id = json["id"].intValue + self.userID = json["user"].intValue + self.email = json["email"].stringValue + self.isVerified = json["is_verified"].boolValue + self.isPrimary = json["is_primary"].boolValue + } } diff --git a/Stepic/Legacy/Model/Entities/ExamSession/ExamSession+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/ExamSession/ExamSession+CoreDataProperties.swift index 851e0b73f1..d41d1e7802 100644 --- a/Stepic/Legacy/Model/Entities/ExamSession/ExamSession+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/ExamSession/ExamSession+CoreDataProperties.swift @@ -1,5 +1,4 @@ import CoreData -import Foundation extension ExamSession { @NSManaged var managedId: NSNumber? @@ -11,18 +10,6 @@ extension ExamSession { @NSManaged var managedSection: Section? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "ExamSession", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "ExamSession") - } - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { get { self.managedId?.intValue ?? -1 diff --git a/Stepic/Legacy/Model/Entities/ExamSession/ExamSession.swift b/Stepic/Legacy/Model/Entities/ExamSession/ExamSession.swift index cca3024048..a4863d3fcc 100644 --- a/Stepic/Legacy/Model/Entities/ExamSession/ExamSession.swift +++ b/Stepic/Legacy/Model/Entities/ExamSession/ExamSession.swift @@ -1,18 +1,17 @@ import CoreData -import Foundation import SwiftyJSON -final class ExamSession: NSManagedObject, JSONSerializable, IDFetchable { +final class ExamSession: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int var isActive: Bool { self.timeLeft > 0 } required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].intValue self.userId = json[JSONKey.user.rawValue].intValue self.sectionId = json[JSONKey.section.rawValue].intValue @@ -21,10 +20,6 @@ final class ExamSession: NSManagedObject, JSONSerializable, IDFetchable { self.timeLeft = json[JSONKey.timeLeft.rawValue].floatValue } - func update(json: JSON) { - self.initialize(json) - } - enum JSONKey: String { case id case user diff --git a/Stepic/Legacy/Model/Entities/LastCodeLanguage/LastCodeLanguage+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/LastCodeLanguage/LastCodeLanguage+CoreDataProperties.swift index c7ca6be99d..a28e38722d 100644 --- a/Stepic/Legacy/Model/Entities/LastCodeLanguage/LastCodeLanguage+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/LastCodeLanguage/LastCodeLanguage+CoreDataProperties.swift @@ -1,22 +1,9 @@ import CoreData -import Foundation extension LastCodeLanguage { @NSManaged var managedLanguage: String? @NSManaged var managedCourse: Course? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "LastCodeLanguage", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "LastCodeLanguage") - } - - convenience init() { - self.init(entity: LastCodeLanguage.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var languageString: String { get { self.managedLanguage ?? "" diff --git a/Stepic/Legacy/Model/Entities/LastCodeLanguage/LastCodeLanguage.swift b/Stepic/Legacy/Model/Entities/LastCodeLanguage/LastCodeLanguage.swift index 1a52da4ef4..be05126aff 100644 --- a/Stepic/Legacy/Model/Entities/LastCodeLanguage/LastCodeLanguage.swift +++ b/Stepic/Legacy/Model/Entities/LastCodeLanguage/LastCodeLanguage.swift @@ -1,7 +1,6 @@ import CoreData -import Foundation -final class LastCodeLanguage: NSManagedObject { +final class LastCodeLanguage: NSManagedObject, ManagedObject { var language: CodeLanguage? { CodeLanguage(rawValue: self.languageString) } override var description: String { @@ -9,7 +8,7 @@ final class LastCodeLanguage: NSManagedObject { } convenience init(language: CodeLanguage) { - self.init() + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) self.languageString = language.rawValue } } diff --git a/Stepic/Legacy/Model/Entities/LastStep/LastStep+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/LastStep/LastStep+CoreDataProperties.swift index 93b14fd5f7..67bac51766 100644 --- a/Stepic/Legacy/Model/Entities/LastStep/LastStep+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/LastStep/LastStep+CoreDataProperties.swift @@ -1,13 +1,4 @@ -// -// LastStep+CoreDataProperties.swift -// Stepic -// -// Created by Alexander Karpov on 13.03.17. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension LastStep { @NSManaged var managedId: String? @@ -16,20 +7,8 @@ extension LastStep { @NSManaged var managedCourse: Course? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "LastStep", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "LastStep") - } - - convenience init() { - self.init(entity: LastStep.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: String { - set (newId) { + set(newId) { self.managedId = newId } get { diff --git a/Stepic/Legacy/Model/Entities/LastStep/LastStep.swift b/Stepic/Legacy/Model/Entities/LastStep/LastStep.swift index 1ef76999c2..9504abc882 100644 --- a/Stepic/Legacy/Model/Entities/LastStep/LastStep.swift +++ b/Stepic/Legacy/Model/Entities/LastStep/LastStep.swift @@ -1,27 +1,22 @@ -// -// LastStep.swift -// Stepic -// -// Created by Alexander Karpov on 13.03.17. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class LastStep: NSManagedObject, JSONSerializable { +final class LastStep: NSManagedObject, ManagedObject, JSONSerializable { typealias IdType = String + convenience init() { + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + } + required convenience init(json: JSON) { self.init() - initialize(json) + self.initialize(json) } func initialize(_ json: JSON) { - id = json["id"].stringValue - unitId = json["unit"].int - stepId = json["step"].int + self.id = json["id"].stringValue + self.unitId = json["unit"].int + self.stepId = json["step"].int } func update(unitId: Int?, stepId: Int?) { @@ -37,6 +32,6 @@ final class LastStep: NSManagedObject, JSONSerializable { } func update(json: JSON) { - initialize(json) + self.initialize(json) } } diff --git a/Stepic/Legacy/Model/Entities/Lesson/Lesson+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Lesson/Lesson+CoreDataProperties.swift index f81c025d8c..25307587ec 100644 --- a/Stepic/Legacy/Model/Entities/Lesson/Lesson+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Lesson/Lesson+CoreDataProperties.swift @@ -1,16 +1,4 @@ -// -// Lesson+CoreDataProperties.swift -// Stepic -// -// Created by Alexander Karpov on 09.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// -// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu -// to delete and recreate this implementation file for your updated model. -// - import CoreData -import Foundation extension Lesson { @NSManaged var managedId: NSNumber? @@ -31,18 +19,6 @@ extension Lesson { @NSManaged var managedUnitsArray: NSObject? @NSManaged var managedUnit: Unit? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "Lesson", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "Lesson") - } - - convenience init() { - self.init(entity: Lesson.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { get { self.managedId?.intValue ?? -1 diff --git a/Stepic/Legacy/Model/Entities/Lesson/Lesson.swift b/Stepic/Legacy/Model/Entities/Lesson/Lesson.swift index dddfea561f..264bd9b26a 100644 --- a/Stepic/Legacy/Model/Entities/Lesson/Lesson.swift +++ b/Stepic/Legacy/Model/Entities/Lesson/Lesson.swift @@ -1,16 +1,7 @@ -// -// Lesson.swift -// Stepic -// -// Created by Alexander Karpov on 09.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class Lesson: NSManagedObject, IDFetchable { +final class Lesson: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int var isCached: Bool { @@ -28,11 +19,11 @@ final class Lesson: NSManagedObject, IDFetchable { } required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].intValue self.title = json[JSONKey.title.rawValue].stringValue self.isFeatured = json[JSONKey.isFeatured.rawValue].boolValue @@ -55,10 +46,6 @@ final class Lesson: NSManagedObject, IDFetchable { } } - func update(json: JSON) { - self.initialize(json) - } - func equals(_ object: Any?) -> Bool { guard let object = object as? Lesson else { return false @@ -85,95 +72,6 @@ final class Lesson: NSManagedObject, IDFetchable { return true } - func loadSteps( - completion: @escaping () -> Void, - error errorHandler: ((String) -> Void)? = nil, - onlyLesson: Bool = false - ) { - _ = ApiDataDownloader.steps.retrieve( - ids: self.stepsArray, - existing: self.steps, - refreshMode: .update, - success: { newSteps in - self.steps = Sorter.sort(newSteps, byIds: self.stepsArray) - self.loadProgressesForSteps({ - if !onlyLesson { - if let unit = self.unit { - _ = ApiDataDownloader.assignments.retrieve( - ids: unit.assignmentsArray, - existing: unit.assignments, - refreshMode: .update, - success: { newAssignments in - unit.assignments = Sorter.sort(newAssignments, steps: self.steps) - completion() - }, - error: { _ in - print("Error while downloading assignments") - errorHandler?("Error while downloading assignments") - } - ) - } else { - completion() - } - } else { - completion() - } - }) - CoreDataHelper.shared.save() - }, - error: { _ in - print("Error while downloading steps") - errorHandler?("Error while downloading steps") - } - ) - } - - func loadProgressesForSteps(_ completion: @escaping () -> Void) { - var progressIds: [String] = [] - var progresses: [Progress] = [] - - for step in steps { - if let progressId = step.progressID { - progressIds += [progressId] - } - if let progress = step.progress { - progresses += [progress] - } - } - - _ = ApiDataDownloader.progresses.retrieve( - ids: progressIds, - existing: progresses, - refreshMode: .update, - success: { newProgresses -> Void in - progresses = Sorter.sort(newProgresses, byIds: progressIds) - for i in 0.. Void in - print("Error while downloading progresses") - } - ) - } - - func getVideoURLs() -> [String] { - var videoURLs = [String]() - - for step in self.steps where step.block.type == .video { - if let video = step.block.video { - videoURLs += [video.urls[0].url] - } - } - - return videoURLs - } - func getVideos() -> [Video] { var videos = [Video]() @@ -186,6 +84,7 @@ final class Lesson: NSManagedObject, IDFetchable { return videos } + @available(*, deprecated, message: "Legacy") static func getLesson(_ id: IdType) -> Lesson? { let request = NSFetchRequest(entityName: "Lesson") request.predicate = NSPredicate(format: "managedId== %@", id as NSNumber) @@ -198,6 +97,7 @@ final class Lesson: NSManagedObject, IDFetchable { } } + @available(*, deprecated, message: "Legacy") static func fetch(_ ids: [IdType]) -> [Lesson] { let request = NSFetchRequest(entityName: "Lesson") diff --git a/Stepic/Legacy/Model/Entities/Notification/Notification+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Notification/Notification+CoreDataProperties.swift index dcf0fc3c06..fa08457a38 100644 --- a/Stepic/Legacy/Model/Entities/Notification/Notification+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Notification/Notification+CoreDataProperties.swift @@ -1,13 +1,4 @@ -// -// Notification+CoreDataProperties.swift -// Stepic -// -// Created by Vladislav Kiryukhin on 26.09.2017. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension Notification { @NSManaged public var managedId: NSNumber? @@ -21,18 +12,6 @@ extension Notification { @NSManaged public var managedPriority: String? @NSManaged public var managedHtmlText: String? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "Notification", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "Notification") - } - - convenience init() { - self.init(entity: Notification.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { get { managedId?.intValue ?? -1 diff --git a/Stepic/Legacy/Model/Entities/Notification/Notification+FetchMethods.swift b/Stepic/Legacy/Model/Entities/Notification/Notification+FetchMethods.swift index e134cd30f2..0927540647 100644 --- a/Stepic/Legacy/Model/Entities/Notification/Notification+FetchMethods.swift +++ b/Stepic/Legacy/Model/Entities/Notification/Notification+FetchMethods.swift @@ -1,17 +1,9 @@ -// -// Notification+FetchMethods.swift -// Stepic -// -// Created by Vladislav Kiryukhin on 13.10.2017. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension Notification { - // FIXME: CREATE GENERIC CLASS + // FIXME: Move to NotificationsPersistenceService + @available(*, deprecated, message: "Legacy") static func fetch(_ ids: [Int]) -> [Notification] { let request = NSFetchRequest(entityName: "Notification") @@ -29,10 +21,12 @@ extension Notification { } } + @available(*, deprecated, message: "Legacy") static func fetch(id: Int) -> Notification? { self.fetch([id]).first } + @available(*, deprecated, message: "Legacy") static func fetch(type: NotificationType?, offset: Int = 0, limit: Int = 10) -> [Notification]? { let request = NSFetchRequest(entityName: "Notification") let sort = NSSortDescriptor(key: "managedTime", ascending: false) @@ -56,6 +50,7 @@ extension Notification { } } + @available(*, deprecated, message: "Legacy") static func markAllAsRead() { let request = NSBatchUpdateRequest(entityName: "Notification") request.predicate = NSPredicate(value: true) diff --git a/Stepic/Legacy/Model/Entities/Notification/Notification.swift b/Stepic/Legacy/Model/Entities/Notification/Notification.swift index f37d2c0453..bc94b918f7 100644 --- a/Stepic/Legacy/Model/Entities/Notification/Notification.swift +++ b/Stepic/Legacy/Model/Entities/Notification/Notification.swift @@ -1,43 +1,10 @@ -// -// Notification.swift -// Stepic -// -// Created by Vladislav Kiryukhin on 26.09.2017. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import PromiseKit import SwiftyJSON -final class Notification: NSManagedObject, JSONSerializable, IDFetchable { +final class Notification: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int - required convenience init(json: JSON) { - self.init() - initialize(json) - } - - func initialize(_ json: JSON) { - id = json["id"].intValue - htmlText = json["html_text"].stringValue - time = Parser.dateFromTimedateJSON(json["time"]) - isMuted = json["is_muted"].boolValue - isFavorite = json["is_favorite"].boolValue - - managedStatus = json["is_unread"].boolValue ? NotificationStatus.unread.rawValue : NotificationStatus.read.rawValue - managedType = json["type"].stringValue - managedAction = json["action"].stringValue - - level = json["level"].stringValue - priority = json["priority"].stringValue - } - - func update(json: JSON) { - initialize(json) - } - var json: JSON { [ "id": id as AnyObject, @@ -51,6 +18,28 @@ final class Notification: NSManagedObject, JSONSerializable, IDFetchable { "priority": priority as AnyObject ] } + + required convenience init(json: JSON) { + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) + } + + func update(json: JSON) { + self.id = json["id"].intValue + self.htmlText = json["html_text"].stringValue + self.time = Parser.dateFromTimedateJSON(json["time"]) + self.isMuted = json["is_muted"].boolValue + self.isFavorite = json["is_favorite"].boolValue + + self.managedStatus = json["is_unread"].boolValue + ? NotificationStatus.unread.rawValue + : NotificationStatus.read.rawValue + self.managedType = json["type"].stringValue + self.managedAction = json["action"].stringValue + + self.level = json["level"].stringValue + self.priority = json["priority"].stringValue + } } enum NotificationStatus: String { @@ -59,21 +48,26 @@ enum NotificationStatus: String { } enum NotificationType: String { - var localizedName: String { - switch self { - case .comments: return NSLocalizedString("NotificationsComments", comment: "") - case .review: return NSLocalizedString("NotificationsReviews", comment: "") - case .teach: return NSLocalizedString("NotificationsTeaching", comment: "") - case .`default`: return NSLocalizedString("NotificationsOther", comment: "") - case .learn: return NSLocalizedString("NotificationsLearning", comment: "") - } - } - case comments = "comments" case learn = "learn" case `default` = "default" case review = "review" case teach = "teach" + + var localizedName: String { + switch self { + case .comments: + return NSLocalizedString("NotificationsComments", comment: "") + case .review: + return NSLocalizedString("NotificationsReviews", comment: "") + case .teach: + return NSLocalizedString("NotificationsTeaching", comment: "") + case .`default`: + return NSLocalizedString("NotificationsOther", comment: "") + case .learn: + return NSLocalizedString("NotificationsLearning", comment: "") + } + } } enum NotificationAction: String { diff --git a/Stepic/Legacy/Model/Entities/ProctorSession/ProctorSession+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/ProctorSession/ProctorSession+CoreDataProperties.swift index d7c9f79bad..fa87c1dcbf 100644 --- a/Stepic/Legacy/Model/Entities/ProctorSession/ProctorSession+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/ProctorSession/ProctorSession+CoreDataProperties.swift @@ -1,5 +1,4 @@ import CoreData -import Foundation extension ProctorSession { @NSManaged var managedId: NSNumber? @@ -19,18 +18,6 @@ extension ProctorSession { @NSManaged var managedSection: Section? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "ProctorSession", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "ProctorSession") - } - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { get { self.managedId?.intValue ?? -1 diff --git a/Stepic/Legacy/Model/Entities/ProctorSession/ProctorSession.swift b/Stepic/Legacy/Model/Entities/ProctorSession/ProctorSession.swift index 6d28da1f36..2ef8d47b04 100644 --- a/Stepic/Legacy/Model/Entities/ProctorSession/ProctorSession.swift +++ b/Stepic/Legacy/Model/Entities/ProctorSession/ProctorSession.swift @@ -1,8 +1,7 @@ import CoreData -import Foundation import SwiftyJSON -final class ProctorSession: NSManagedObject, JSONSerializable, IDFetchable { +final class ProctorSession: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int var isFinished: Bool { @@ -10,11 +9,11 @@ final class ProctorSession: NSManagedObject, JSONSerializable, IDFetchable { } required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].intValue self.userId = json[JSONKey.user.rawValue].intValue self.sectionId = json[JSONKey.section.rawValue].intValue @@ -28,10 +27,6 @@ final class ProctorSession: NSManagedObject, JSONSerializable, IDFetchable { self.score = json[JSONKey.score.rawValue].floatValue } - func update(json: JSON) { - self.initialize(json) - } - enum JSONKey: String { case id case user diff --git a/Stepic/Legacy/Model/Entities/Profile/Profile+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Profile/Profile+CoreDataProperties.swift index ef79396cd1..574d7d8d10 100644 --- a/Stepic/Legacy/Model/Entities/Profile/Profile+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Profile/Profile+CoreDataProperties.swift @@ -1,13 +1,4 @@ -// -// Profile+CoreDataProperties.swift -// Stepic -// -// Created by Vladislav Kiryukhin on 24.07.2017. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension Profile { @NSManaged var managedId: NSNumber? @@ -34,22 +25,6 @@ extension Profile { @NSManaged var managedUserActivity: UserActivityEntity? - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "Profile") - } - - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "Profile", in: CoreDataHelper.shared.context)! - } - - convenience init() { - self.init(entity: Profile.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { set(newId) { self.managedId = newId as NSNumber? diff --git a/Stepic/Legacy/Model/Entities/Profile/Profile.swift b/Stepic/Legacy/Model/Entities/Profile/Profile.swift index 7c47711d82..fd16a0649f 100644 --- a/Stepic/Legacy/Model/Entities/Profile/Profile.swift +++ b/Stepic/Legacy/Model/Entities/Profile/Profile.swift @@ -1,18 +1,13 @@ -// -// Profile.swift -// Stepic -// -// Created by Vladislav Kiryukhin on 24.07.2017. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class Profile: NSManagedObject, JSONSerializable { +final class Profile: NSManagedObject, ManagedObject, JSONSerializable { typealias IdType = Int + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] + } + var json: JSON { [ JSONKey.id.rawValue: self.id, @@ -34,11 +29,11 @@ final class Profile: NSManagedObject, JSONSerializable { } required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].intValue self.firstName = json[JSONKey.firstName.rawValue].stringValue self.lastName = json[JSONKey.lastName.rawValue].stringValue @@ -58,10 +53,7 @@ final class Profile: NSManagedObject, JSONSerializable { self.emailAddressesArray = json[JSONKey.emailAddresses.rawValue].arrayObject as? [Int] ?? [] } - func update(json: JSON) { - self.initialize(json) - } - + @available(*, deprecated, message: "Legacy") static func fetchById(_ id: Int) -> [Profile]? { let request = NSFetchRequest(entityName: "Profile") let predicate = NSPredicate(format: "managedId== %@", id as NSNumber) diff --git a/Stepic/Legacy/Model/Entities/Progress/Progress+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Progress/Progress+CoreDataProperties.swift index 7f301a0ceb..bdfc297b6b 100644 --- a/Stepic/Legacy/Model/Entities/Progress/Progress+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Progress/Progress+CoreDataProperties.swift @@ -1,16 +1,4 @@ -// -// Progress+CoreDataProperties.swift -// Stepic -// -// Created by Alexander Karpov on 03.11.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// -// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu -// to delete and recreate this implementation file for your updated model. -// - import CoreData -import Foundation extension Progress { @NSManaged var managedId: String? @@ -27,18 +15,6 @@ extension Progress { @NSManaged var managedUnit: Unit? @NSManaged var managedCourse: Course? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "Progress", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "Progress") - } - - convenience init() { - self.init(entity: Progress.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: String { set(newId) { self.managedId = newId diff --git a/Stepic/Legacy/Model/Entities/Progress/Progress.swift b/Stepic/Legacy/Model/Entities/Progress/Progress.swift index 863f469fec..f52b8902b9 100644 --- a/Stepic/Legacy/Model/Entities/Progress/Progress.swift +++ b/Stepic/Legacy/Model/Entities/Progress/Progress.swift @@ -1,16 +1,7 @@ -// -// Progress.swift -// Stepic -// -// Created by Alexander Karpov on 03.11.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class Progress: NSManagedObject, JSONSerializable, IDFetchable { +final class Progress: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = String var json: JSON { @@ -25,12 +16,22 @@ final class Progress: NSManagedObject, JSONSerializable, IDFetchable { ] } + var completeRate: Float { + self.numberOfSteps != 0 + ? Float(self.numberOfStepsPassed) / Float(self.numberOfSteps) + : 1 + } + + var percentPassed: Float { + self.completeRate * 100 + } + required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].stringValue self.isPassed = json[JSONKey.isPassed.rawValue].boolValue self.score = json[JSONKey.score.rawValue].floatValue @@ -40,10 +41,6 @@ final class Progress: NSManagedObject, JSONSerializable, IDFetchable { self.lastViewed = json[JSONKey.lastViewed.rawValue].doubleValue } - func update(json: JSON) { - self.initialize(json) - } - func equals(_ object: Any?) -> Bool { guard let object = object as? Progress else { return false @@ -63,16 +60,6 @@ final class Progress: NSManagedObject, JSONSerializable, IDFetchable { return true } - var completeRate: Float { - self.numberOfSteps != 0 - ? Float(self.numberOfStepsPassed) / Float(self.numberOfSteps) - : 1 - } - - var percentPassed: Float { - self.completeRate * 100 - } - enum JSONKey: String { case id case score diff --git a/Stepic/Legacy/Model/Entities/Section/Section+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Section/Section+CoreDataProperties.swift index f59173afbf..56e4e749bb 100644 --- a/Stepic/Legacy/Model/Entities/Section/Section+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Section/Section+CoreDataProperties.swift @@ -1,16 +1,4 @@ -// -// Section+CoreDataProperties.swift -// Stepic -// -// Created by Alexander Karpov on 08.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// -// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu -// to delete and recreate this implementation file for your updated model. -// - import CoreData -import Foundation extension Section { @NSManaged var managedId: NSNumber? @@ -45,18 +33,6 @@ extension Section { @NSManaged var managedExamSession: ExamSession? @NSManaged var managedProctorSession: ProctorSession? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "Section", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest
{ - NSFetchRequest
(entityName: "Section") - } - - convenience init() { - self.init(entity: Section.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { set(newId) { self.managedId = newId as NSNumber? diff --git a/Stepic/Legacy/Model/Entities/Section/Section.swift b/Stepic/Legacy/Model/Entities/Section/Section.swift index dbce3d057a..4ec01644bf 100644 --- a/Stepic/Legacy/Model/Entities/Section/Section.swift +++ b/Stepic/Legacy/Model/Entities/Section/Section.swift @@ -1,17 +1,8 @@ -// -// Section.swift -// Stepic -// -// Created by Alexander Karpov on 08.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON @objc -final class Section: NSManagedObject, IDFetchable { +final class Section: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int var isReachable: Bool { @@ -108,11 +99,11 @@ final class Section: NSManagedObject, IDFetchable { } required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].intValue self.title = json[JSONKey.title.rawValue].stringValue self.position = json[JSONKey.position.rawValue].intValue @@ -141,10 +132,7 @@ final class Section: NSManagedObject, IDFetchable { self.hardDeadline = Parser.dateFromTimedateJSON(json[JSONKey.hardDeadline.rawValue]) } - func update(json: JSON) { - self.initialize(json) - } - + @available(*, deprecated, message: "Legacy") static func fetch(_ ids: [IdType]) -> [Section] { let request = NSFetchRequest(entityName: "Section") let idPredicates = ids.map { NSPredicate(format: "managedId == %@", $0 as NSNumber) } @@ -162,6 +150,7 @@ final class Section: NSManagedObject, IDFetchable { return sections } + @available(*, deprecated, message: "Legacy") static func getSections(_ id: Int) throws -> [Section] { let request = NSFetchRequest(entityName: "Section") @@ -182,6 +171,7 @@ final class Section: NSManagedObject, IDFetchable { } } + @available(*, deprecated, message: "Legacy") func loadUnits(success: @escaping (() -> Void), error errorHandler: @escaping (() -> Void)) { if self.unitsArray.count == 0 { success() @@ -212,7 +202,7 @@ final class Section: NSManagedObject, IDFetchable { } var wasError = false - let errorWhileDownloading : () -> Void = { + let errorWhileDownloading: () -> Void = { if !wasError { wasError = true errorHandler() @@ -245,6 +235,7 @@ final class Section: NSManagedObject, IDFetchable { } } + @available(*, deprecated, message: "Legacy") func loadProgressesForUnits( units: [Unit], completion: @escaping (() -> Void), @@ -267,7 +258,7 @@ final class Section: NSManagedObject, IDFetchable { refreshMode: .update, success: { newProgresses -> Void in progresses = Sorter.sort(newProgresses, byIds: progressIds) - for i in 0 ..< min(units.count, progresses.count) { + for i in 0.. Void), @@ -303,7 +295,7 @@ final class Section: NSManagedObject, IDFetchable { success: { newLessons in lessons = Sorter.sort(newLessons, byIds: lessonIds) - for i in 0 ..< units.count { + for i in 0.. { - NSFetchRequest(entityName: "SocialProfile") - } - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { get { self.managedId?.intValue ?? -1 diff --git a/Stepic/Legacy/Model/Entities/SocialProfile/SocialProfile.swift b/Stepic/Legacy/Model/Entities/SocialProfile/SocialProfile.swift index 9153b28b87..48ceb3012b 100644 --- a/Stepic/Legacy/Model/Entities/SocialProfile/SocialProfile.swift +++ b/Stepic/Legacy/Model/Entities/SocialProfile/SocialProfile.swift @@ -1,10 +1,13 @@ import CoreData -import Foundation import SwiftyJSON -final class SocialProfile: NSManagedObject, JSONSerializable, IDFetchable { +final class SocialProfile: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] + } + var json: JSON { [ JSONKey.id.rawValue: self.id, @@ -20,11 +23,11 @@ final class SocialProfile: NSManagedObject, JSONSerializable, IDFetchable { } required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].intValue self.userID = json[JSONKey.user.rawValue].intValue self.providerString = json[JSONKey.provider.rawValue].stringValue @@ -32,10 +35,6 @@ final class SocialProfile: NSManagedObject, JSONSerializable, IDFetchable { self.urlString = json[JSONKey.url.rawValue].stringValue } - func update(json: JSON) { - self.initialize(json) - } - enum JSONKey: String { case id case user diff --git a/Stepic/Legacy/Model/Entities/Step/Step+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Step/Step+CoreDataProperties.swift index 043ae504be..3125681779 100644 --- a/Stepic/Legacy/Model/Entities/Step/Step+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Step/Step+CoreDataProperties.swift @@ -1,16 +1,4 @@ -// -// Step+CoreDataProperties.swift -// Stepic -// -// Created by Alexander Karpov on 12.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// -// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu -// to delete and recreate this implementation file for your updated model. -// - import CoreData -import Foundation extension Step { @NSManaged var managedId: NSNumber? @@ -40,18 +28,6 @@ extension Step { @NSManaged var managedDiscussionThreadsArray: NSObject? @NSManaged var managedDiscussionThreads: NSOrderedSet? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "Step", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "Step") - } - - convenience init() { - self.init(entity: Step.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { get { self.managedId?.intValue ?? -1 diff --git a/Stepic/Legacy/Model/Entities/Step/Step.swift b/Stepic/Legacy/Model/Entities/Step/Step.swift index ad860abf78..683dc9b0bd 100644 --- a/Stepic/Legacy/Model/Entities/Step/Step.swift +++ b/Stepic/Legacy/Model/Entities/Step/Step.swift @@ -1,16 +1,7 @@ -// -// Step.swift -// Stepic -// -// Created by Alexander Karpov on 12.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class Step: NSManagedObject, IDFetchable { +final class Step: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int var needsPlanType: CourseType? { @@ -22,7 +13,7 @@ final class Step: NSManagedObject, IDFetchable { } required convenience init(json: JSON) { - self.init() + self.init(entity: Step.entity, insertInto: CoreDataHelper.shared.context) self.initialize(json) self.block = Block(json: json[JSONKey.block.rawValue]) } @@ -108,6 +99,7 @@ final class Step: NSManagedObject, IDFetchable { return true } + @available(*, deprecated, message: "Legacy") static func getStepWithID(_ id: IdType, unitID: Unit.IdType? = nil) -> Step? { let request = NSFetchRequest(entityName: "Step") let predicate = NSPredicate(format: "managedId== %@", id as NSNumber) diff --git a/Stepic/Legacy/Model/Entities/StepOptions/StepOptions+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/StepOptions/StepOptions+CoreDataProperties.swift index dabb22504a..a6eb54178f 100644 --- a/Stepic/Legacy/Model/Entities/StepOptions/StepOptions+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/StepOptions/StepOptions+CoreDataProperties.swift @@ -1,13 +1,4 @@ -// -// StepOptions+CoreDataProperties.swift -// Stepic -// -// Created by Ostrenkiy on 30.05.17. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation extension StepOptions { @NSManaged var managedExecutionTimeLimit: NSNumber? @@ -18,18 +9,6 @@ extension StepOptions { @NSManaged var managedTemplates: NSOrderedSet? @NSManaged var managedSamples: NSOrderedSet? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "StepOptions", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "StepOptions") - } - - convenience init() { - self.init(entity: StepOptions.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var executionTimeLimit: Double { get { self.managedExecutionTimeLimit?.doubleValue ?? 0.0 diff --git a/Stepic/Legacy/Model/Entities/StepOptions/StepOptions.swift b/Stepic/Legacy/Model/Entities/StepOptions/StepOptions.swift index 3450022819..65bd878825 100644 --- a/Stepic/Legacy/Model/Entities/StepOptions/StepOptions.swift +++ b/Stepic/Legacy/Model/Entities/StepOptions/StepOptions.swift @@ -1,16 +1,7 @@ -// -// StepOptions.swift -// Stepic -// -// Created by Ostrenkiy on 30.05.17. -// Copyright © 2017 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class StepOptions: NSManagedObject { +final class StepOptions: NSManagedObject, ManagedObject { var languages: [CodeLanguage] { self.limits.compactMap { $0.language } } @@ -20,15 +11,11 @@ final class StepOptions: NSManagedObject { } required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } func update(json: JSON) { - self.initialize(json) - } - - func initialize(_ json: JSON) { self.executionTimeLimit = json[JSONKey.executionTimeLimit.rawValue].doubleValue self.executionMemoryLimit = json[JSONKey.executionMemoryLimit.rawValue].doubleValue self.isRunUserCodeAllowed = json[JSONKey.isRunUserCodeAllowed.rawValue].boolValue diff --git a/Stepic/Legacy/Model/Entities/StoryPartReaction/StoryPartReaction+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/StoryPartReaction/StoryPartReaction+CoreDataProperties.swift index e969caa7b9..5d74e7db11 100644 --- a/Stepic/Legacy/Model/Entities/StoryPartReaction/StoryPartReaction+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/StoryPartReaction/StoryPartReaction+CoreDataProperties.swift @@ -1,27 +1,10 @@ import CoreData -import Foundation extension StoryPartReaction { @NSManaged var managedStoryId: NSNumber? @NSManaged var managedPosition: NSNumber? @NSManaged var managedReaction: String? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "StoryPartReaction", in: CoreDataHelper.shared.context)! - } - - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedPosition), ascending: true)] - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "StoryPartReaction") - } - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var storyID: Int { get { self.managedStoryId?.intValue ?? 0 diff --git a/Stepic/Legacy/Model/Entities/StoryPartReaction/StoryPartReaction.swift b/Stepic/Legacy/Model/Entities/StoryPartReaction/StoryPartReaction.swift index 6976d5af34..78e3c1c6eb 100644 --- a/Stepic/Legacy/Model/Entities/StoryPartReaction/StoryPartReaction.swift +++ b/Stepic/Legacy/Model/Entities/StoryPartReaction/StoryPartReaction.swift @@ -1,7 +1,10 @@ import CoreData -import Foundation -final class StoryPartReaction: NSManagedObject { +final class StoryPartReaction: NSManagedObject, ManagedObject { + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedPosition), ascending: true)] + } + var storyReaction: StoryReaction? { if let reaction = self.reaction { return StoryReaction(rawValue: reaction) @@ -13,22 +16,18 @@ final class StoryPartReaction: NSManagedObject { "StoryPartReaction(storyID: \(self.storyID), position: \(self.position), reaction: \(String(describing: self.reaction))" } - convenience init( + static func insert( + into context: NSManagedObjectContext, storyID: Int, position: Int, - reaction: StoryReaction, - managedObjectContext: NSManagedObjectContext - ) { - guard let entity = NSEntityDescription.entity( - forEntityName: "StoryPartReaction", in: managedObjectContext - ) else { - fatalError("Wrong object type") - } + reaction: StoryReaction + ) -> StoryPartReaction { + let object: StoryPartReaction = context.insertObject() - self.init(entity: entity, insertInto: managedObjectContext) + object.storyID = storyID + object.position = position + object.reaction = reaction.rawValue - self.storyID = storyID - self.position = position - self.reaction = reaction.rawValue + return object } } diff --git a/Stepic/Legacy/Model/Entities/Submission/SubmissionEntity+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Submission/SubmissionEntity+CoreDataProperties.swift index 081727994c..e432d72cef 100644 --- a/Stepic/Legacy/Model/Entities/Submission/SubmissionEntity+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Submission/SubmissionEntity+CoreDataProperties.swift @@ -1,5 +1,4 @@ import CoreData -import Foundation extension SubmissionEntity { @NSManaged var managedID: NSNumber @@ -16,11 +15,101 @@ extension SubmissionEntity { @NSManaged var managedAttempt: AttemptEntity? - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedID), ascending: false)] + var id: Int { + get { + self.managedID.intValue + } + set { + self.managedID = NSNumber(value: newValue) + } } - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "SubmissionEntity") + var attemptID: AttemptEntity.IdType { + get { + self.managedAttemptID.intValue + } + set { + self.managedAttemptID = NSNumber(value: newValue) + } + } + + var reply: Reply? { + get { + self.managedReply + } + set { + self.managedReply = newValue + } + } + + var isLocal: Bool { + get { + self.managedLocal.boolValue + } + set { + self.managedLocal = NSNumber(value: newValue) + } + } + + var score: Float { + get { + self.managedScore.floatValue + } + set { + self.managedScore = NSNumber(value: newValue) + } + } + + var hint: String? { + get { + self.managedHint + } + set { + self.managedHint = newValue + } + } + + var statusString: String? { + get { + self.managedStatus + } + set { + self.managedStatus = newValue + } + } + + var status: SubmissionStatus? { + if let statusString = self.statusString { + return SubmissionStatus(rawValue: statusString) + } else { + return nil + } + } + + var feedback: SubmissionFeedback? { + get { + self.managedFeedback + } + set { + self.managedFeedback = newValue + } + } + + var time: Date { + get { + self.managedTime ?? Date() + } + set { + self.managedTime = newValue + } + } + + var attempt: AttemptEntity? { + get { + self.managedAttempt + } + set { + self.managedAttempt = newValue + } } } diff --git a/Stepic/Legacy/Model/Entities/Submission/SubmissionEntity.swift b/Stepic/Legacy/Model/Entities/Submission/SubmissionEntity.swift index ee8be4e77a..c17643f6fd 100644 --- a/Stepic/Legacy/Model/Entities/Submission/SubmissionEntity.swift +++ b/Stepic/Legacy/Model/Entities/Submission/SubmissionEntity.swift @@ -1,115 +1,12 @@ import CoreData -import Foundation -final class SubmissionEntity: NSManagedObject { +final class SubmissionEntity: NSManagedObject, ManagedObject, Identifiable { typealias IdType = Int - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "SubmissionEntity", in: CoreDataHelper.shared.context)! - } - - var id: Int { - get { - self.managedID.intValue - } - set { - self.managedID = NSNumber(value: newValue) - } - } - - var attemptID: AttemptEntity.IdType { - get { - self.managedAttemptID.intValue - } - set { - self.managedAttemptID = NSNumber(value: newValue) - } - } - - var reply: Reply? { - get { - self.managedReply - } - set { - self.managedReply = newValue - } - } - - var isLocal: Bool { - get { - self.managedLocal.boolValue - } - set { - self.managedLocal = NSNumber(value: newValue) - } - } - - var score: Float { - get { - self.managedScore.floatValue - } - set { - self.managedScore = NSNumber(value: newValue) - } - } - - var hint: String? { - get { - self.managedHint - } - set { - self.managedHint = newValue - } - } - - var statusString: String? { - get { - self.managedStatus - } - set { - self.managedStatus = newValue - } - } - - var status: SubmissionStatus? { - if let statusString = self.statusString { - return SubmissionStatus(rawValue: statusString) - } else { - return nil - } - } - - var feedback: SubmissionFeedback? { - get { - self.managedFeedback - } - set { - self.managedFeedback = newValue - } - } - - var time: Date { - get { - self.managedTime ?? Date() - } - set { - self.managedTime = newValue - } - } - - var attempt: AttemptEntity? { - get { - self.managedAttempt - } - set { - self.managedAttempt = newValue - } - } - - // MARK: Init + static var idAttributeName: String { #keyPath(managedID) } - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedID), ascending: false)] } } @@ -131,23 +28,19 @@ extension SubmissionEntity { ) } - convenience init(submission: Submission, managedObjectContext: NSManagedObjectContext) { - guard let entity = NSEntityDescription.entity( - forEntityName: "SubmissionEntity", in: managedObjectContext - ) else { - fatalError("Wrong object type") - } + static func insert(into context: NSManagedObjectContext, submission: Submission) -> SubmissionEntity { + let object: SubmissionEntity = context.insertObject() - self.init(entity: entity, insertInto: managedObjectContext) + object.id = submission.id + object.attemptID = submission.attemptID + object.reply = submission.reply + object.isLocal = submission.isLocal + object.score = submission.score + object.hint = submission.hint + object.statusString = submission.statusString + object.feedback = submission.feedback + object.time = submission.time - self.id = submission.id - self.attemptID = submission.attemptID - self.reply = submission.reply - self.isLocal = submission.isLocal - self.score = submission.score - self.hint = submission.hint - self.statusString = submission.statusString - self.feedback = submission.feedback - self.time = submission.time + return object } } diff --git a/Stepic/Legacy/Model/Entities/Unit/Unit+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Unit/Unit+CoreDataProperties.swift index c38cf3a6f4..40a92a6bab 100644 --- a/Stepic/Legacy/Model/Entities/Unit/Unit+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Unit/Unit+CoreDataProperties.swift @@ -1,16 +1,4 @@ -// -// Unit+CoreDataProperties.swift -// Stepic -// -// Created by Alexander Karpov on 09.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// -// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu -// to delete and recreate this implementation file for your updated model. -// - import CoreData -import Foundation extension Unit { @NSManaged var managedId: NSNumber? @@ -31,18 +19,6 @@ extension Unit { @NSManaged var managedAssignments: NSOrderedSet? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "Unit", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "Unit") - } - - convenience init() { - self.init(entity: Unit.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { set(newId) { self.managedId = newId as NSNumber? diff --git a/Stepic/Legacy/Model/Entities/Unit/Unit.swift b/Stepic/Legacy/Model/Entities/Unit/Unit.swift index b367de4954..7b3a4556df 100644 --- a/Stepic/Legacy/Model/Entities/Unit/Unit.swift +++ b/Stepic/Legacy/Model/Entities/Unit/Unit.swift @@ -1,58 +1,30 @@ -// -// Unit.swift -// Stepic -// -// Created by Alexander Karpov on 09.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON -final class Unit: NSManagedObject, IDFetchable { +final class Unit: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int required convenience init(json: JSON) { - self.init() - initialize(json) - } - - func initialize(_ json: JSON) { - id = json["id"].intValue - position = json["position"].intValue - isActive = json["is_active"].boolValue - lessonId = json["lesson"].intValue - progressId = json["progress"].string - sectionId = json["section"].intValue - - assignmentsArray = json["assignments"].arrayObject as! [Int] - - beginDate = Parser.dateFromTimedateJSON(json["begin_date"]) - softDeadline = Parser.dateFromTimedateJSON(json["soft_deadline"]) - hardDeadline = Parser.dateFromTimedateJSON(json["hard_deadline"]) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } func update(json: JSON) { - initialize(json) - } - - func loadAssignments(_ completion: @escaping () -> Void, errorHandler: @escaping () -> Void) { - _ = ApiDataDownloader.assignments.retrieve( - ids: self.assignmentsArray, - existing: self.assignments, - refreshMode: .update, - success: { newAssignments in - self.assignments = Sorter.sort(newAssignments, byIds: self.assignmentsArray) - completion() - }, - error: { _ in - print("Error while downloading assignments") - errorHandler() - } - ) + self.id = json["id"].intValue + self.position = json["position"].intValue + self.isActive = json["is_active"].boolValue + self.lessonId = json["lesson"].intValue + self.progressId = json["progress"].string + self.sectionId = json["section"].intValue + + self.assignmentsArray = json["assignments"].arrayObject as! [Int] + + self.beginDate = Parser.dateFromTimedateJSON(json["begin_date"]) + self.softDeadline = Parser.dateFromTimedateJSON(json["soft_deadline"]) + self.hardDeadline = Parser.dateFromTimedateJSON(json["hard_deadline"]) } + @available(*, deprecated, message: "Legacy") static func getUnit(id: Int) -> Unit? { let request = NSFetchRequest(entityName: "Unit") diff --git a/Stepic/Legacy/Model/Entities/User/User+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/User/User+CoreDataProperties.swift index 0ecc72d820..c5597034cc 100644 --- a/Stepic/Legacy/Model/Entities/User/User+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/User/User+CoreDataProperties.swift @@ -1,16 +1,4 @@ -// -// User+CoreDataProperties.swift -// Stepic -// -// Created by Alexander Karpov on 03.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// -// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu -// to delete and recreate this implementation file for your updated model. -// - import CoreData -import Foundation extension User { @NSManaged var managedId: NSNumber? @@ -49,22 +37,6 @@ extension User { @NSManaged var managedProfileEntity: Profile? @NSManaged var managedUserCourse: UserCourse? - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "User") - } - - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "User", in: CoreDataHelper.shared.context)! - } - - convenience init() { - self.init(entity: User.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { set(value) { managedId = value as NSNumber? diff --git a/Stepic/Legacy/Model/Entities/User/User.swift b/Stepic/Legacy/Model/Entities/User/User.swift index cb1c0c692e..2cfcf2e68e 100644 --- a/Stepic/Legacy/Model/Entities/User/User.swift +++ b/Stepic/Legacy/Model/Entities/User/User.swift @@ -1,19 +1,14 @@ -// -// User.swift -// Stepic -// -// Created by Alexander Karpov on 03.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// - import CoreData -import Foundation import SwiftyJSON @objc -final class User: NSManagedObject, IDFetchable { +final class User: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] + } + /// Returns true if joinDate is less than in 5 minutes from now. var didJustRegister: Bool { if let joinDate = self.joinDate { @@ -23,11 +18,11 @@ final class User: NSManagedObject, IDFetchable { } required convenience init(json: JSON) { - self.init() - self.initialize(json) + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) + self.update(json: json) } - func initialize(_ json: JSON) { + func update(json: JSON) { self.id = json[JSONKey.id.rawValue].intValue self.profile = json[JSONKey.profile.rawValue].intValue self.isPrivate = json[JSONKey.isPrivate.rawValue].boolValue @@ -53,10 +48,7 @@ final class User: NSManagedObject, IDFetchable { self.socialProfilesArray = json[JSONKey.socialProfiles.rawValue].arrayObject as? [Int] ?? [] } - func update(json: JSON) { - self.initialize(json) - } - + @available(*, deprecated, message: "Legacy") static func fetchById(_ id: Int) -> [User]? { let request = NSFetchRequest(entityName: "User") @@ -72,6 +64,7 @@ final class User: NSManagedObject, IDFetchable { } } + @available(*, deprecated, message: "Legacy") static func removeAllExcept(_ user: User) { if let fetchedUsers = fetchById(user.id) { for fetchedUser in fetchedUsers { @@ -83,6 +76,7 @@ final class User: NSManagedObject, IDFetchable { } } + @available(*, deprecated, message: "Legacy") static func fetch(_ ids: [Int]) -> [User] { let request = NSFetchRequest(entityName: "User") diff --git a/Stepic/Legacy/Model/Entities/UserActivity/UserActivityEntity+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/UserActivity/UserActivityEntity+CoreDataProperties.swift index fe81eeca21..113806f2e0 100644 --- a/Stepic/Legacy/Model/Entities/UserActivity/UserActivityEntity+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/UserActivity/UserActivityEntity+CoreDataProperties.swift @@ -1,5 +1,4 @@ import CoreData -import Foundation extension UserActivityEntity { @NSManaged var managedId: NSNumber? @@ -7,12 +6,22 @@ extension UserActivityEntity { @NSManaged var managedProfile: Profile? - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] + var id: Int { + get { + self.managedId?.intValue ?? -1 + } + set { + self.managedId = NSNumber(value: newValue) + } } - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "UserActivityEntity") + var pins: [Int] { + get { + self.managedPinsArray as? [Int] ?? [] + } + set { + self.managedPinsArray = NSArray(array: newValue) + } } var profile: Profile? { diff --git a/Stepic/Legacy/Model/Entities/UserActivity/UserActivityEntity.swift b/Stepic/Legacy/Model/Entities/UserActivity/UserActivityEntity.swift index 937b51a0ae..58d7f405a2 100644 --- a/Stepic/Legacy/Model/Entities/UserActivity/UserActivityEntity.swift +++ b/Stepic/Legacy/Model/Entities/UserActivity/UserActivityEntity.swift @@ -1,35 +1,10 @@ import CoreData -import Foundation -final class UserActivityEntity: NSManagedObject { +final class UserActivityEntity: NSManagedObject, ManagedObject, Identifiable { typealias IdType = Int - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "UserActivityEntity", in: CoreDataHelper.shared.context)! - } - - var id: Int { - get { - self.managedId?.intValue ?? -1 - } - set { - self.managedId = NSNumber(value: newValue) - } - } - - var pins: [Int] { - get { - self.managedPinsArray as? [Int] ?? [] - } - set { - self.managedPinsArray = NSArray(array: newValue) - } - } - - // MARK: Init - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] } } @@ -39,4 +14,13 @@ extension UserActivityEntity { var plainObject: UserActivity { UserActivity(id: self.id, pins: self.pins) } + + static func insert(into context: NSManagedObjectContext, userActivity: UserActivity) -> UserActivityEntity { + let object: UserActivityEntity = context.insertObject() + + object.id = userActivity.id + object.pins = userActivity.pins + + return object + } } diff --git a/Stepic/Legacy/Model/Entities/UserCourse/UserCourse+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/UserCourse/UserCourse+CoreDataProperties.swift index 9ec4d1429d..502546badd 100644 --- a/Stepic/Legacy/Model/Entities/UserCourse/UserCourse+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/UserCourse/UserCourse+CoreDataProperties.swift @@ -1,5 +1,4 @@ import CoreData -import Foundation extension UserCourse { @NSManaged var managedId: NSNumber? @@ -13,24 +12,6 @@ extension UserCourse { @NSManaged var managedUser: User? @NSManaged var managedCourse: Course? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "UserCourse", in: CoreDataHelper.shared.context)! - } - - static var defaultSortDescriptors: [NSSortDescriptor] { - [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] - } - - static var fetchRequest: NSFetchRequest { - NSFetchRequest(entityName: "UserCourse") - } - - static var observableKeys: Set = ["managedIsFavorite", "managedIsArchived", "managedCourse"] - - convenience init() { - self.init(entity: Self.oldEntity, insertInto: CoreDataHelper.shared.context) - } - var id: Int { get { self.managedId?.intValue ?? 0 diff --git a/Stepic/Legacy/Model/Entities/UserCourse/UserCourse.swift b/Stepic/Legacy/Model/Entities/UserCourse/UserCourse.swift index 15f5c94dd0..e41770c814 100644 --- a/Stepic/Legacy/Model/Entities/UserCourse/UserCourse.swift +++ b/Stepic/Legacy/Model/Entities/UserCourse/UserCourse.swift @@ -1,10 +1,15 @@ import CoreData -import Foundation import SwiftyJSON -final class UserCourse: NSManagedObject, JSONSerializable, IDFetchable { +final class UserCourse: NSManagedObject, ManagedObject, IDFetchable { typealias IdType = Int + static var defaultSortDescriptors: [NSSortDescriptor] { + [NSSortDescriptor(key: #keyPath(managedId), ascending: false)] + } + + static var observableKeys: Set = ["managedIsFavorite", "managedIsArchived", "managedCourse"] + var json: JSON { [ JSONKey.isFavorite.rawValue: self.isFavorite, @@ -14,7 +19,7 @@ final class UserCourse: NSManagedObject, JSONSerializable, IDFetchable { } required convenience init(json: JSON) { - self.init() + self.init(entity: Self.entity, insertInto: CoreDataHelper.shared.context) self.update(json: json) NotificationCenter.default.post(name: .userCourseDidCreateNotification, object: self) } diff --git a/Stepic/Legacy/Model/Entities/Video/Video+CoreDataProperties.swift b/Stepic/Legacy/Model/Entities/Video/Video+CoreDataProperties.swift index 338d89b83d..a0409376c3 100644 --- a/Stepic/Legacy/Model/Entities/Video/Video+CoreDataProperties.swift +++ b/Stepic/Legacy/Model/Entities/Video/Video+CoreDataProperties.swift @@ -1,16 +1,4 @@ -// -// Video+CoreDataProperties.swift -// Stepic -// -// Created by Alexander Karpov on 14.10.15. -// Copyright © 2015 Alex Karpov. All rights reserved. -// -// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu -// to delete and recreate this implementation file for your updated model. -// - import CoreData -import Foundation extension Video { @NSManaged var managedId: NSNumber? @@ -22,18 +10,6 @@ extension Video { // @NSManaged var managedCachedPath: String? @NSManaged var managedCachedQuality: NSNumber? - static var oldEntity: NSEntityDescription { - NSEntityDescription.entity(forEntityName: "Video", in: CoreDataHelper.shared.context)! - } - - static var fetchRequest: NSFetchRequest